Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Thread Interruption Mechanisms in Java

Tech May 17 2

Natural Termination

A thread terminates naturally when its run method completes execution or when an unhandled exception causes premature termination.

Deprecated API Methods

The following methods have been deprecated and are not recommended for use:

  • suspend(): Suspends a thread
  • resume(): Resumes a suspended thread
  • stop(): Stops a thread abruptly

These method are discouraged due to serious side effects. For instance, when suspend() is invoked, the thread retains all acquired resources (such as locks) while entering a suspanded state, which can lead to deadlock situations.

Similarly, the stop() method does not ensure proper resource cleanup when terminating a thread. It denies the thread the opportunity to release resources gracefully, potentially leaving the appplication in an inconsistent state.

Due to these adverse effects, the suspend(), resume(), and stop() methods have been marked as deprecated.

Cooperative Interruption

interrupt()

Signals a thread to interrupt itself cooperatively:

public static void main(String[] args) throws ExecutionException, InterruptedException, IOException {
    WorkerThread worker = new Thread(() -> {
        Thread current = Thread.currentThread();
        while (!current.isInterrupted()) {
            // Perform work here
        }
        System.out.println(current.getName() + " received interruption signal");
    });
    worker.start();
    System.out.println("Press any key to trigger interruption");
    System.in.read();
    worker.interrupt();
}

isInterrupted()

Checks whether a thread has been interrupted:

public static void main(String[] args) throws ExecutionException, InterruptedException, IOException {
    WorkerThread worker = new Thread(() -> {
        while (!Thread.currentThread().isInterrupted()) {
            // Continue processing
        }
        System.out.println("Interruption detected");
    });
    worker.start();
    System.out.println("Press any key to interrupt the thread");
    System.in.read();
    worker.interrupt();
}

Thread.interrupted()

Tests whether the current thread has been interrupted and clears the interrupt status if it was set, returning the thread to a normal state:

public static void main(String[] args) throws ExecutionException, InterruptedException, IOException {
    WorkerThread worker = new Thread(() -> {
        while (!Thread.currentThread().isInterrupted()) {
            // Process until interrupted
        }
        System.out.println("First check: " + Thread.interrupted());
        System.out.println("Second check: " + Thread.interrupted());
    });
    worker.start();
    System.out.println("Press any key to examine thread status");
    System.in.read();
    worker.interrupt();
}

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.