Which class safely protects the doIt () method from concurrent thread access?
A.
class SafeMethod {
Static int ID = 0;
Public static void doIt(String s) {
Synchronized (s) {
System.out.println(“Name:”+ s +”ID:”+ id++);
}
}
}
B.
class SafeMethod {
Static int ID = 0;
Public static void doIt(String s) {
Synchronized (new object () ) {
System.out.println(“Name:”+ s +”ID:”+ id++);
}
}
}
C.
class SafeMethod {
Static int ID = 0;
Public static void doIt(String s) {
Synchronized (this) {
System.out.println(“Name:”+ s +”ID:”+ id++);
}
}
}
D.
class SafeMethod {
Static int ID = 0;
Public static void doIt(String s) {
Synchronized (SafeMethod.class) {
System.out.println(“Name:”+ s +”ID:”+ id++);
}
}
}
Explanation:
It should be pointed out that:public void blah() {
synchronized (this) {
// do stuff
}
}
is semantically equivalent to:public synchronized void blah() {
// do stuff
}Incorrect answer:
B: A constructor cannot be synchronized.
D
only D
D
B and D
D only. B has no effect.
D only. Because the method is static and we can’t use “this”.
d
D