Synchronizing in Threads

Introduction

Threads are small sections of the program. Each thread decides its line of execution and multithreading in Java allows several of these threads to run simultaneously. Not only does this make the execution of the program much faster but also allows users to achieve optimal CPU efficiency. Although multithreading has led to better performances, there lies the factor of synchronization. If the synchronization goes haywire, multiple threads will try to access a resource at the same time and result in errors and program crashes. Therefore, synchronization is defined as the process of management of threads such that only one thread accesses a particular resource at any given time.

How is Synchronization Achieved?

The process of synchronizing threads in Java is through synchronized blocks. The keyword ‘synchronized’ is used to denote such blocks. These blocks are associated with objects. All blocks synchronized with a certain object will make sure only one thread is executing at a given time. Other threads attempting to execute are blocked until the current execution has finished. To facilitate the process of synchronization, Java uses the concept of monitors. Monitors are workspaces where execution takes place. The monitor can only be owned by one thread at a time. Once a thread acquires it, the monitor remains blocked such that no other thread can access it. The execution takes place using the object and the thread exits the monitor. Only then can the next thread enter the monitor and this process follows thereafter.

Syntax

synchronized (objectidentifier) {
// Access shared variables and other shared resources
}

The object identifier acts as a reference to the object that is currently using the monitor and has locked it. After the current thread has finished execution and the monitor gets associated with another object, the object identifier also changes its reference.

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.