I have a requirement which is as below :
1) A class which has all static methods and a static list. This list stores some objects on which I perform some operation.
2) Now this operation is called from multiple threads.
3) this operation call is not sharing any common data so this methods is not synchronized.
4) now whenever this list gets updated with new objects, I have to stop this operation call.
class StaticClass{
static List<SomeObjects>=new List<>();
static performOperation()
{
//call operation on all objects in the list
}
static updateList()
{
//update list, add, update or remove objects
}
}
Possible solutions :
1) Make performOperation() and updateList() synchronized. But the frequency at which performOperation() gets called is too high and udpate list frequency is too low.
2) use read write locks. Use read locks in performOperation() and write locks in updateList(). Sample is shown below :
class StaticClass{
static List<SomeObjects>=new List<>();
static final ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
static performOperation()
{
readWriteLock.readLock().lock();
//call operation on all objects in the list
readWriteLock.readLock().unlock();
}
static updateList()
{
readWriteLock.writeLock().lock();
//update list, add, update or remove objects
readWriteLock.writeLock().unlock();
}
So which solution is better? Is this a correct usage of readwrite locks. Why I am confused in going with approach 2 is there is not such data in performOperation() which needs read access or write access. I just cannot call this method when list is being updated. So I am not sure whether its a appropriate usage of read write locks or not.