Finding out the classloader that loaded a particular class

You can have your classes loaded by several distinct classloaders. For example, you may have a URLClassLoader that loads your classes over the network.

To determine what ClassLoader loaded a particular class, you can invoke getClassLoader on the Class object of that class. This method returns null if the default system classloader was used to load the class.

Main.java:

public class Main {
   public static void main(String args[]) throws Exception {
 
      System.out.println(Main.class.getClassLoader());
      System.out.println(A.class.getClassLoader());
      System.out.println(String.class.getClassLoader());
   }
}
 
class A 
{
}

outputs:

sun.misc.Launcher$AppClassLoader@81012801
sun.misc.Launcher$AppClassLoader@81012801
null

Checking if another instance of the same program is already running

The best way in my opinion is to use ServerSockets. A ServerSocket can only be opened once. So if the application is already running, the creation of the same ServerSocket will fail. This is how you know the app is already running. Sockets are the best approach because the ports get closed by the JVM upon shut down, locking files used for behavior might not work under all circumstances.
Here is a sample:

public class MainApp
{
  private static ServerSocket applLockSocket;
 
  public MainApp()
  {
    // Do something...
 
  } 
 
  private static boolean isApplRunning()
  {
    try	
    {
       // Open a ServerSocket on an app specific port
       applLockSocket = new ServerSocket(2345);  
    } 
    catch (java.net.BindException e)
    {
       //There is already an application running!
       return true;
    }
    catch (IOException e)
    {
      // This was not expected...
    }
    return false;
  } 
 
  public static void main(String[] args)
  {
    try
    {
      if (isApplRunning())
      {
        // Since we only allow this application to be 
        // started once, we need to show the user, that
        // this app is already running...		   
        JOptionPane.showMessageDialog(null
          ,"This app is already running!"
          ,"Info:"
          ,JOptionPane.INFORMATION_MESSAGE);
	System.exit(0);
      } 
 
      // Start the application...
      new MainApp();
    } 
    catch (Exception e)
    {
      JOptionPane.showMessageDialog(null
        ,e.toString()
        ,"Error:"
	,JOptionPane.ERROR_MESSAGE);
    } 
  }
} 

Determining the OS at runtime

Use the following code to get information about the operating system:

   System.out.println("OS Name: " + System.getProperty("os.name"));
   System.out.println("OS Architecture: " + System.getProperty("os.arch"));
   System.out.println("OS Version: " + System.getProperty("os.version"));

Output will be something like:

   OS Name: Windows NT
   OS Architecture: x86
   OS Version: 4.0

Trapping CTRL-C in a Java app

The method addShutdownHook() of the java.lang.Runtime class provides a way of trapping a shutdown of the virtual machine. Please not that this method was added since java version 1.3.

The method expects one argument and that is a Thread object. This thread will be started when the virtual machine terminates. The only way this code will not be executed is when you use the method Runtime.halt().
After you have added a Shutdown hook, it is also possible to remove it with the equivalent method removeShutdownHook(). Its parameter should be the same as the one passed in addShutdownHook.

The following code illustrates an example that makes use of the addShutdownHook method.

Main.java:

// The Shutdown class is a sample class to illustrate the
// use of the addShutdownHook method
class Shutdown {
  private Thread thread = null;
 
  public Shutdown() {
    thread = new Thread("Sample thread") {
      public void run() {
        while (true) {
          System.out.println("[Sample thread] Sample thread speaking...");
          try {
            Thread.currentThread().sleep(1000);
          } catch (InterruptedException ie) {
            break;
          }
        }
        System.out.println("[Sample thread] Stopped");
      }
    };
    thread.start();
  }

  public void stopThread() {
    thread.interrupt();
  }
}
 
 
// The ShutdownThread is the thread we pass to the
// addShutdownHook method
class ShutdownThread extends Thread {
  private Shutdown shutdown = null;
 
  public ShutdownThread(Shutdown shutdown) {
    super();
    this.shutdown = shutdown;
  }
  
  public void run() {
    System.out.println("[Shutdown thread] Shutting down");
    shutdown.stopThread();
    System.out.println("[Shutdown thread] Shutdown complete");
  }
}
 
 
// And finally a Main class which tests the two classes
// We let the sample thread run for 10 seconds and then
// force a Shutdown with System.exit(0). You may stop the
// program early by pressing CTRL-C.
public class Main {
  public static void main(String [] args) {
    Shutdown shutdown = new Shutdown();
    try {
      Runtime.getRuntime().addShutdownHook(new ShutdownThread(shutdown));
      System.out.println("[Main thread] Shutdown hook added");
    } catch (Throwable t) {
      // we get here when the program is run with java
      // version 1.2.2 or older
      System.out.println("[Main thread] Could not add Shutdown hook");
    }
 
    try {
      Thread.currentThread().sleep(10000);
    } catch (InterruptedException ie) {
    }
    System.exit(0);
  }
}

Getting a list of packages that have been loaded

Main.java:

public class Main
{
   public static void main(String []args) {
      Package[] packages = Package.getPackages();
      for (int i=0; i<packages.length; i++) {
         System.out.println(packages[i]);
      }
   }
}

prints out:

package java.util.zip, Java Platform API Specification, version 1.3
package java.security, Java Platform API Specification, version 1.3
package java.io, Java Platform API Specification, version 1.3
package sun.net.www.protocol.file, Java Platform API Specification, version 1.3
package sun.net.www.protocol.jar, Java Platform API Specification, version 1.3
package sun.net.www, Java Platform API Specification, version 1.3
package java.util.jar, Java Platform API Specification, version 1.3
package sun.security.action, Java Platform API Specification, version 1.3
package java.lang, Java Platform API Specification, version 1.3
package sun.io, Java Platform API Specification, version 1.3
package java.util, Java Platform API Specification, version 1.3
package sun.misc, Java Platform API Specification, version 1.3
package java.security.cert, Java Platform API Specification, version 1.3
package java.lang.reflect, Java Platform API Specification, version 1.3
package java.net, Java Platform API Specification, version 1.3
package sun.security.util, Java Platform API Specification, version 1.3
package java.lang.ref, Java Platform API Specification, version 1.3
package sun.security.provider, Java Platform API Specification, version 1.3
package com.sun.rsajca

Executing another java app from an already running one

You can either invoke the program entry point (the “main” function) of the other
application:

public class App1 {
   public void main(String args[]) {

      String []args2 = { "firstparam", "secondparam" };

      App2.main(args2);

   }
}

This will run App2 in the currently running JVM. You could also have the
new application running in another instance of a VM:

public class App1 {
   public void main(String []args) {
      
      Runtime.exec("java App2 firstparam secondparam");

   }
}

Reading a given rectangle from an image with ImageIO

Use the method setSourceRegion, defined in ImageReadParam and pass it to your reader. This example reads a given rectangle, specified by top x,y and width, height and creates a new image.

Main.java:

import javax.imageio.metadata.*; 
import javax.imageio.stream.*;
import javax.imageio.event.*;
import javax.imageio.*;
 
import java.awt.image.*; 
import java.util.*;
import java.awt.*;
import java.io.*;
  
public class Main 
{ 
   public static void main(String []args) throws Exception {
      if (args.length != 5 || !args[0].endsWith(".jpg")) {
         System.out.println("Usage: java Main image.jpg x y w h");
         System.exit(1);
      }
 
      int x = Integer.parseInt(args[1]);
      int y = Integer.parseInt(args[2]);
      int w = Integer.parseInt(args[3]);
      int h = Integer.parseInt(args[4]);
 
      Iterator readers = ImageIO.getImageReadersByFormatName("jpg");
      ImageReader reader = (ImageReader) readers.next();
 
      Iterator writers = ImageIO.getImageWritersByFormatName("jpg");
      ImageWriter writer = (ImageWriter) writers.next();
 
      ImageInputStream iis = ImageIO.createImageInputStream(new File(args[0]));
      reader.setInput(iis, true);
      ImageReadParam param = reader.getDefaultReadParam();
      param.setSourceRegion(new Rectangle(x, y, w, h));
      
      BufferedImage bi = reader.read(0, param);
  
      String jpgFile = args[0].substring(0, args[0].length()-4) + "_new.jpg";
      ImageOutputStream ios = ImageIO.createImageOutputStream(new File(jpgFile));
      writer.setOutput(ios);
      writer.write(bi);
   }
}

Catching events while an image is being written out using ImageIO

Register an IIOWriteProgressListener with your ImageWriter.

   IIOWriteProgressListener listener = new MyWriteProgressListener();
   writer.addIIOWriteProgressListener(listener);

This example reads a JPG and creates a new one, vertically subsampled.

Main.java:

import javax.imageio.metadata.*; 
import javax.imageio.stream.*;
import javax.imageio.event.*;
import javax.imageio.*;
 
import java.awt.image.*; 
import java.util.*;
import java.io.*;
  
public class Main 
{ 
   public static void main(String []args) throws Exception {
      if (args.length != 1 || !args[0].endsWith(".jpg")) {
         System.out.println("Usage: java Main image.jpg");
         System.exit(1);
      }
 
      Iterator readers = ImageIO.getImageReadersByFormatName("jpg");
      ImageReader reader = (ImageReader) readers.next();
 
      Iterator writers = ImageIO.getImageWritersByFormatName("jpg");
      ImageWriter writer = (ImageWriter) writers.next();
 
      ImageInputStream iis = ImageIO.createImageInputStream(new File(args[0]));
      reader.setInput(iis, true);
      BufferedImage bi = reader.read(0);
 
      IIOWriteProgressListener listener = new MyWriteProgressListener();
      writer.addIIOWriteProgressListener(listener);
 
      String jpgFile = args[0].substring(0, args[0].length()-4) + "_new.jpg";
      ImageOutputStream ios = ImageIO.createImageOutputStream(new File(jpgFile));
      ImageWriteParam param = writer.getDefaultWriteParam();
 
      IIOImage iioImage = new IIOImage(bi, null, null);
      param.setSourceSubsampling(1, 4, 0, 0);
      writer.setOutput(ios);
      writer.write(null, iioImage, param);
   }
 
   static class MyWriteProgressListener implements IIOWriteProgressListener {
        float last = 0;
 
	public MyWriteProgressListener() {}

        public void imageStarted(ImageWriter dest, int imageIndex)  { 
           System.out.println("0% -----------------------------------> 100%n");
        }
 
        public void imageProgress(ImageWriter dest, final float percentageDone) {
           int n = (int) (percentageDone-last);
           for (int i=0; i<n/2; i++) {
              System.out.print("*");
           }
           last = percentageDone;
        }
 
        public void imageComplete(ImageWriter dest) { 
           System.out.println();
        }
 
        public void writeAborted(ImageWriter dest)                  { }
        public void sequenceComplete(ImageWriter dest)              { }
        public void sequenceStarted(ImageWriter dest, int minIndex) { }
        public void thumbnailComplete(ImageWriter dest)             { }
        public void thumbnailProgress(ImageWriter dest, float percentageDone) { }
        public void thumbnailStarted(ImageWriter dest, int imageIndex, int thumbnailIndex) { }
   }
}