[concurrency-interest] static initializers and threads

Hanson Char hanson.char at gmail.com
Fri May 26 16:25:31 EDT 2006


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

For the sake of not killing the fun, please don't.

(Venkatesh, have you tried running the code to see ?)

H

On 5/26/06, Venkatesh Prasad Ranganath <vranganath at sbcglobal.net> wrote:
> 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
> _______________________________________________
> Concurrency-interest mailing list
> Concurrency-interest at altair.cs.oswego.edu
> http://altair.cs.oswego.edu/mailman/listinfo/concurrency-interest
>



More information about the Concurrency-interest mailing list