Java Programming - Threads - Discussion
Discussion Forum : Threads - Finding the output (Q.No. 10)
10.
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()
{
f.increase(20);
}
};
t.start();
}
}
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?Answer: Option
Explanation:
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.
Discussion:
7 comments Page 1 of 1.
Nikhil said:
2 years ago
No, @Gaurav.
Because what if I cal increase () method twice then it will change the value continuously.
Because what if I cal increase () method twice then it will change the value continuously.
Vadim_shb said:
5 years ago
There is no guarantee that at line 10 "f" is available for the second thread.
Koushik mukherjee said:
7 years ago
Where is System.out .println(data);? Otherwise Gaurav's concept is correct.
Ron said:
8 years ago
Same point @Gaurav, 'Foo f = new Foo ();' should have been declared outside the t thread for the explanation to be valid.
Abhin said:
9 years ago
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.
Gaurav said:
10 years ago
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.
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.
Dhawan said:
1 decade ago
The class doesn't extends Thread or implement Runnable.
Post your comments here:
Quick links
Quantitative Aptitude
Verbal (English)
Reasoning
Programming
Interview
Placement Papers