Thread safety in Java class

前端 未结 4 747
陌清茗
陌清茗 2020-12-15 06:30

Why is this java class not Thread safe.

class TestClass {  
   private int x;

   int get() {
       return x;
   }

   void set(int x) {
       this.x = x;
         


        
4条回答
  •  自闭症患者
    2020-12-15 07:21

    With multiple processors, some values may be cached by the processor and may not reflect the changes made by other threads/processors for the same objects. Actually, JVM may be implemented to work this way even with a single processor.

    Synchronized methods are explicitly required by language specification to present a memory barrier and require reread of all instance variables from the memory.

    Because your code is not synchronized, one thread may set the value, but the other thread will return the value still cached by that thread.

    Please read 'Memory and Locks' chapter of Java Language Specification.

提交回复
热议问题