Difference between volatile and synchronized in Java

后端 未结 4 1103
旧时难觅i
旧时难觅i 2020-11-22 03:58

I am wondering at the difference between declaring a variable as volatile and always accessing the variable in a synchronized(this) block in Java?<

4条回答
  •  既然无缘
    2020-11-22 04:34

    synchronized is method level/block level access restriction modifier. It will make sure that one thread owns the lock for critical section. Only the thread,which own a lock can enter synchronized block. If other threads are trying to access this critical section, they have to wait till current owner releases the lock.

    volatile is variable access modifier which forces all threads to get latest value of the variable from main memory. No locking is required to access volatile variables. All threads can access volatile variable value at same time.

    A good example to use volatile variable : Date variable.

    Assume that you have made Date variable volatile. All the threads, which access this variable always get latest data from main memory so that all threads show real (actual) Date value. You don't need different threads showing different time for same variable. All threads should show right Date value.

    Have a look at this article for better understanding of volatile concept.

    Lawrence Dol cleary explained your read-write-update query.

    Regarding your other queries

    When is it more suitable to declare variables volatile than access them through synchronized?

    You have to use volatile if you think all threads should get actual value of the variable in real time like the example I have explained for Date variable.

    Is it a good idea to use volatile for variables that depend on input?

    Answer will be same as in first query.

    Refer to this article for better understanding.

提交回复
热议问题