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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With