Pinging a host in JDK1.5

JDK1.5 provides the functionality to test the reachability of a host. Before JDK 1.5, you had to implement this yourself (for example by sending UDP packets to the echo port (7) of the target machine).

Actually, the strategy of the implementation of isReachable is to try to use ICMP if it is available, or else to try to connect to the echo port.

This example shows you how the test the reachability of a host:

import java.net.*;

public class Main
{
   public static void main(String []args) throws Exception {
      if (args.length != 1) {
         System.out.println("Usage: java Main <host or ipaddress>");
         System.exit(1);
      }
      
      InetAddress inetAddress = InetAddress.getByName(args[0]);
      System.out.println(inetAddress);
      
      System.out.println(args[0] + " is reachable? " + inetAddress.isReachable(5000));
   }  
}

Changes to java.text.MessageFormat in JDK1.5

Before the new 1.5 feature that allows for a variable number of arguments in methods, the class MessageFormat could only be using an array of Objects as shown in the following example

Main.java:

import java.text.MessageFormat;
import java.util.Date;
 
public class Main
{
   public static void main(String args[]) throws Exception
   {
      Object[] arguments = {"John", new Date()};
      
      String template = "{0}, the date is {1,time,short}";
      String message = MessageFormat.format(template, arguments);
 
      System.out.println(message);
   }
}

With 1.5, there is a new overloaded format method declared as follows:

   public static String format(String pattern, Object... arguments)

This allows you to rewrite the above code as follows:

import java.text.MessageFormat;
import java.util.Date;
 
public class Main
{
   public static void main(String args[]) throws Exception
   {
      String template = "{0}, the date is {1,time,short}";
      String message = MessageFormat.format(template, "John", new Date());
 
      System.out.println(message);
   }
}

Creating a method with a variable number of arguments

JDK1.5 allows methods to have a variable number of arguments. The syntax is to specify the type, three dots and the argument name. The variable number of arguments must be the last argument to the method. Other (normal) arguments may precede the variable argument list. Only one variable argument list may be specified.

Main.java:

public class Main
{
   public static void main(String []args) {
      printStrings("one arg");
      System.out.println("--------------");
      printStrings("an arg", "another arg");
   }
   
   public static void printStrings(String... strings) {
      for (int i=0; i<strings.length; i++) {
         System.out.println(strings[i]);
      }   
   }
}

Typesafe enum in JDK 1.5

Earlier version of the JDK did not have true enumerated types. Many developers have implemented workarounds for this, a popular one described in Effective Java, item 21. Starting from 1.5, enumerated types have been integrated with the language, allowing developers to write more robust programs without having to write dull boilerplate code, which is automatically generated.

A simple example showing some advantages of the new enum feature:

enum DestinationType
{
   queue,
   topic
}

public class Main
{
   public static void main(String []args) {
      DestinationType dt = DestinationType.queue;

      // Outputting an enumerated type is user-friendly
      System.out.println(dt);   // prints out "queue"
      
      // Switch can be used on an enumerated type, no need to qualify the name of the constant
      switch (dt) {
         case queue:  System.out.println("Using a queue");
                      break;
         case topic:  System.out.println("Using a topic");
                      break;
         default:
      }
   }
}

It is possible to iterate over all declared enum constants:

import java.util.*;

enum DestinationType
{
   queue,
   topic
}

public class Main
{
   public static void main(String []args) {
      printDestinations(DestinationType.values());
      
      // or
      
      for (DestinationType dt : DestinationType.values()) {
         System.out.println(dt);
      }
   }
   
   public static void printDestinations(DestinationType[] list) {
      for (int i=0; i<list.length; i++) {
         System.out.println(list[i]);
      }
   }
}

It is even possible to declare methods on enum constants and attach behavior to the constants.

DestinationType.java:

public abstract enum DestinationType
{
   queue {
      public void print(String queueName) {
         System.out.println("This is queue " + queueName);
      }
   },
   topic {
      public void print(String topicName) {
         System.out.println("This is topic " + topicName);
      }
   };
   
   abstract void print(String name);
}

Main.java:

public class Main
{
   public static void main(String []args) {
      DestinationType dt = DestinationType.queue;

      dt.print("queue1");
   }
}

Static imports in JDK 1.5

Static imports have been introduced in 1.5 to remove the burden of having to qualify constant names. With static imports, you import the static members from a class rather than the classes from a package.

For example, suppose we have a class Einstein that calculates the formula E=m*c*c.

comesusEinstein.java:

package com.esus;
 
public class Einstein
{
   public static long SPEED_OF_LIGHT = 299792458;
 
   public static double getEnergy(double mass) {
      return mass * SPEED_OF_LIGHT * SPEED_OF_LIGHT;
   }
}

Here is an example of how to use this class before 1.5.

Main.java:

import com.esus.Einstein;
 
public class Main
{
   public static void main(String []args) {
      double energy = Einstein.getEnergy(1.0);
   
      System.out.println("Speed of light is " + Einstein.SPEED_OF_LIGHT + " m/s");
      System.out.println("1KG of mass gives " + energy + " Joules");
   
   }
}

In 1.5, things would get simpler and more readable.

Main.java:

import static com.esus.Einstein.*;
 
public class Main
{
   public static void main(String []args) {
      double energy = getEnergy(1.0);
    
      System.out.println("Speed of light is " + SPEED_OF_LIGHT + " m/s");
      System.out.println("1KG of mass gives " + energy + " Joules");
   }
}

Notice that you can import static member constants as well as static methods.

NullPointerException when auto-unboxing

This can happen when you cast a null to a primitive type. It can be hard to spot these types of errors:

Main.java:

import java.util.*;

public class Main
{
   public static void main(String []args) {
      // allow only integers to be added to the arraylist
      HashMap<String, Integer> map = new HashMap<String, Integer>();
      
      map.put("1", 10);
      map.put("2", null);
      
      int a = map.get("1");   // works fine
      int b = map.get("2");   // throws NullPointerException
   }
}

The reason for the NullPointerException is much clearer if you look
at the equivalent:

   int b = ((Integer) map.get("2")).intValue(); 

What is autoboxing?

Autoboxing is the automatic conversion between primitive types and reference types. It eliminates the need to explicitely create wrapper objects for primitive types.

Main.java:

public class Main
{
   public static void main(String []args) {
      Integer n1 = 20;   // no need to "new Integer", is done automatically
   
      System.out.println(n1);
      
      int n2 = n1;
       // no need to do "n1.intValue()"
 
      System.out.println(n2);
   }
}

This means that you don’t need to create wrapper objects anymore to use primitives in collection classes.

Main.java:

import java.util.*;
 
public class Main
{
   public static void main(String []args) {
      // allow only integers to be added to the arraylist
      ArrayList<Integer> arrayList = new ArrayList<Integer>();
      
      arrayList.add(10);
      arrayList.add(20);
      arrayList.add(30);
   
      for (int i=0; i<arrayList.size(); i++) {
         System.out.println(arrayList.get(i));
      }
   }
}

Pretty-printing an XML in Java

Imagine you want to format the following xml in a human-friendly format: test.xml:

<?xml version="1.0" encoding="UTF-8" ?> 
<message><content>Hello World!</content><destinations><dest>jmsqueue:myjmsqueue</dest>
<dest>file:/home/filequeue</dest><dest>123.30.230.90</dest></destinations></message>

You can do this using the XSLT transformer package. Working code sample: Main.java:

import org.w3c.dom.*;
 
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.*;
   
import java.io.*;
  
public class Main
{
   public static void main(String []args) {
      Document doc;
   
      try {
         DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
         DocumentBuilder db = dbf.newDocumentBuilder();
         doc = db.parse(new File("test.xml"));
   
         // use the XSLT transformation package to output the subtree destinations
         Transformer transformer = TransformerFactory.newInstance().newTransformer();
         transformer.setOutputProperty(OutputKeys.METHOD, "xml");
         transformer.setOutputProperty(OutputKeys.INDENT, "yes"); 
         transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
          
         StringWriter sw = new StringWriter();
         transformer.transform(new DOMSource(doc), new StreamResult(sw));
          
         System.out.println(sw.toString());
      }
      catch(Exception e) {
         e.printStackTrace();
      }
   } 
}

outputs:

<?xml version="1.0" encoding="UTF-8"?>
<message>
  <content>Hello World!</content>
  <destinations>
    <dest>jmsqueue:myjmsqueue</dest>
    <dest>file:/home/filequeue</dest>
    <dest>123.30.230.90</dest>
  </destinations>
</message>

Getting the current memory usage of a Process in windows with Java

You will have to use JNI for this. Using the following code, we will create a DLL that provides the method getProcessWorkingSet which will return the current working set size, and the method getProcessVMSize which will return the current pagefile usage. The working set size is the memory size as shown in the Windows Task Manager. The pagefile usage corresponds with the VM Size in the Windows Task Manager.

From MSDN:
Working set size: The working set is the amount of physical memory assigned to a process. If the working set is too small, the process incurs a high number of page faults as it repeatedly accesses the disk drive to locate data not currently in memory. If the working set is too large, fewer page faults occur, but the process retains memory that it no longer needs, and which might be required by other processes. A steady increase in the size of the working set can mean that the process is not releasing memory appropriately.

MemUsage.java:

public class MemUsage
{
   public native int getProcessWorkingSet();
   public native int getProcessVMSize();
}

Compile it and run javah on it to create the memusage.h header file:

javah -o memusage.h MemUsage

It generates the C header file memusage.h:

/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class MemUsage */
 
#ifndef _Included_MemUsage
#define _Included_MemUsage
#ifdef __cplusplus
extern "C" {
#endif
/*
 * Class:     MemUsage
 * Method:    getProcessWorkingSet
 * Signature: ()I
 */
JNIEXPORT jint JNICALL Java_MemUsage_getProcessWorkingSet
  (JNIEnv *, jobject);
 
/*
 * Class:     MemUsage
 * Method:    getProcessVMSize
 * Signature: ()I
 */
JNIEXPORT jint JNICALL Java_MemUsage_getProcessVMSize
  (JNIEnv *, jobject);
 
#ifdef __cplusplus
}
#endif
#endif

The implementation of these functions were put in memusage.c:

#include <windows.h>
#include <stdio.h>
#include <iphlpapi.h>
#include <Psapi.h>
#include "memusage.h"
 
/*
 * Class:     MemUsage
 * Method:    getProcessWorkingSet
 * Signature: ()I
 */
JNIEXPORT jint JNICALL Java_MemUsage_getProcessWorkingSet
  (JNIEnv *env, jobject obj) {
   PROCESS_MEMORY_COUNTERS  pmc;
 
   pmc.cb = sizeof(pmc);
 
   if (!GetProcessMemoryInfo(GetCurrentProcess(),&pmc,sizeof(pmc)))
      return;           // (must be running on Win9x)
 
   return pmc.WorkingSetSize;
}
 
/*
 * Class:     MemUsage
 * Method:    getProcessVMSize
 * Signature: ()I
 */
JNIEXPORT jint JNICALL Java_MemUsage_getProcessVMSize
  (JNIEnv *env, jobject obj) {
   PROCESS_MEMORY_COUNTERS  pmc;
 
   pmc.cb = sizeof(pmc);
 
   if (!GetProcessMemoryInfo(GetCurrentProcess(),&pmc,sizeof(pmc)))
      return;           // (must be running on Win9x)
 
   return pmc.PagefileUsage;
}

I used cygwin to develop a Windows DLL from this in the following way:

gcc -mno-cygwin -I/usr/include -Ic:/jdk1.3.1/include -Ic:/jdk1.3.1/include/win32
 -shared memusage.c -Wl,--add-stdcall-alias -o MemUsage.dll -lpsapi

This DLL now allowed me to get the current memory usage and page file usage on Windows. Here’s an example:

Main.java:

public class Main
{
   public static void main(String []args) throws Exception {
      System.loadLibrary("MemUsage");
      System.out.println("MemUsage loaded");
 
      MemUsage mem = new MemUsage();
      System.out.println("Current process working set: " + mem.getProcessWorkingSet() / 1024 + "K");
      System.out.println("Current process VM size:     " + mem.getProcessVMSize() / 1024 + "K");
       
      System.in.read();
   }
}

Sample run:

C:\experiments\java\workingset>java Main
MemUsage loaded
Current process working set: 4868K
Current process VM size:     5780K
  
C:\experiments\java\workingset>java Main
MemUsage loaded
Current process working set: 4872K
Current process VM size:     5784K

For those who don’t have cygwin installed or just want to start using this library right away, here it is:

MemUsage.dll

Getting the process ID on Windows from Java

You will have to use JNI for this. Using the following code, I’ll create a DLL that provides the method getPid which will return the current process ID.

Pid.java:

public class Pid {
   public native int getPid();
   
   public int getProcessID() {
      try {
         return getPid();
      }
      catch(UnsatisfiedLinkError e) {
         e.printStackTrace();
      }
      
      return -1;
   }
   
   public static void main(String args[])
   {
      try {
         System.loadLibrary("Pid");
      }
      catch(java.lang.UnsatisfiedLinkError e) {
         e.printStackTrace();
      }

      Pid pid = new Pid();
      System.out.println(pid.getProcessID());
   }
}

Compile and run javah on it to create the pid.h header file:

javah Pid

It generates the C header file Pid.h:

/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class Pid */

#ifndef _Included_Pid
#define _Included_Pid
#ifdef __cplusplus
extern "C" {
#endif
/*
 * Class:     Pid
 * Method:    getPid
 * Signature: ()I
 */
JNIEXPORT jint JNICALL Java_Pid_getPid
  (JNIEnv *, jobject);

#ifdef __cplusplus
}
#endif
#endif

The C code that allows to get the current process ID:

#include <windows.h>
#include <stdio.h>
#include <iphlpapi.h>
#include "pid.h"

JNIEXPORT jint JNICALL Java_Pid_getPid
  (JNIEnv *env, jobject object) {
   return (int) GetCurrentProcessId();
}

I used cygwin to develop a Windows DLL from this in the following way:

gcc -mno-cygwin -I/usr/include -Ic:/jdk1.3.1/include -Ic:/jdk1.3.1/include/win32
 -shared Pid.c -Wl,--add-stdcall-alias -o Pid.dll

This DLL now allows you to get the process ID of your current Java app. Here’s an example:

C:experimentsjavapid>java Pid
3844
C:experimentsjavapid>java Pid
3876

For those who don’t have cygwin installed or want to start using it right away, here’s the library:

Pid.dll