I need to do an update operation asynchronously when I receive a notification. The update()
method below manipulates instance variables.
public class UpdateOperation implements Runnable
{
private Boolean isInProgress = false;
@Override
public void run() {
try
{
synchronized (isInProgress)
{
isInProgress = true;
}
update(); //perform update
synchronized (isInProgress)
{
isInProgress = false;
}
}
catch (UpdaterException e)
{
// deal with it
}
}
}
// In another class
private UpdateOperation mCurrentUpdateOperation = new UpdateOperation();
public void updateRequired()
{
synchronized (mCurrentUpdateOperation.isInProgress)
{
if (!mCurrentUpdateOperation.isInProgress)
{
new Thread(mCurrentUpdateOperation).start();
}
else
{
// reschedule or silently ignore
}
}
}
Is this setup sufficient for no two (2) update operations to run concurrently? I believe it is because the first thread to reach the synchronized
block will acquire the lock, launch the operation, and release the lock. Then the second (or more) will acquire the lock, see that operation is in progress, reschedule, and release the lock.
Can this setup ever fail?