What does 'synchronized' mean?

2018-12-31 05:26发布

I have some questions regarding the usage and significance of the synchronized keyword.

  • What is the significance of the synchronized keyword?
  • When should methods be synchronized?
  • What does it mean programmatically and logically?

15条回答
君临天下
2楼-- · 2018-12-31 05:35

synchronized simple means no two threads can access the block/method simultaneously. When we say any block/method of a class is synchronized it means only one thread can access them at a time. Internally the thread which tries to access it first take a lock on that object and as long as this lock is not available no other thread can access any of the synchronized methods/blocks of that instance of the class.

Note another thread can access a method of the same object which is not defined to be synchronized. A thread can release the lock by calling

Object.wait()
查看更多
何处买醉
3楼-- · 2018-12-31 05:37

The synchronized keyword prevents concurrent access to a block of code or object by multiple Threads. By default, a Hashtable is synchronized, so only one thread can access the table at a time.

On usage of non-synchronized constructs like HashMap,you must build thread safety features in your code to prevent memory consistency errors.

查看更多
浪荡孟婆
4楼-- · 2018-12-31 05:38

The synchronized keyword causes a thread to obtain a lock when entering the method, so that only one thread can execute the method at the same time (for the given object instance, unless it is a static method).

This is frequently called making the class thread-safe, but I would say this is a euphemism. While it is true that synchronization protects the internal state of the Vector from getting corrupted, this does not usually help the user of Vector much.

Consider this:

 if (vector.isEmpty()){
     vector.add(data);
 }

Even though the methods involved are synchronized, because they are being locked and unlocked individually, two unfortunately timed threads can create a vector with two elements.

So in effect, you have to synchronize in your application code as well.

Because method-level synchronization is a) expensive when you don't need it and b) insufficient when you need synchronization, there are now un-synchronized replacements (ArrayList in the case of Vector).

More recently, the concurrency package has been released, with a number of clever utilities that take care of multi-threading issues.

查看更多
泪湿衣
5楼-- · 2018-12-31 05:39

Overview

Synchronized keyword in Java has to do with thread-safety, that is, when multiple threads read or write the same variable.
This can happen directly (by accessing the same variable) or indirectly (by using a class that uses another class that accesses the same variable).

The synchronized keyword is used to define a block of code where multiple threads can access the same variable in a safe way.

Deeper

Syntax-wise the synchronized keyword takes an Object as it's parameter (called a lock object), which is then followed by a { block of code }.

  • When execution encounters this keyword, the current thread tries to "lock/acquire/own" (take your pick) the lock object and execute the associated block of code after the lock has been acquired.

  • Any writes to variables inside the synchronized code block are guaranteed to be visible to every other thread that similarly executes code inside a synchronized code block using the same lock object.

  • Only one thread at a time can hold the lock, during which time all other threads trying to acquire the same lock object will wait (pause their execution). The lock will be released when execution exits the synchronized code block.

Synchronized methods:

Adding synchronized keyword to a method definition is equal to the entire method body being wrapped in a synchronized code block with the lock object being this (for instance methods) and ClassInQuestion.getClass() (for class methods).

- Instance method is a method which does not have static keyword.
- Class method is a method which has static keyword.

Technical

Without synchronization, it is not guaranteed in which order the reads and writes happen, possibly leaving the variable with garbage.
(For example a variable could end up with half of the bits written by one thread and half of the bits written by another thread, leaving the variable in a state that neither of the threads tried to write, but a combined mess of both.)

It is not enough to complete a write operation in a thread before (wall-clock time) another thread reads it, because hardware could have cached the value of the variable, and the reading thread would see the cached value instead of what was written to it.

Conclusion

Thus in Java's case, you have to follow the Java Memory Model to ensure that threading errors do not happen.
In other words: Use synchronization, atomic operations or classes that use them for you under the hoods.

Sources

http://docs.oracle.com/javase/specs/jls/se8/html/index.html
Java® Language Specification, 2015-02-13

查看更多
步步皆殇っ
6楼-- · 2018-12-31 05:42

To my understanding synchronized basically means that the compiler write a monitor.enter and monitor.exit around your method. As such it may be thread safe depending on how it is used (what I mean is you can write an object with synchronized methods that isn't threadsafe depending on what your class does).

查看更多
余生无你
7楼-- · 2018-12-31 05:42

synchronized is a keyword in Java which is used to make happens before relationship in multithreading environment to avoid memory inconsistency and thread interference error.

查看更多
登录 后发表回答