File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Threads and Synchronization and the fly likes Static blocks and multi threading Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login
JavaRanch » Java Forums » Java » Threads and Synchronization
Reply Bookmark "Static blocks and multi threading" Watch "Static blocks and multi threading" New topic
Author

Static blocks and multi threading

Kamatchi Kamaka
Greenhorn

Joined: Apr 26, 2002
Posts: 2
Hi,
Assume the following scenario:
In a commonly accessed class, I have a static block which initialises a class variable (say a Hashtable). Now this initialisation takes a very long time (for example I populate this hashtable with all country codes as the keys and related information in a Vector as values - basically its one bloody huge hashtable!!!). Assume this class has a getter methods that returns a reference to this class variable. When the first thread accesses this getter method, the static block starts to execute (assume this is the first entry point into this class). By the time the static block is fully completed, assume a second thread accesses the same getter method. Note that this getter method is not synchronized. So multiple thread can call for this class variable via the getter method. In the case described above, will the second thread get a half baked reference to the class variable or is the JVM intelligent enough to complete the static block before it gives a reference of the class variable. According to the behaviour we have observed, it looks like the JVM services threads only after fully completing the static block. Please, can anyone let me know or point me to some resource to confirm this.
Thanks,
Kamatchi
John Dale
Ranch Hand

Joined: Feb 22, 2001
Posts: 399
See12.4.2 Detailed Initialization Procedure in the Java Language Specification.
Kamatchi Kamaka
Greenhorn

Joined: Apr 26, 2002
Posts: 2
Hi John,
Thanks for that pointer, that clears up the lot of questions I had. So, in a nutshell, the JVM is good enough to ensure that no class or its memebers shall have an erroneous state while one thread is initialising it and another thread is requesting for a handle. The onus is on the JVM and not on the developer to ensure this, I hope I have my conclusion right. So in my scenario, there is no way that I can get a handle to a badly initialised reference of the hashtable.
Thanks,
Kamatchi
 
IntelliJ Java IDE
 
subject: Static blocks and multi threading
 
Threads others viewed
classes
Usefulness of this code....
When is a String a constant?
Basic Java
static block and static variable?
WebSphere development made easy
without the weight of IBM tools
http://www.myeclipseide.com