Let’s say you have the following class:
class A {
private Foo foo = new Foo();
Foo getFoo() {
return foo; //foo.clone()?
}
void modifyFoo() {
//modify this.foo
//...
}
}
I want to allow:
- either multiple threads to call
getFoo() - or one thread to call
modifyFoo(), - once a thread wants to modify foo, no other new
getFoo()calls arriving after that may be executed, until modification is done.
Are there classes already for this problem in Java or do I have to implement it? If I have to implement it, then how do I implement it ensure thread safety?
It sounds like what you’re looking for is a Read-Write lock, fortunately, java provides one,
ReentrantReadWriteLock. You can use it as follows:This will allow any number of threads to call
getFoo()simultaneously, but only one to callmodifyFoo(). When modify foo is called, the thread will block until all read locks are released, then begin executing and prevent any new read locks from being acquired until it has finished. There are still concurrency issues to consider since the returnedFoocan be modified by the code that callsgetFoo, but this should provide the basic tool you need.