219. Task Cancellation

Cancellation is a common technique used for forcibly stopping or completing a task that is currently running. A canceled task will not complete naturally. Cancellation should have no effect on an already completed task. Think of it as a Cancel button of a GUI.

Java doesn't provide a preemptive way for stopping a thread. Therefore for canceling a task, a common practice is to rely on a loop that uses a flag condition. The task responsibility is to check this flag periodically, and when it finds the flag set, then it should stop as fast as possible. The following code is an example of this:

public class RandomList implements Runnable {
private volatile boolean cancelled;
private final List<Integer> randoms = new CopyOnWriteArrayList<>();
private final Random rnd = new Random();

@Override
public void run() {
while (!cancelled) {
randoms.add(rnd.nextInt(100));
}
}

public void cancel() {
cancelled = true;
}

public List<Integer> getRandoms() {
return randoms;
}
}

The focus here is on the canceled variable. Notice that this variable was declared as volatile (also known as the lighter-weight synchronization mechanism). Being a volatile variable, it is not cached by threads and operations on it are not reordered in memory; therefore, a thread cannot see an old value. Any thread that reads a volatile field will see the most recently written value. This is exactly what we need in order to communicate the cancellation action to all running threads that are interested in this action. The following diagram depicts how volatile and non-volatile work:

Notice that the volatile variables are not a good fit for read-modify-write scenarios. For such scenarios, we will rely on atomic variables (for example, AtomicBoolean, AtomicInteger, AtomicReference, and so on).

Now, let's provide a simple snippet of code for canceling the task implemented in RandomList:

RandomList rl = new RandomList();

ExecutorService executor = Executors.newFixedThreadPool(10);

for (int i = 0; i < 100; i++) {
executor.execute(rl);
}

Thread.sleep(100);

rl.cancel();

System.out.println(rl.getRandoms());
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.118.2.240