Sunday, September 12, 2010

Synchronization Questions

Q: what are the different ways of synchronization?
A: Synchronized method and synchronized block.
Q: How do you make a method synchronized?
A: A method can be made synchronized by using the synchronized keyword in the method declaration.
Q: What happens when multiple threads call a synchronized method?
When a thread enters a synchronized method, the object on which the method is called gets locked by that thread, so no other thread cannot call that or any other synchronized method on the same object.
Q: Do you mean to say that when a thread enters a synchronized method, no other thread can enter the same method or other synchronized methods on that class?
A: No, when a thread enters a synchronized method, only the object on which the method is called gets locked by that thread, but other objects instantiated from the same class are still not locked and methods on those instances can be called.
Q: What happens when I make a static method as synchronized?
A: Static methods are invoked directly on the class and not on object instances of the class, so when a thread enters a synchronized static method, the class itself gets locked by the thread and no other thread can enter any static synchronized methods on that class.
Q: When do you use synchronized blocks?
A: When synchronized method is used, the object on which the method is called gets locked by the thread. But, if you do not want that object to get locked, but you want some instance variable in that object to be locked, you go for synchronized blocks. Moreover, code in synchronized methods and block execute much slower that in non synchronized blocks and methods. Using synchronized blocks we can synchronize only the required portion of a method and thus improve performance.

No comments: