Showing posts with label Java Hacks. Show all posts
Showing posts with label Java Hacks. Show all posts

Thursday, 25 May 2017

Can we execute the java program after calling System.exit(0)

Approach#1
Using ShutdownHook

class MyThread extends Thread { 
     public void run() { 
           System.out.println("After System exit call.");
     } 

public classTestSystemExit { 
     public static voidmain(String[] args)throws Exception { 

           Runtime runtime = Runtime.getRuntime(); 
          
           runtime.addShutdownHook(new MyThread()); 

           System.out.println("Before System exit call.");
           System.exit(0); 
          
     } 
}
Output:
Before System exit call.
After System exit call.

What is ShutDownHook?
Shutdown Hooks are a special construct that allow developers to plug in a piece of code to be executed when the JVM is shutting down.

Approach#2
We can achieve it by overriding the checkExit method of SecurityManager class.

importjava.security.Permission;

public classSystemExitBreaked {
     public static voidmain(String[] args) {
           System.setSecurityManager(new SecurityManager() {

                @Override
                public voidcheckPermission(Permission perm) {
                }

                @Override
                public void checkExit(int status) {
                     //throw new SecurityException(); // Line 10
                }

           });
           checkSystemExit();

     }

     public static voidcheckSystemExit() {

           System.out.println("Before System.exit(0)");
           try {
                System.exit(0);
           } catch(SecurityException se) {
                System.out.println("Inside the catch block !");
           }
           System.out.println("After System.exit(0)");

     }
}

Output: Before System.exit(0)

Now uncomment the line 10 i.e throw new SecurityException().

The new output will be:
Output:
Before System.exit(0)
Inside the catch block!
After System.exit(0)

Saturday, 22 October 2016

Listing all drives with type, total space and free space in Java



importjava.io.File;

importjavax.swing.filechooser.FileSystemView;

public class DrivesLists {
  
   public static voidmain(String[] args) {

      FileSystemView fsv = FileSystemView.getFileSystemView();

      File[] drives = File.listRoots();

      if (drives != null && drives.length > 0) {

         for (File drive : drives) {
            System.out.print("Drive name: "+drive);
            System.out.print(",\tType: "+fsv.getSystemTypeDescription(drive));
            System.out.print(",\tTotal space: "+drive.getTotalSpace());
            System.out.print(",\tFree space: "+drive.getFreeSpace());
            System.out.println();
         }
      }
   }
}

Thursday, 8 September 2016

Cast Java classes into user defined class


import java.util.LinkedList;
import java.util.List;

public class CastCollection extends LinkedList<String> {

      private static final long serialVersionUID = 1L;

      public static void main(String[] args) {

            class MyList extends CastCollection {
                  private static final long serialVersionUID = 1L;
            };

            MyList list = new MyList();
            list.add("Yasin");

            if (list instanceof CastCollection) {
                  CastCollection castedObj = (CastCollection) list;
                  System.out.println("Casted succesfully");
                  System.out.println(castedObj.get(0));
            }
      }
}
Output:
Casted succesfully
Yasin


Thursday, 25 August 2016

How to ensure that the Parent thread will die after the Child thread?

In below given example, the Parent thread dies before the Child thread.
classChildThread1 extends Thread {
     @Override
     public void run() {
           try {
                System.out.println("Child thread start");
                Thread th = Thread.currentThread();
               
                if("Child Thread".equals(th.getName())) {
                     Thread.sleep(1000);
                }
               
                System.out.println("Child thread closed");
               
           } catch(Exception e) {
                System.out.println("exception is" + e);
           }
     }
}

public classCloseChildThreadTest {
    public static void main(String args[]) throws InterruptedException {
    System.out.println("Main thread start");
    ChildThread1 cThread = new ChildThread1();
   
        cThread.setName("Child Thread");
        cThread.start();
        System.out.println("Main thread closed");
    }
}
Output:
Main thread start
Main thread closed
Child thread start
Child thread closed

Ensure the parent dies after the Child thread?

1. Using join() method
classChildThread1 extends Thread {
     @Override
     public void run() {
           try {
                System.out.println("Child thread start");
                Thread th = Thread.currentThread();
               
                if("Child Thread".equals(th.getName())) {
                     Thread.sleep(1000);
                }
               
                System.out.println("Child thread closed");
               
           } catch(Exception e) {
                System.out.println("exception is" + e);
           }
     }
}

public classCloseChildThreadTest {
    public static void main(String args[]) throws InterruptedException {
    System.out.println("Main thread start");
    ChildThread1 cThread = new ChildThread1();
   
        cThread.setName("Child Thread");
        cThread.start();
       
        cThread.join();
        System.out.println("Main thread closed");
    }
}
Output:
Main thread start
Child thread start
Child thread closed
Main thread closed

Using CountDownLatch:
package com.thread;

importjava.util.concurrent.CountDownLatch;
classChildThread1 extends Thread {
     CountDownLatch latch;
     publicChildThread1(CountDownLatch latch) {
           this.latch = latch;
     }

     @Override
     public void run() {
           try {
                System.out.println("Child thread start");
                Thread th = Thread.currentThread();
               
                if("Child Thread".equals(th.getName())) {
                     Thread.sleep(1000);
                }
                System.out.println("Child thread closed");
                /* Count down when the run method execution finished. */
                latch.countDown();
           } catch(Exception e) {
                System.out.println("exception is" + e);
           }
     }
}

public classCloseChildThreadTest {
    public static void main(String args[]) throws InterruptedException {
        /*Set count 1 to CountDownLatch. */
        CountDownLatch latch = new CountDownLatch(1);
        System.out.println("Main thread start");
        ChildThread1 cThread = new ChildThread1(latch);

        cThread.setName("Child Thread");
        cThread.start();

        /* Await till the end of the Child thread. */
        latch.await();
        System.out.println("Main thread closed");
    }
}
Output:
Main thread start
Child thread start
Child thread closed
Main thread closed
Related Posts Plugin for WordPress, Blogger...