[concurrency-interest] static initializers and threads

Joshua Bloch josh at bloch.us
Fri May 26 17:14:50 EDT 2006


I'm gonna go with Hanson on this.  If anyone has run the program,
can't figure out why it does what it does, and asks me, I will send
them the solution, but I won't post it for a few days:)

            Josh

On 5/26/06, Hanson Char <hanson.char at gmail.com> wrote:
> > 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