Java — Synchronization FAQs | Code Factory

  • Synchronized is a modifier, applicable for methods, blocks but not for variables and classes.
  • We can resolve data inconsistancy problems.
  • In increase waiting time of threads and creates performance problems.
  • 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.
  • 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.
  • 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.
  • 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.
  • No
  • Performance improve, waiting time of thread will be reduced.
  • 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
}
}
}
}
  • The statements presents in synchronized method and synchronized block are called synchronized statements.

--

--

--

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

The Eureka moment

Why is everyone choosing MSP over an IT guy?

Non Root Gluster CLI access

Transforming the response of an API on the fly

How to pinpoint UI bugs automatically

My journey through code learning platforms (FreeCodeCamp, Treehouse, Codecademy, Youtube)

Following agile ? This is how you should create User Stories and give Story Points.

Rabbit MQ Disaster Recovery(DR) Strategy

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Code Factory

Code Factory

More from Medium

SOLID Principles (Journey for writing readable and maintainable code)

Undo Changes With Memento Pattern

Chain of Responsibility Pattern(Behavioral Design Pattern)

Single Responsibility Principle (SRP)