Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7637505
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 31, 20262026-05-31T07:57:26+00:00 2026-05-31T07:57:26+00:00

I would like to cancel a running task and replace it with a new

  • 0

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.

  1. Why does my code not work?
  2. 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();
            }
        });
    }
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-31T07:57:28+00:00Added an answer on May 31, 2026 at 7:57 am

    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:

    class Task implements Runnable {
        public void run() {
            System.out.println("New task started");
            int i = 0; 
            while (true) {
                i++;
                if (Thread.currentThread().isInterrupted()) {
                    System.out.println("Exiting gracefully");
                    return;
                }
            }
        }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I would like to clarify something about TimerTask. When you have the code below:
i am new programmer in android application i would like display multiple notifications one
Would like to make anapplication in Java that will not automatically parse parameters used
Would like to know the c# code to actually retrieve the IP type: Static
I have a long running task, something like: public void myCancellableTask() { while (
I would like to show a simple confirmation dialog box show before running a
I am new to WPF and MVVM. I would like to minimize the window
I would like to be able to cancel delayed selectors individually. I can do
I would like to start a server request, you can cancel. My idea is
I have a UISearchDisplayController that shows the cancel button. I would like to call

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.