Java Programming

10.5 Synchronization

Thread synchronization is the concurrent execution of two or more threads that share critical resources.

Threads should be synchronized to avoid critical resource use conflicts. Otherwise, conflicts may arise when parallel-running threads attempt to modify a common variable at the same time.

if multiple threads try to write within a same file then they may corrupt the data because one of the threads can overrite data or while one thread is opening the same file at the same time another thread might be closing the same file.

So there is a need to synchronize the action of multiple threads and make sure that only one thread can access the resource at a given point in time. This is implemented using a concept called monitors.

Each object in Java is associated with a monitor, which a thread can lock or unlock. Only one thread at a time may hold a lock on a monitor.

Java programming language provides a very handy way of creating threads and synchronizing their task by using synchronized blocks. You keep shared resources within this block.

Syntax
synchronized (object reference expression)
{
//code block
}

Here, the object identifier is a reference to an object whose lock associates with the monitor that the synchronized statement represents.

Download for more knowledge

https://play.google.com/store/apps/details?id=ab.java.programming

Leave a comment