Java Programming - Threads - Discussion


What will be the output of the program?

public class SyncTest 
    public static void main (String [] args) 
        Thread t = new Thread() 
            Foo f = new Foo();
            public void run() 
class Foo 
    private int data = 23;
    public void increase(int amt) 
        int x = data;
        data = x + amt;
and assuming that data must be protected from corruption, what—if anything—can you add to the preceding code to ensure the integrity of data?

[A]. Synchronize the run method.
[B]. Wrap a synchronize(this) around the call to f.increase().
[C]. The existing code will cause a runtime exception.
[D]. Synchronize the increase() method

Answer: Option D


Option D is correct because synchronizing the code that actually does the increase will protect the code from being accessed by more than one thread at a time.

Option A is incorrect because synchronizing the run() method would stop other threads from running the run() method (a bad idea) but still would not prevent other threads with other runnables from accessing the increase() method.

Option B is incorrect for virtually the same reason as A—synchronizing the code that calls the increase() method does not prevent other code from calling the increase() method.

Dhawan said: (Jul 29, 2012)  
The class doesn't extends Thread or implement Runnable.

Gaurav said: (Jul 29, 2013)  
This question is vague.

As there is no need of synchronization, as each time a new thread is created, new foo() object is created and there will be no problem while accessing data from multiple threads.

Abhin said: (Apr 23, 2014)  
Thats correct @Gaurav. The foo object is created inside the anonymous class; and that object can't be used by other thread; infact a new foo object is created every time.

Ron said: (Jul 10, 2015)  
Same point @Gaurav, 'Foo f = new Foo ();' should have been declared outside the t thread for the explanation to be valid.

Koushik Mukherjee said: (Aug 19, 2016)  
Where is System.out .println(data);? Otherwise Gaurav's concept is correct.

Vadim_Shb said: (Jan 17, 2018)  
There is no guarantee that at line 10 "f" is available for the second thread.

Nikhil said: (Jul 25, 2021)  
No, @Gaurav.

Because what if I cal increase () method twice then it will change the value continuously.

Post your comments here:

Name *:

Email   : (optional)

» Your comments will be displayed only after manual approval.