Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Thread , How it comes the answer is A?

The question is from http://www.javacertifications.net/javacert/scjp1.6Mock.jsp

Questions no -20

What is the output for the below code ?

public class Test extends Thread
{   
    static String sName = "good";
    public static void main(String argv[])
    {
        Test t = new Test();
        t.nameTest(sName);
        System.out.println(sName);    
    }
    public void nameTest(String sName)
    {
        sName = sName + " idea ";
        start();
    }
    public void run()
    {
        for(int i=0;i  <  4; i++)
        {
            sName = sName + " " + i;

        }
    }
}

options A)good B)good idea C)good idea good idea Correct answer is : A

Explanations : Change value in local methods wouldn’t change in global in case of String ( because String object is immutable).

like image 983
komenan Avatar asked Jun 14 '26 12:06

komenan


2 Answers

None of the answers are correct, and there is no single correct answer.

The Question is very bad because it mixes two entirely separate problems:

  • The sName parameter of the nameTest() method hides the static variable of the same name, and changes to the local variable have no effect.
  • The nameTest() starts a thread which changes the static variable in its run() method, and the main() method prints the variable without waiting for that thread to finish. This is known as a race condition: it's pretty much coincidence which state of the variable will be printed - any of the following is possible:
    • good
    • good 0
    • good 0 1
    • good 0 1 2
    • good 0 1 2 3
like image 155
Michael Borgwardt Avatar answered Jun 16 '26 01:06

Michael Borgwardt


Note that method nameTest has a parameter String sName, which effectively shadows the static class member with the same name. So the line

sName = sName + " idea ";

refers to and modifies the local method parameter instead of the static class member. To access the class member from within the method, it should be qualified with the class name, i.e. Test.sName.

In the run method, the static sName member is modified, though, so eventually it becomes something like "good 0 1 2 3". However, there is a race condition between the main thread which (implicitly) starts the thread t then prints the value of sName, and the child thread which modifies the same value. Since there is no synchronization involved, it is entirely possible that the main thread prints the value before it is modified by the other thread (i.e. "good"). The outcome could also be "good 0", "good 0 1" etc. However, of all these, only "good" is listed. So A is the only possible answer.

like image 40
Péter Török Avatar answered Jun 16 '26 01:06

Péter Török