Synchronization in Java Multi threading

Synchronization in Java Multi threading

Carlos
Carlos

1. Why do we need synchronization?
In multithreading technology, if the threads use data independently, there is
nothing to argue about. But if on a system with multiple CPUs or multi-core CPUs
or CPUs that support hyper-threading, the threads will actually operate in
parallel at the same time. Thus, if these threads access the same data variable
or method due to the reasons mentioned above, this can cause data corruption.

Suppose that, at the same time, there are 2 threads simultaneously calling the
increase() method on an object of class Counter.

Thus, at the same time, the two threads retrieve the current count value of 0,
and at the same time add 1 to this count value to become 1, then write the newly
added value, which is 1, to RAM.

If that's really the case, after both threads do their work, count will have the
value 1. However, if 2 threads increase the count value at the same time, then
count must have the value 2, which is exactly what we want.

=> Arranging object access order is really necessary now when threads share
data.

2. What is synchronization?
The ordering of object access threads is really necessary in multithreading
techniques. Synchronization is the arrangement of threads when accessing the
same object so that there is no data conflict. In other words, synchronization
means serialization
3. Java monitor
JVM Monitor (Java Virtual Machine) or java monitor is a monitoring tool that
supports thread synchronization.

4. Ways to synchronize in Java
Java provides us with 3 ways to synchronize: synchronized methods and
synchronized statements, static synchronized method.

5. Compare three synchronize methods
Synchronized method: locks all methods of an instance of an object (this).
Synchronized block: locks a part of code in a method.
Synchronized static method: locks all methods of a class.
Example:

Thank for reading the post.