Win a copy of Murach's Python Programming this week in the Jython/Python forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Static blocks and multi threading  RSS feed

 
Kamatchi Kamaka
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 399
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
See12.4.2 Detailed Initialization Procedure in the Java Language Specification.
 
Kamatchi Kamaka
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!