In this chapter, you will learn what a synchronized block is, why it is used, and how to implement it with practical examples.
A synchronized block is used to synchronize a specific portion of code instead of synchronizing the entire method. It allows better control over shared resources and improves performance by reducing the scope of synchronization.
For a given object, only one thread can execute the synchronized block at a time and excessive use of synchronization may impact application performance. Overall, synchronized blocks are generally more efficient than synchronized methods due to their limited scope.
Sometimes, a method may contain many lines of code, but only a few of them need synchronization. In such cases, using a synchronized block is more efficient than synchronizing the entire method. If all the code inside a method is placed within a synchronized block, it behaves the same as a synchronized method.
To create/define a synchronized block, you need to use the "synchronized" keyword. Here is the syntax to define a synchronized block:
Consider this example, where only a specific part of the method is synchronized to prevent multiple threads from accessing the shared resource simultaneously.
Output:
5 10 15 20 25 100 200 300 400 500
This approach uses a synchronized block inside a method while creating threads through anonymous classes. It reduces code length and ensures that only one thread at a time can access the shared resource.
In this example, the threads are created using anonymous classes to reduce code length while still ensuring thread safety.
Output:
5 10 15 20 25 100 200 300 400 500
In this concept, a synchronized block is used to allow only one thread to send or process a message at a time, ensuring ordered execution and preventing message interference between threads.
In this example, a synchronized block ensures that only one thread sends a message at a time.
Output:
Sending a Message: Hola Hola Sent Sending a Message: Welcome to TpointTech website Welcome to TpointTech website Sent
We request you to subscribe our newsletter for upcoming updates.