Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to achieve exclusive writing, but non-exclusive reading?

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?

like image 276
WelcomeTo Avatar asked Mar 31 '13 11:03

WelcomeTo


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.

like image 200
Mik378 Avatar answered Sep 30 '22 13:09

Mik378