简体   繁体   中英

Synchronized property reading as non-synchronized property

I have a non-atomic java property, which can be set by synchronized setter. My question is, can I read this property by non-synchronized getter? Thanks.

You can read the property, ie the thread will see some value but the problem is that it is not predictable -- it may not reflect the most recent value written by another thread or it may even be a random value. Therefore, you should synchronize the getter as well. It is not safe to only synchronize methods that write to a variable.

If the property is not atomic, you might have to introduce a ReadwriteLock. See http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/locks/ReadWriteLock.html

The answer depends on whether the field is volatile.

If the field is not volatile, then the other answers are correct. You can read the value, but the thread doing the read many not be able "see" the value that another thread wrote. The value written might be in a thread-local cache, so the second thread might always see the old value. In addition, the JIT compiler is free to reorder the code in a way that only works if no one is reading the value concurrently.

If the field is volatile, then you will get the behavior you want. The JVM will ensure that every thread will get the latest value.

Note you shouldn't do read-modify-write operations (like incrementing an integer field) on a volatile field outside of a synchronized block, because race conditions can result in unexpected results.

For more details, read Java Concurrency in Practice .

You can read the value through getter method but you can get unpredictable value. Because the movement you are getting value from getter it might be possible that other thread call setter method and change the value. So to avoid data violation we should make setter and getter both synchronize and it must be lock under same object lock.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM