Synchronization in Java

Monitor in Java

Monitor, mutex is a means of providing control over access to a resource. A monitor can have a maximum of one owner at a time. Therefore, if someone is using a resource and hijacked a monitor to provide sole access, then another who wants to use the same resource must wait for the monitor to be released, seize it, and only then start using the resource.

It is convenient to think of the monitor as the id of the object that captured it. If this id is 0, the resource is free. If not 0, the resource is busy. You can queue up and wait for his release.

In Java, each instance of an object has a monitor that is controlled directly by the virtual machine. It is used like this: any non-static synchronized method, when called, first of all tries to capture the monitor of the object on which it is called (which it can refer to as this). If it succeeds, the method is executed. If not, the thread stops and waits for the monitor to be released.

Synchronization in Java

Synchronization is a process that allows threads to run in parallel.

In Java, all objects have one lock, thanks to which only one thread at a time can access critical code in the object. This synchronization helps prevent damage to the state of the object. If a thread has acquired a lock, no other thread can enter the synchronized code until the lock is released. When the thread that owns the lock exits synchronized code, the lock is released. Now another thread can acquire the lock on the object and execute synchronized code. If a thread tries to acquire a lock on an object while another thread owns the lock, the thread enters the Blocked state until the lock is released.

Ways to synchronize in Java

  • System synchronization using wait()/notify(). A thread that is waiting for the fulfillment of any conditions calls the wait() method on this object, having previously captured its monitor. At this, his work is suspended. Another thread can call the notify() method on the same object (again, after capturing the monitor of the object), as a result of which the thread waiting on the object "wakes up" and continues its execution. In both cases, the monitor must be captured explicitly, via a synchronized block, because the wait()/notify() methods are not synchronized!
  • System synchronization using join(). The join() method called on an instance of the Thread class allows the current thread to stop before the thread associated with that instance finishes running.
  • Using classes from the java.util.concurrent package, which provides a set of classes for organizing inter-thread communication. Examples of such classes are Lock, Semaphore, etc. The concept of this approach is to use atomic operations and variables.

Read also:


Comments

Popular posts from this blog

Methods for reading XML in Java

XML, well-formed XML and valid XML

ArrayList and LinkedList in Java, memory usage and speed