This question already has an answer here:
- What does 'synchronized' mean? 15 answers
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?
There is no
synchronized
keyword in C++.There is one in Java, though, where for methods it means the following two things:
Similar rules apply to arbitrary blocks.
Also, I recommend learning from a peer-reviewed book, not some arbitrary non-authoritative website.
As the commenters already pointed out, synchronized is a Java keyword.
It means that two threads cannot execute the method at the same time and the JVM takes care of enforcing that.
In C++, you will have to use some synchronization construct, like a critical section or a mutex. You can consult this.
If one thread tries to read the data and other thread tries to update the same data, it leads to inconsistent state.
This can be prevented by synchronising access to the data. Use “synchronized” method:
In the (Java) example
means that only one thread at a time should be able to access the getInstance() method this to avoid a racing condition.