I have encountered a question which I am struggled to understand though I found the answer. Please look at this and provide me an explanation on the answer.
public class TestSeven extends Thread {
private static int x;
public synchronized void doThings() {
int current = x;
current++;
x = current;
}
public void run() {
doThings();
}
}
question and given answer is... Which statement is true?
A. Compilation fails.
B. An exception is thrown at runtime.
C. Synchronizing the run() method would make the class thread-safe.
D. The data in variable "x" are protected from concurrent access problems.
E. Declaring the doThings() method as static would make the class thread-safe.
F. Wrapping the statements within doThings() in a synchronized(new Object()) { } block would make the class thread-safe.
Bold one is given as the answer. Thanks for the replies in advance !!
If you have a synchronized instance method like that, it synchronizes on the instance, i.e. every instance can access the method on its own. But x
is static, so any instance of TestSeven
can access it concurrently.
If doThings()
is static, it synchronizes on the class, so only one instance can access synchronized code at a given time.
Here is what will happen.
public static syncronized void doThings();
This will synchronize method at class level. Which means only one instance of class will be able to access the code at an instance of time, Which means there is no possibility of static variable x
to be modified by other instances.
In other case,
public syncronized void doThings();
This means that doThings(); method is synchronized on current object. i.e. an instance of TestSeven
, so multiple instances can access the method which in turn can change the static shared variable x
which is not desirable.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With