Amazon Interview Question
Software Engineer / DevelopersCountry: United States
Interview Type: In-Person
There exists only one copy of each method per class, be the method static or non-static. A thread needs to acquire the monitor of an appropriate object before entering a synchronized method which it releases when the thread returns from the method. In case of static synchronization the thread acquires the monitor of the class object, the locking is at class level so no other thread can execute it until the current thread releases the lock. In case of non-static synchronisation the thread acquires the monitor of that particular instance on which the call was made so other threads using different instances are not locked. They acquire monitors of there respective instances but continue to execute, as no two thread use the same instance. So what i feel is the non-static part will work faster i.e printB().
Clazz is heavier to lock. You can check the result with below code.
To put the mutex on it would take more time.
import java.util.Date;
public class Try {
public static void main(String[] args) throws InterruptedException {
Date d = new Date();
final Try2 t2 = new Try2();
for (int i = 0; i < 100000; i++) {
Thread t = new Thread() {
public void run() {
t2.test();
}
};
t.start();
t.join();
}
Date d2 = new Date();
System.out.println(d2.getTime() - d.getTime());
d = new Date();
for (int i = 0; i < 100000; i++) {
Thread t = new Thread() {
public void run() {
Try1.test();
}
};
t.start();
t.join();
}
d2 = new Date();
System.out.println(d2.getTime() - d.getTime());
}
}
class Try1 {
public static synchronized void test() {
}
}
class Try2 {
public synchronized void test() {
}
}
One important thing to question the interviewers at this point is, for a particular class, say A, are all the calls of method printA() for the same object or do each of the threads have their own instances? In case, which is most likely the case, that all threads have their own objects, printB() methods will take much less time.
- nosyDeveloper November 21, 2013Since the methods are synchronized, the caller thread needs to acquire a monitor for that method. In case of the method being static, this monitor is class-specific, so essentially every thread tries to acquire a single monitor.
In case the method is non static like printB() each of the objects have their own monitors for the method. Since every thread is the only entity trying to acquire lock on object specific method-monitor in respective objects, these threads can work parallely.
Result, printB() takes much less time.
[Corrected, thanks to user fReaK]