I want to initialize a static field but I can't get its value in a "static" way. I mean, I can't do:
So, I thought I could do this:
But this way I have a problem with thread-safety and initialization, so I thought I could do this:
Can you help me with this? I'm in the right way? Are there better ways to do it? Is it completely insane?
I suppose this is a common problem so there should be a "best practice" for it.
If you want a more realistic example, I can tell you why I want to do this: I want to create a static "constant" object that needs a value from a HttpServletRequest (I'm working with a Struts-based framework). Simplifying:
Setting a final static value from a constructor? So you instantiate one object, and set the value. Then you instantiate a second object, try to reset a final value, and hope the compiler won't notice . . .
Campbell Ritchie wrote:Setting a final static value from a constructor? So you instantiate one object, and set the value. Then you instantiate a second object, try to reset a final value, and hope the compiler won't notice . . .
I don't understand what you mean. It's not possible to initialize a final static field from a constructor. You have to initialize it inline or from a static block like:
Joined: Feb 13, 2009
Ulf Dittmer wrote:Why is there a problem with thread-safety? If it's static, then it should be initialized only once, not multiple times.
The field is initialized from a thread, so two threads might try to initialize it.
I made a mistake in my first post. I forgot to put the "static" keyword in methods. I'm going to fix it now.
Your version with the synchronized static set/get methods is probably the best you can do, given your goal.
But maybe we can take a step back: why do you need to do this, exactly? And given that this is in a web application, how can you ensure that no code will try to initialize it a second time? And why is it useful to have an HttpServletRequest live through the whole lifetime of that class without changing -- surely the class will live longer than a single request?