Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does "synchronized" mean in Java? [duplicate]

Tags:

I have been trying to learn design patterns. This site uses the synchronized keyword, but I don't understand what it does.

I searched on the net and found that it is somewhat related to multi-threading and memory, but I am a mechanical engineer and don't understand what that means.

Can anybody please help me understand threads and the synchronized keyword?

like image 610
Cool_Coder Avatar asked Oct 21 '11 10:10

Cool_Coder


People also ask

What is the difference between synchronized and non synchronized?

Non synchronized -It is not-thread safe and can't be shared between many threads without proper synchronization code. While, Synchronized- It is thread-safe and can be shared with many threads.

Why we use synchronized in java?

We need to synchronize the shared resources to ensure that at a time only one thread is able to access the shared resource. If an Object is shared by multiple threads then there is need of synchronization in order to avoid the Object's state to be getting corrupted. Synchronization is needed when Object is mutable.

What does synchronized mean in java?

Synchronization in java is the capability to control the access of multiple threads to any shared resource. In the Multithreading concept, multiple threads try to access the shared resources at a time to produce inconsistent results. The synchronization is necessary for reliable communication between threads.


1 Answers

There is no synchronized keyword in C++.

There is one in Java, though, where for methods it means the following two things:

  • It is not possible for two invocations of synchronized methods on the same object to interleave. When one thread is executing a synchronized method for an object, all other threads that invoke synchronized methods for the same object block (suspend execution) until the first thread is done with the object.
  • When a synchronized method exits, it automatically establishes a happens-before relationship with any subsequent invocation of a synchronized method for the same object. This guarantees that changes to the state of the object are visible to all threads.

Similar rules apply to arbitrary blocks.

Also, I recommend learning from a peer-reviewed book, not some arbitrary non-authoritative website.

like image 140
Lightness Races in Orbit Avatar answered Oct 21 '22 05:10

Lightness Races in Orbit