[concurrency-interest] static initializers and threads

Venkatesh Prasad Ranganath vranganath at sbcglobal.net
Fri May 26 15:37:47 EDT 2006


On Thu, 2006-05-25 at 21:47 -0700, Joshua Bloch wrote:
> Now the quiz.  What does this program print, and why?
> 
> public class Lazy {
>     private static boolean initialized = false;
>     static {
>         Thread t = new Thread(new Runnable() {
>             public void run() {
>                 initialized = true;
>             }
>         });
>         t.start();
>         try {
>             t.join();
>         } catch (InterruptedException e) {
>             throw new AssertionError(e);
>         }
>     }
>     public static void main(String[] args) {
>         System.out.println(initialized);
>     }
> }
> 
> For the answer, see Puzzle 85 in "Java Puzzlers."

Due to the lexical ordering of static initializations and the
uninterrupted execution of the new thread and the join() invocation in
the static initializer will imply the program will print "true".  If the
latter conditions (any one) do not hold, then the program may print
"true" or "false".

For the sake of people who don't know the "Puzzlers", can you please
divulge the answer? :-)

--

Venkatesh Prasad Ranganath


More information about the Concurrency-interest mailing list