Machine-translated by Google. Questions are authored in English.
Top

Discussion

Sample63 is run - what will be the output?

public class Sample63
{
    static class Broken
    {
        Broken()
        {
            new Thread(() -> System.out.println(value)).start();
            value = 42;
        }

        int value;
    }

    public static void main(String[] args) throws InterruptedException
    {
        new Broken();
        Thread.sleep(200);
    }
}

  • A.0 always, because the field is read before it is assigned
  • B.A compile error, because a constructor may not start a thread
  • C.Either 0 or 42, because the reference escaped before construction finished
  • D.42 always, because the constructor completes before the thread runs

Answer: C

Starting a thread from inside the constructor publishes this before the object is finished, so the new thread may observe the field at its default value or at 42 depending on timing. Publishing a reference only after construction has completed is what avoids the race.

No comment is present. Be the first to comment.
Loading…

Post your comment

Please log in or register to post a comment.