Thursday 12 May 2016

Why destroy() method deprecated in java?

destroy() method is deadlock prone. If the target thread holds a lock on object when it is destroyed, no thread can lock this object. It results in deadlock formation. These deadlocks are generally called frozen processes.

Additionally you must know calling destroy() method on Threads throw runtimeException i.e. NoSuchMethodError.

public class DestroyTest {

      public static void main(String[] args) throws InterruptedException {

          final Thread thread1 = new Thread("thread1") {
             public void run() {
               String name = Thread.currentThread().getName();
               System.out.println(name + "has started...");
               Thread.currentThread().destroy();
               System.out.println(name +" has ended.");
    
               }
            };
            thread1.start();
      }  
}

Output:
      thread1 has started...
      Exception in thread "thread1" java.lang.NoSuchMethodError
            at java.lang.Thread.destroy(Unknown Source)
            at DestroyTest$1.run(DestroyTest.java:10)




No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...