What does 'synchronized' mean?

后端 未结 17 1897
广开言路
广开言路 2020-11-22 00:13

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

  • What is the significance of the synchronized
17条回答
  •  失恋的感觉
    2020-11-22 00:35

    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

提交回复
热议问题