I have a code like this:
public class SomeClass
{
private ScheduledExecutorService executor;
private ScheduledFuture<?> future;
private Set<String> keys;
private ConcurrentMap<String, Something> map;
public void startTask()
{
future = executor.scheduleWithFixedDelay(new SomeTask(), ...);
}
public void stopTask()
{
future.cancel(true);
map.clear();
}
private class SomeTask implements Runnable
{
@Override
public void run()
{
for (String key : keys)
{
if (Thread.interrupted())
{
break;
}
// Getting value...
map.put(key, value);
}
}
}
}
I want to make sure that map
is empty when stopTask
exits.
I am thinking about making the method wait until the task has exited by using some synchronizer, however, I'm not sure which one would work better. There's also may be another, better way to do what I need.
The task has only one instance and can be rescheduled later after cancellation, if it matters.