What is synchronization?

When multiple numbers of threads need to access a common resource, then care must be taken by the programmer that only one thread is able to access the shared resource at a particular instance of time. The techniq through which this goal is achieved is known as synchronization.
When we use threads, we usually need to use some synchronization somewhere to
make sure our methods don't interrupt each other at the wrong time and mess up our
data.
Java uses the concept of moniter(or semaphore) to achieve this.
Moniter is an object having mutual lock. The method which needs to be synchronized enters into the moniter. At a particular instance of time one thread can be the owner of the moniter. When one thread is executing in the moniter, all other threads have to wait until the thread exits from moniter.
Java directly supports synchronization by using keyword ‘synchronized’.
Generally, any time more than one thread is accessing mutable (changeable)
data, you synchronize to protect that data, to make sure two threads aren't changing
it at the same time.

No comments:

Post a Comment