Category Archives: java

Database Connections Are Performance Expensive

While reading the Data Access Handbook I came across some facts about database connections. These connections are established by any JEE application to the database server.

  • Creating a connection is performance-expensive compared to all other tasks a database application can perform.
  • Open connections use a substantial amount of memory on both the database server and database client machines.
  • Establishing a connection takes multiple network round trips to and from the database server.
  • Opening numerous connections can contribute to out-of-memory conditions, which might cause paging of memory to disk and, thus, overall performance degradation.
  • In today’s architectures, many applications are deployed in connection pooled environments, which are intended to improve performance.However, many times poorly tuned connection pooling can result in performance degradation. Connection pools can be difficult to design, tune, and monitor.

Read the rest of this entry

Implicit escape of “this” reference

One of the prerequisite in making an object immutable include making sure that the this reference isn’t allowed to escape during creation. This point is also referenced in the famous Java Concurrency In Practice book. Section 3.2 of the book states

A mechanism by which an object or its internal state can be published is to publish an inner class instance, as shown in ThisEscape in Listing 3.7. When ThisEscape publishes the EventListener, it implicitly publishes the enclosing ThisEscape instance as well, because inner class instances contain a hidden reference to the enclosing instance. ”

public class ThisEscape {
    private final int num;

    public ThisEscape(EventSource source) {
       source.registerListener(
          new EventListener() {
            public void onEvent(Event e) {
              doSomething(e);
           }
          });
      num = 42;
   }

   private void doSomething(Event e) {
     if (num != 42) {
       System.out.println("Race condition detected at " +
           new Date());
     }
   }
}

The above code creates issues in cases where for e.g. EventSource starts a concurrent execution which leads to the creation of the events before the constructor of ThisEscape completes. What this means is that the doSomething method gets called before the constructor of ThisEscape ends. Like any other method the doSomething() method, as shown above, could access the state of ThisEscape class assuming the object is in the consistent state.
To give an idea the EventSource code could look similar to

import java.util.concurrent.atomic.*;

public class EventSource extends Thread {
  private final AtomicReference<EventListener> listeners =
      new AtomicReference<EventListener>();

  public void run() {
    while (true) {
      EventListener listener = listeners.getAndSet(null);
      if (listener != null) {
        listener.onEvent(null);
      }
    }
  }

  public void registerListener(EventListener eventListener) {
    listeners.set(eventListener);
  }
}

So publishing an object from within its constructor can publish an incompletely constructed object. This is true even if the publication is that last statement in the constructor because the Java Memory Model (JMM) allows reordering of the statements. Thus the code might be optimized in such a way that the “this” reference escapes earlier.

To test the above explained race condition you could execute

 public class ThisEscapeTest {
   public static void main(String[] args) {
     EventSource es = new EventSource();
     es.start();
     while(true) {
       new ThisEscape(es);
     }
   }
 }

One of the solutions mentioned in the Java Concurrency In Practice book to the above problem is to use static factory method

public class SafeListener {
    private final EventListener listener;

    private SafeListener() {
        listener = new EventListener() {
            public void onEvent(Event e) {
                doSomething(e);
            }
        };
    }

    public static SafeListener newInstance(EventSource source) {
        SafeListener safe = new SafeListener();
        source.registerListener(safe.listener);
        return safe;
    }

}

Thanks to the Java Specialist news letters for providing details on this topic.

Estimating the memory usage of a java object

JDK 1.5 introduces the java.lang.instrument package which provides services that allow java programming agents to instrument programs running on the JVM. In simple words an agent is an interceptor in front of your main method, executed in the same JVM and loaded by the same system classloader, and governed by the same security policy and context.

We can create an instrumentation agent in Java by writing a class containing a premain(String, Instrumentation) method. This method is called by the JVM on startup and an instance of Instrumentation is passed in.

import java.lang.instrument.Instrumentation;

public class ObjectSizeFetcher {
    private static Instrumentation instrumentation;

    public static void premain(String args, Instrumentation inst) {
        instrumentation = inst;
    }

    public static long getObjectSize(Object o) {
        return instrumentation.getObjectSize(o);
    }
}

Since an agent has to be packaged in a jar file, compile the above class and package it in a jar file. Add a MANIFEST.MF file in the jar file under META-INF folder. The MANIFEST.MF file should contain the below line
Premain-Class: ObjectSizeFetcher

Use getObjectSize method

public class C {
   private int x;
   private int y;

   public static void main(String [] args) {
     System.out.println(ObjectSizeFetcher.getObjectSize(new C()));
   }
}

Invoke the above class C using the below command
java -javaagent:<path to objectsizefetcheragent.jar> C

Note that the instrumentation interface gives you a flat size of the object and does not recursively estimate the size of the objects that it references. To calculate the deep size of an object have a look at this article from java specialist.

Useful TimeUnit enum in java

JDK 1.5 introduces the TimeUnit enum that represents time durations at a given unit of granularity and provides utility methods to convert across units, and to perform timing and delay operations in these units.

Although it is part of the java.util.concurrent package, the TimeUnit enum is useful in many contexts outside of concurrency.

One of the clear advantages include code readability. Below are few code samples to demonstrate this

Code Sample 1 –
Instead of implementing the convertMillisToDays as below


/**
    * Convert provided number of milliseconds into number of days.
    *
    * @param numberMilliseconds Number of milliseconds to be converted into days.
    * @return Number of days corresponding to number of provided milliseconds.
    */
   private static long convertMilliSecondsToDaysViaSingleMagicNumber(final long numberMilliseconds)
   {
      // 86400000 = 86400 seconds in a day multipled by 1000 ms per second
      return numberMilliseconds / 86400000;
   }

A more readable code would look like


/**
    * Convert provided number of milliseconds into number of days.
    *
    * @param numberMilliseconds Number of milliseconds to be converted into days.
    * @return Number of days corresponding to number of provided milliseconds.
    */
   private static long convertMillisecondsToDaysViaTimeUnit(final long numberMilliseconds)
   {
      return TimeUnit.MILLISECONDS.toDays(numberMilliseconds);
   }

Code Sample 2 –
Instead of calling

Thread.sleep(5000); //Sleeping for 5 seconds

A more readable code would look like

TimeUnit.SECONDS.sleep(5);

The enum constant of theTimeUnit implies the applicable unit of time, so only a base number needs to be provided. The implication here, of course, is that more obvious numbers can be provided for sleeping rather than needing to worry about expressing a large number in milliseconds or even remembering that the method requires the time be specified in milliseconds.

Besides SECONDS, other time unit representations provided by TimeUnit include DAYSHOURS,MICROSECONDSMINUTESNANOSECONDS, and MILLISECONDS.

Two other related useful methods available in TimeUnit are TimeUnit.timedJoin(Thread,long)[convenience method for Thread.join] and TimeUnit.timedWait(Thread,long) [convenience method forObject.wait].

This post is inspired from The Highly Useful Java TimeUnit Enum.

How to find if a method returns void?

Normally this is the question which comes when using reflection to find the return type of a method. Void class comes to rescue.

   public class VoidClassApp {
       public static void main(String[] args) throws NoSuchMethodException {
          Class clazz = Test.class.getMethod("method").getReturnType();
          System.out.println(clazz == Void.TYPE);
       }
   }

   class Test {
      public void method() {
         System.out.println("Does Nothing");
      }
  }

The output is : true