Java — Synchronization FAQs | Code Factory

Index Page : Link

Donate : Link

WordPress Blog : Link

1. What is synchronized keyword and where we can apply?

  • Synchronized is a modifier, applicable for methods, blocks but not for variables and classes.

2. Explain advantage of synchronized keyword?

  • We can resolve data inconsistancy problems.

3. Explain disadvantage of synchronized keyword?

  • In increase waiting time of threads and creates performance problems.

4. What is Race condition?

  • If multiple threads are operating simultaneously on same Java object then thare may be a chance of data inconsistancy problem this is called Race Condition. We can overcome this problem by using synchronized keyword.

5. What is object lock and when it is required?

  • Every object in Java has a unique lock which is nothing but object lock. Whenever thread wants to execute Synchronized method on instance then the thread requires object lock.

6. What is class level lock and when it is required?

  • Every class in Java has a unique lock which is nothing but class level lock. Whenever if a Thread wants to execute static Synchronized method then the thread requires this lock.

7. What is the difference between class level lock and object lock?

  • If a Thread wants to execute static Synchronized method then class level lock is required. If a Thread wants to execute instance Synchronized method then object level lock is required.

8. While a Thread executing Synchronized method on the given object is a remaining threads are allow to execute any other Synchronized method simultaneously on the same object.

  • No

9. What is the advantage of Synchronized block over Synchronized method?

  • Performance improve, waiting time of thread will be reduced.

10. Is a Thread can acquire multiple locks simultaneously?

  • Yes, of course from different objects.
class X {
public synchronized void m1() {
// Here thread has lock of x object
Y y = new Y();
synchronized(y) {
// Here thread has lock of x and y object
Z z = new Z();
synchronized(z) {
// Here thread has lock of x, y and z object
}
}
}
}

11. What is Synchronized statement?

  • The statements presents in synchronized method and synchronized block are called synchronized statements.