Blog Archives

Generating Delegate Methods In Java Using Intellij

If you are implementing a decorator pattern, you would have to implement one or more interfaces. If the interface has large number of methods, delegating each of them might be troublesome and error prone. Since there is no good way in java to implement delegates (implementing a proxy with an invocation handler is a workaround :)), a better option would be to take help of the IDE to be sure that the implementation is not error prone. Here is how to do it using Intellij IDE

Read the rest of this entry

Java Proxies and UndeclaredThrowableException

A common approach in Java is to use dynamic proxies to provide decorator-style behavior. Doing this allows you to add additional behavior “around” an object without the object itself or it’s callers being aware of the decorating.

Let’s take an common implementation of java proxy.

public interface InterfaceA {
    void display() throws SQLException;
}

public class ClassA implements InterfaceA {

    @Override
    public void display() throws SQLException {
        throw new SQLException();
    }
}

public class ProxyHandler implements InvocationHandler {

    private InterfaceA delegate;

    public ProxyHandler(InterfaceA delegate) {
        this.delegate = delegate;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println("Inside the invocation handler");
        return method.invoke(delegate, args);
    }
}

public class ProxyApp {
    public static void main(String[] args) {
        createAndTestProxy();
    }

    private static void createAndTestProxy() {
        InterfaceA interfaceA = (InterfaceA) Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),
                                                    new Class[]{InterfaceA.class}, new ProxyHandler(new ClassA()));
        try {
            interfaceA.display();
        } catch (java.sql.SQLException e) {
            throw new RuntimeException("Something bad happened", e);
        }
    }
}

If you run the ProxyApp class to test the proxy implementation, you would get the below exception trace

Inside the invocation handler
Exception in thread "main" java.lang.reflect.UndeclaredThrowableException
	at $Proxy0.display(Unknown Source)
	at proxy.ProxyApp.createAndTestProxy(ProxyApp.java:23)
	at proxy.ProxyApp.main(ProxyApp.java:16)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
	at java.lang.reflect.Method.invoke(Method.java:597)
	at com.intellij.rt.execution.application.AppMain.main(AppMain.java:110)
Caused by: java.lang.reflect.InvocationTargetException
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
	at java.lang.reflect.Method.invoke(Method.java:597)
	at proxy.ProxyHandler.invoke(ProxyHandler.java:26)
	... 8 more
Caused by: java.sql.SQLException
	at proxy.ClassA.display(ClassA.java:18)
	... 13 more

The expected stacktrace should have been

Inside the invocation handler
Exception in thread "main" java.lang.RuntimeException: Something bad happened
	at proxy.ProxyApp.createAndTestProxy(ProxyApp.java:25)
	at proxy.ProxyApp.main(ProxyApp.java:16)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
	at java.lang.reflect.Method.invoke(Method.java:597)
	at com.intellij.rt.execution.application.AppMain.main(AppMain.java:110)
Caused by: java.sql.SQLException
	at proxy.ClassA.display(ClassA.java:18)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
	at java.lang.reflect.Method.invoke(Method.java:597)
	at proxy.ProxyHandler.invoke(ProxyHandler.java:28)
	at $Proxy0.display(Unknown Source)
	at proxy.ProxyApp.createAndTestProxy(ProxyApp.java:23)
	... 6 more

Read the rest of this entry

Text Search In Jar Files

I found this  tool which can be help you to do a text search in jar files. Just execute the below command to start the application

java -jar Javinder.jar

Here is a sample snapshot

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