I would like to cancel a running task and replace it with a new one, on the same thread.
In the code below, I used a single-thread executor to start a new task and capture a Future representing it. I then used the Future to cancel the task. However, the task did not cancel.
- Why does my code not work?
- How do I cancel a running task and replace it with a new one, on the same thread?
Example code:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.concurrent.Executors;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
class Task implements Runnable {
public void run() {
System.out.println("New task started");
int i = 0; while (true) i++;
}
}
public class TaskLauncher extends JFrame {
private JButton button = new JButton("Start new task");
private ExecutorService executor = Executors.newSingleThreadExecutor();
private Future<?> future;
public TaskLauncher() {
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
if (future != null) future.cancel(true);
future = executor.submit(new Task());
}
});
add(button);
pack();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new TaskLauncher();
}
});
}
}
Just calling cancel on the Future object will not cause the task to stop. See the API docs for more information. Also check this SO Question which shows how you have to code your task so that it can be cancelled using the Future object.
Modify your task like this: