1

I have a swing application. Upon clicking a menuItem on the menu bar, I am trying to make an API call which will supposedly take some time.

I didn't want the Swing app to get stuck/hanged until the API call gives its result so I have used the SwingUtilities.invokeLater to separate out a newly spawned thread that will take care of API call. The following is the code for the above

public void actionPerformed(ActionEvent e){
    Object src=e.getSource();

    if(src.equals(theJMenuItemClicked)){
        SwingUtilities.invokeLater(new Runnable() {

                    @Override
                    public void run() {
                        //apicall here
                    }
                })
    }

As long as the API call thread is functioning I show a JDIalog with a message saying "API call in Progress" and an "Abort Thread" button.

I would like to kill the thread upon clicking the "ABort Thread" button in the Jdialog.

If it is a normal thread, we have a Thread t = new Thread(new Runnable()) and we invoke a t.stop on the same.

How do I get hold of that particular thread instance spawned by SwingUtilities so that I can call a stop on it? In simpler words how can I kill the above thread created?

kleopatra
  • 51,061
  • 28
  • 99
  • 211
Vamsi Emani
  • 10,072
  • 9
  • 44
  • 71

1 Answers1

0
public class SwingUtilitiesExample implements ActionListener {

// Declaration of Swing Components
private JMenuItem menuItem;
private JButton abortOperation;

// Thread-safe indicator of the presence of the Thread
private volatile boolean isThreadRunning = false;

public SwingUtilitiesExample() {
    // Initialize Swing Components 
    menuItem = new JMenuItem();

    // Add ActionListeners
    menuItem.addActionListener(this);
    abortOperation.addActionListener(this);
}

@Override
public void actionPerformed(ActionEvent e) {
    Object source = e.getSource();
    if (source.equals(menuItem)) {
        isThreadRunning = true;
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                while (isThreadRunning) {
                    // API calls here
                }
            }
        });
    } else if (source.equals(abortOperation)) {
        isThreadRunning = false;
    }
}
}

By changing the value of isThreadRunning to false, you can effectively abort the Thread. As long as the Thread regularly checks this boolean, this code will function just fine.

The method Thread.stop() is deprecated. Oracle states that the method is inherently unsafe. Therefore, you should refrain from using it. Try using Thread-safe boolean variables to control the flow of the Thread instead, as seen in the code sample above.

If you're looking into returning some sort of type after you've finished the Thread, you might want to consider the SwingWorker class.

Christian Specht
  • 35,843
  • 15
  • 128
  • 182
Oskar
  • 1,321
  • 9
  • 19