I have the following use case: I have a class that has two methods m1 and m2. Normally, m1() need not be synchronized, however if someone calls m2(), then m1() needs to be synchronized as long as m2() is being executed. In order to achieve this, I came up with the following code. Could you pl. comment on it and suggest better options?
Note: I realize that this situation is not practical, because e.g. if some thread is in the middle of m1 and some other thread calls m2, then there would be a problem (and it would be great if someone points out how to take care of that); nonetheless I found thinking about this interesting.
public class DynamicSync
{
volatile MyLock lock;
private final MyLock DUMMY_LOCK = new DummyMyLock();
private final MyLock SYNCHRONIZED_LOCK = new SynchronizedMyLock();
public DynamicSync()
{
lock = DUMMY_LOCK;
}
public void dynamicallySynchronizedMethod() // this is method m1() in the question above
{
lock.lock();
// some logic
lock.unlock();
}
public void setLockAndExecuteLogic() // this is method m2() in the question above
{
synchronized(SYNCHRONIZED_LOCK)
{
lock = SYNCHRONIZED_LOCK;
// some logic
}
}
interface MyLock
{
void lock();
void unlock();
}
class DummyMyLock implements MyLock
{
@Override
public void lock()
{
}
@Override
public void unlock()
{
}
}
class SynchronizedMyLock implements MyLock
{
@Override
public synchronized void lock()
{
// no op
}
@Override
public void unlock()
{
lock = DUMMY_LOCK;
}
}
}
EDIT: the actual problem is: I'm designing an object pool, where I need to know how many and which of the objects are given out, and how many remain. So I was thinking of maintaining two collections: origSet would be a HashSet that contains all the objects and dynaSet would be a ConcurrentSkipListSet from which I give out objects and put them back in. If I need to figure out the difference between origSet and dynaSet at an instant, I need to 'freeze' dyanSet till the difference is calculated. But getting this difference will be a very infrequent operation, hence my question.