Which class safely protects the doIt () method from concurrent thread access?

Which class safely protects the doIt () method from concurrent thread access?

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.



Leave a Reply 8

Your email address will not be published. Required fields are marked *


Tim

Tim

D only. B has no effect.

David

David

D only. Because the method is static and we can’t use “this”.