0

I have a Java class in AEM called "helper", the snippet looks like this:

public class Helper extends Thread{
    ................
      private String glossaryText;
      public String getGlossaryText() {
           Thread thread = new Thread() {
              public void run() {
                  glossaryText = getGlossaryHTML();
            }
        };
        try {
           thread.start();
        }
        catch(Exception e) {
        
        }finally {
           //this does NOT stop the thread
         thread.interrupt(); 
        }
        System.out.println(thread.isAlive());
        return glossaryText;
   }
 ........
 }

The problem is that, no matter what i do, System.out.println(thread.isAlive()); always print "true". thread.interrupt(); did not stop the thread.

Rongeegee
  • 866
  • 3
  • 10
  • 30
  • Why would you assume that `interrupt()` kills the `Thread`? The [documentation](https://docs.oracle.com/en/java/javase/14/docs/api/java.base/java/lang/Thread.html#interrupt()) only says that "*this thread's interrupt status will be set.*" It is up to the thread's `run()` method to query the thread's status and act accordingly. If no such check is done, interrupting the `Thread` will not have any effect. – Turing85 Sep 22 '20 at 14:58
  • The method `Thread#interrupt` does not "stop" or "kill" the thread. This method sets a flag of `Thread`, which the thread can check to act accordingly. It also throws an `InterruptedException` if the thread is blocked at the time of the call. – akuzminykh Sep 22 '20 at 15:00

1 Answers1

1

interrupt() does not work instantly stop the thread. It is just a signal to the thread, that it should stop itself soon. You have to build an reaction to it yourself.

The thing is, you don't wait for your thread to end. You just start the thread, signal it to stop an then check if its alive. There is a really small chance that between thread.start() and your print the thread will be executed, but in most cases the executing thread will just end processing getGlossaryText().

You could just put a thread.join(500); in front of your print and then your thread won't be alive anymore because it waits for the thread to be executed.

Milgo
  • 2,617
  • 4
  • 22
  • 37