I am having a multi-thread application using a single static class which provides a list. I want getters of the static class to work freely (not synchronized against each other) but when a setter is working I want all getters to get locked and wait until setter’s job is done. I don’t want to lock getters when they are called together since it would degrade performance a lot. Getters are called 1,000,000 times per day and setter is only supposed to work once per day.
I am having a multi-thread application using a single static class which provides a
Share
Consider using a
java.util.concurrent.locks.ReadWriteLockimplementation, such asReentrantReadWriteLock(see javadoc)You would use this instead of
synchronized. Your getters would obtain the read lock, then release when they return, e.g.Similarly for setters methods, but using
readWriteLock.writeLock()instead.The class would have a single
ReentrantReadWriteLockobject, shared by all getters and setters on each object (or, if you wish, one per getter/setter pair).It’s quite cumbersome, but should give good concurrency. For those reasons, you should only take this on if you really need it, and that means measuring the degraded concurrency you get if you just use vanilla synchronization.