How I can achieve exclusive writing, but non-exclusive reading? Can I synchronize
access to a setter and make a variable volatile
? Is this enough?

- 8,504
- 7
- 59
- 75

- 19,843
- 53
- 170
- 286
-
1What kind of variable that is? Some types have atomic writes guaranteed. – John Dvorak Mar 31 '13 at 11:28
-
1Can you show an example of code that needs that? In some situations, you can simply mark the variable volatile. – assylias Mar 31 '13 at 11:34
1 Answers
Look at the Java5 concurrent api:
http://docs.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/locks/ReadWriteLock.html
This will achieve your requirement since you can allow several thread reading without lock and locking only when writing.
Here an interesting post comparing this api with the traditional synchronized when reading: ReentrantReadWriteLock vs synchronized
Besides, as @assylias said in comment, you should avoid locking when it is not really necessary.
Indeed, you can trust the volatile
keyword only and only if both conditions are met:
You can use volatile variables instead of locks only under a restricted set of circumstances. Both of the following criteria must be met for volatile variables to provide the desired thread-safety:
_ Writes to the variable do not depend on its current value.
_ The variable does not participate in invariants with other variables.
-
1Depending on the use case, it might be unnecessary to use locking and volatile might be enough. – assylias Mar 31 '13 at 11:33