This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
The moose likes Java in General and the fly likes Using static Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Using static" Watch "Using static" New topic
Author

Using static

Paul Keohan
Ranch Hand

Joined: Mar 15, 2000
Posts: 411
Is there a preference to using a static initializer to instantiate an object or just declaring it as static?
1.
MyObject obj;
static
{
MyObject obj = new MyObject();
}


2.
public static MyObject obj = new MyObject();
Which is better?
Jim Yingst
Wanderer
Sheriff

Joined: Jan 30, 2000
Posts: 18671
Usually, if you can fit the initialization onto a single line as part of the declaration, that's easier. The most common reason to require a static initializer block is to invoke a method which throws an exception which you must catch. You can't possibly do this in one line, so you must use a static block.


"I'm not back." - Bill Harding, Twister
Ilja Preuss
author
Sheriff

Joined: Jul 11, 2001
Posts: 14112
Notice that a static block is NOT a substitute for the static modifier of a field. You can also inititalize a non-static field 'inline' and a static field in a static block.


The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus
Jim Yingst
Wanderer
Sheriff

Joined: Jan 30, 2000
Posts: 18671
Oops - I didn't notice that obj wasn't even static in the first example. Yeah - those are completely different. First decide if you want the field to be static or not - then decide how to initialize it.
Ganesh Ram
Ranch Hand

Joined: Jul 20, 2001
Posts: 33
The static block would get called only if the value is referred.
This way you can prevent loading unwanted values. This is very useful in scenarios where things are configurable.
Ilja Preuss
author
Sheriff

Joined: Jul 11, 2001
Posts: 14112
Originally posted by Ganesh Ram:
The static block would get called only if the value is referred.
This way you can prevent loading unwanted values. This is very useful in scenarios where things are configurable.

Huh? The static block will be executed when the class gets loaded. I don't understand what you are referring to.
Jim Yingst
Wanderer
Sheriff

Joined: Jan 30, 2000
Posts: 18671
I'm guessing that Ganesh is referring to a form of lazy instantiation which avoids the overhead of synchronization which is often associated with lazy instantiation:
<code><pre> private static class FieldHolder {
public static final Object field = timeConsumingInitializer();
}

public static Object getField() {
return FieldHolder.field;
}
</pre></code>
Here the FieldHolder class will not get loaded until the first time getField() is called. Once it's loaded, subsequent accesses will have negligible overhead. This trick only works for static fields, but it works well for those.
[This message has been edited by Jim Yingst (edited August 04, 2001).]
Paul Keohan
Ranch Hand

Joined: Mar 15, 2000
Posts: 411
Thanks for all the responses. Another question that comes to mind with static : I uderstand as soon as a class is referenced to, any code in it's static initializer block or any static objects are immediately created. What if the objects process a lot of code? Will the object be 'unreferenceable' until all processes have completed, even if they take several seconds? Something tells me you should keep static code very short and simple but I'd like to hear some opinions.
Jim Yingst
Wanderer
Sheriff

Joined: Jan 30, 2000
Posts: 18671
Any threads which attempt to use the class will be forced to wait until the class loading is clompleted, which includes running all static initializers. There is no danger that the system will reference anything before the class loading is completed. The idea behind lazy instantiation is that there's an initialization process that does take more time than you'd like, but you're stuck with it. If the class is going to be used, you're going to have to wait out that time at some point - whether it's at program start-up, or in the middle of a run. But if you don't know whether or not the object will really be needed in a given run, you might as well wait to initialize it until you know for sure it is needed. Now, there are some types of programs where this approach won't work - for a real-time system, it may be much better to have all the "wait time" at the beginning of the program, so once it's up and running, response time is reliable. But for many others, deferred instantiation makes a lot of sense.
Jose Botella
Ranch Hand

Joined: Jul 03, 2001
Posts: 2120
static final literals are not initialized within < clinit> but before it.
To check that set a breakpoint with jdb in the < clinit> method and print the fields.
is this due to the fact that they are not going to be inititialized by <clinit> but their fields must be initialized when this method returns?

[This message has been edited by Jim Yingst (edited August 08, 2001).]


SCJP2. Please Indent your code using UBB Code
Jose Botella
Ranch Hand

Joined: Jul 03, 2001
Posts: 2120
In the previous post I wrote a word tha didn�t appear because was between less and greater than signs. The word was "clinit" meaning the class initialization method.
Jim Yingst
Wanderer
Sheriff

Joined: Jan 30, 2000
Posts: 18671
I fixed this by inserting a space after the "<". (You can also replace < with &amp; if you prefer.) You can edit you own post after you've posted it by using the icon at the top of your post.

[This message has been edited by Jim Yingst (edited August 08, 2001).]
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Using static
 
Similar Threads
static method
Static object
pass reference variable in method
Data structure to cache objects
finalize() problem