Suppose I have an ExecutorService (which can be a thread pool, so there is concurrency) that executes the task at different times, periodically or in response to some other condition. The task to be completed is as follows:
- If this task is already being completed, do nothing (and let the finished work end).
- If this task is not already running, run Algorithm X, which can take a long time.
I am trying to come up with a way to implement this. It should be something like:
Runnable task = new Runnable() {
final SomeObj inProgress = new SomeObj();
@Override public void run() {
if (inProgress.acquire())
{
try
{
algorithmX();
}
finally
{
inProgress.release();
}
}
}
}
SomeObj ReentrantLock ( = tryLock() release = unlock()), AtomicBoolean -, , . ReentrantLock ? ( , , algorithmX() !) AtomicBoolean?
edit: , ?
Runnable task = new Runnable() {
boolean inProgress = false;
final private Object lock = new Object();
private boolean acquire() {
synchronized(this.lock)
{
boolean result = !this.inProgress;
this.inProgress = true;
return result;
}
}
private void release() {
synchronized(this.lock)
{
this.inProgress = false;
}
}
@Override public void run() {
if (acquire())
{
try
{
algorithmX();
}
finally
{
release();
}
}
}
}