Synchronization in JavaSynchronization in Java is the capability to control the access of multiple threads to any shared resource. Java Synchronization is better option where we want to allow only one thread to access the shared resource. Why use Synchronization?The synchronization is mainly used to
Types of SynchronizationThere are two types of synchronization
Here, we will discuss only thread synchronization. Thread SynchronizationThere are two types of thread synchronization mutual exclusive and inter-thread communication.
Mutual ExclusiveMutual Exclusive helps keep threads from interfering with one another while sharing data. It can be achieved by using the following three ways:
Concept of Lock in JavaSynchronization is built around an internal entity known as the lock or monitor. Every object has a lock associated with it. By convention, a thread that needs consistent access to an object's fields has to acquire the object's lock before accessing them, and then release the lock when it's done with them. From Java 5 the package java.util.concurrent.locks contains several lock implementations. Understanding the problem without SynchronizationIn this example, there is no synchronization, so output is inconsistent. Let's see the example: TestSynchronization1.java Output: 5 100 10 200 15 300 20 400 25 500 Java Synchronized MethodIf you declare any method as synchronized, it is known as synchronized method. Synchronized method is used to lock an object for any shared resource. When a thread invokes a synchronized method, it automatically acquires the lock for that object and releases it when the thread completes its task. TestSynchronization2.java Output: 5 10 15 20 25 100 200 300 400 500 Example of synchronized method by using annonymous classIn this program, we have created the two threads by using the anonymous class, so less coding is required. TestSynchronization3.java Output: 5 10 15 20 25 100 200 300 400 500 Next TopicSynchronized Block Example |
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India