Define synchronized keyword in java with an example program
Without reentrant synchronization, synchronized code would have to take many additional precautions to avoid having a thread cause itself to block. In this example, we are not using synchronization and creating multiple threads that are accessing the display method and produce random output.
In the above program, object s of class Synchronization is shared by all the three running threads t1, t2, and t3 to call the shared method void bookticket.
Hence the result is non-synchronized and such a situation is called a Race condition. Java synchronized keyword marks a block or a method a critical section. A critical section is where only one thread is executing at a time, and the thread holds the lock for the synchronized section.
This synchronized keyword helps in writing concurrent parts of any application. It also protects shared resources within the block.
To overcome the above Race Condition problem, we must synchronize access to the shared display method, making it available to only one thread at a time. This is done by using the keyword synchronized with display method, i. Synchronized void display String msg.
There are two types of Thread Synchronization. Mutual Exclusive helps keep threads from interfering with one another while sharing data. Mutual Exclusion can be achieved by three ways in java:. Method level synchronization is used for making a method code thread-safe, i. In the case of the synchronized method, the lock object is:. Block-level synchronization is used for making some amount of method code is thread-safe. If we want to synchronize access to an object of a class or only a part of a method to be synchronized then we can use the synchronized block for it.
It is capable to make any part of the object and method synchronized. The keyword synchronized means that only one thread can access the method at a time. Cloud Computing. Data Science. Angular 7. Machine Learning. Data Structures. Operating System.
Computer Network. Compiler Design. Computer Organization. Discrete Mathematics. Ethical Hacking. Computer Graphics.
Software Engineering. Web Technology. Cyber Security. C Programming. Control System. Data Mining. Data Warehouse. 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.
Here, the objectidentifier is a reference to an object whose lock associates with the monitor that the synchronized statement represents.