Issue
I have two methods, one for reading and one for writing. They both access the same collection and are used across multiple threads. For example, three threads for writing and eight - for reading. I need to test the thread safety of my collection. The write method takes precedence.
public static void insertEntity(Entity entity) {
try {
readWriteLock.writeLock().lock();
Session session = sf.openSession();
session.beginTransaction();
GenericDAO.insertEntity(session, entity);
session.getTransaction().commit();
session.close();
} finally {
readWriteLock.writeLock().unlock();
}
}
public static Entity getByID(Integer id) {
try {
readWriteLock.readLock().lock();
Session session = sf.openSession();
Entity entity = GenericDAO.selectByID(session, Entity.class, id);
session.close();
return entity;
} finally {
readWriteLock.readLock().unlock();
}
}
Solution
If you want to test your lock handling, you should extract that logic in to its own class. What has to be done while holding the lock should be encapsulated into an interface. Your production code implementation will do the Entity stuff. Your test code implementation will stress the lock handling (e.g. asserting mutual exclusivity)
By the way: your locking code is not correct. You should unlock()
a lock only if the corresponding lock()
succeeded. The pattern goes like this:
lock.lock();
try {
// do stuff
} finally {
lock.unlock();
}
Answered By - Frank Neblung