Getting the parameters passed to the VM at runtime

With the new java.lang.management package in JDK 1.5, this becomes very simple now.

Main.java:

import java.lang.management.*;
import java.util.*;
 
public class Main
{
   public static void main(String []args) {
      RuntimeMBean mbean = ManagementFactory.getRuntimeMBean();
      List list = mbean.getInputArguments();
       
      Iterator iter = list.iterator();
      while (iter.hasNext()) {
         String s = (String) iter.next();
         System.out.println(s);
      }
   }
}

For example, run it with

java -Xmx200M -Xrs Main

outputs:

-Xmx200M
-Xrs

Comparing StringBuiler with StringBuffer

StringBuilder is a replacement for the thread-safe StringBuffer class. It works much faster as it has no synchronized methods. So, if you are doing lots of String operations in a single thread, you will gain a lot of performance when using this class.

Here’s a comparison.

Main.java:

public class Main
{
   public static void main(String []args) {
      stringBufferTest();
      stringBuilderTest();
   }
    
   public static void stringBufferTest() {
      long startTime = System.nanoTime();
      StringBuffer sb = new StringBuffer();
      for (int i=0; i<100000; i++) {
         sb.append((char) 'a');
      }
      System.out.println("StringBuffer test: " + (System.nanoTime() - startTime));
   }
    
   public static void stringBuilderTest() {
      long startTime = System.nanoTime();
      StringBuilder sb = new StringBuilder();
      for (int i=0; i<100000; i++) {
         sb.append((char) 'a');
      }
      System.out.println("StringBuilder test: " + (System.nanoTime() - startTime));
   }
}

outputs:

StringBuffer test: 12849957
StringBuilder test: 8935494