Reflection and Singletons

*** Posted on https://bigendian.wordpress.com All rights reserved ***

Java reflection is one of those tools that you may go for years without using, and never miss it. Until the day comes that you have to invoke methods without knowing what they are in advance. When that happens, reflection will be the thing that would prevent you from jumping off the nearest cliff. IF you do it right.

Invoking a method by reflection is fairly straight forward: You get a Class object that describes the class of the method that you are trying to use, get the method you want, and create a method object that represents that method. I wont go into the details or code for this, but you can find a fairly comprehensive guide here.

The tricky part starts when you attempt to invoke the method. The signature for invoking a method requires an object that the method is invoked on, and the list of parameters. In other words, if you are trying to invoke method myMethod() from Class MyClass, the reflection API wants to know which object of MyClass do you want to call that method. The API even goes a step further and lets you specify that a new object should be created for this by invoking the Class.newInstance() method which calls the default no-args constructor of the class. So far so good.

But what happens if the class you are trying to call is a singleton? (I know I said that Java doesn’t have real singletons, but what it does have behaves enough like a singleton to cause this problem) Remember that in a singleton, there are no public constructors, and the only way to get an object of the class is by calling getInstance(). Unfortunately, if you are using reflection you can run into a situation where the object you are invoking at any particular iteration may or may not be a singleton and you wont know in advance, and calling newInstance() on a singleton will definitely not work as advertised. So what do you do?

What you can try to do is something like this:

Object obj = null;
Class<?> cls = Class.forName(className);
Method methodIWantToInvoke = cls.getMethod(methodName, Params);

try{
     Method getinst = cls.getMethod("getInstance",null);
     obj = getinst.invoke(null, null);
     }catch(NoSuchMethodException n){
     try {
         obj = cls.newInstance();
     } catch (InstantiationException e) {
      e.printStackTrace();
     }
 }
Object result = methodIWantToInvoke.invoke(obj, params);

What you are doing here is using reflection to get an object so that you can use reflection to invoke a method. 🙂

If the Class object cls describes a class that is a singleton, then the request to getMethod(getInstance(), null) will give ou back a Method object that you can invoke to get the instance of the singleton you need. If it isn’t a singleton, it will throw a MethodNotFoundException, in which case you know you can use plain old newInstance you invoke the constructor.  Either way, but the end of this, you can an Object that you can then pass to the method you originally wanted to invoke in order to invoke it.

Note that the order of actions here is arbitrary: You can just as easily call newInstance first and then (upon getting an IllegalAccessException) try getInstance(). You can also combine this with a static factory method to allow calling of constructors other than the no-args, which adds to your flexibility.

Using reflection is realy not as complicated as it might seem, but there are (at least) two things you must by mindful of:

1. Reflection is slow and heavy. It adds a lot of overhead to your code and should be used very judiciously (for a bit of insight to the overhead, checkout Dennis Sosnoski’s Java programming dynamics article. It’s a little dated, and reflection HAS become more efficient, but it’s still no where near directly coding)

2. One of the more common uses of reflection is with serialization, to examine and use de-serialized objects. This is exactly where Java Singletons fails. If you have an Object that was serialized and then deserialized in different JVMs, even though you can successfully call its getInstance() method with the code above, you are still not getting the same object.

Good luck, and happy coding,

B.E.

Java Singletons don’t exist.

*** Posted on https://bigendian.wordpress.com All rights reserved ***

When I first started in my current project I set down to a code review with the lead programmer to see “my” project. At some point during the review, the man pointed to a certain class that was being used as part of the startup sequence for the application and said “this should be reimplemented as a singelton”. Up until then I was following him closely, but that statement took me by surprise, because as far as I knew, singletons don’t exist in Java.

To understand why, we have to look at the definition of a Singelton:

A singleton is a pattern that permits exactly one object that is needed to coordinate actions across the system.

In other words, whereever I am, if I try to use a class that is defined as a singleton, I would always, always, get the SAME object.  Usually, a native implementation of a Singleton looks something like this:

public final class MySingleton{

private MySingelton me=null;

private MySingleton(){
   ...instantiation code here...
}

public Mysingelton getInstance(){
  if (null==me) me = new MySingelton();
  return me;
}

}

As you can see, MySingleton has no public contractors. It can’t be directly instantiated or inherited. You can only get a MySingleton Object by calling getInstance(), which always returns the same object. This makes the singleton very handy for coordinating actions across a system. System states, for example, can be saved as singletons, as can factories, shared queues (a synchronized singleton), thread states, etc. Everywhere in the system that you can the singleton’s name, you’re guarantied to have the exact same object returned to you.

So why are there no Java singletons? Clearly the code above is written in Java and would run in Java, and would function as expected in a Java program. The reason this is not a singleton is the last part of the singleton definition “across the system”.

Consider: In C++, I can use code very much like the one above to tell me if a program has been launched. On the first time that the program runs, it asks for the singleton object, gets it (after it has been allocated by the system) and modifies it to indicate that it had been launched. If the program is then launched again, the second instance of the program would request and get the SAME singleton, see that the “running” state has already been set, and exit. The singleton is used across the system in coordinate states.

In Java, on the other hand, every program instance would run in its own instance of the JVM. This means that when the second instance of the program is launched, it would NOT get the same object as the first instance, but rather it would get the instance that has just been instantiated in its own JVM. The code above can coordinate across the same JVM, but it fails to coordinate across the system. Therefore, it does not qualify as a true singleton.

This may seem like splitting hairs, but it’s a very important thing to know. The guy I set with in the code review was pointing at a class who’s job was to make sure only one instance of the application would ever launch. We work on a project that does network measurements and topographies. It sends out packets with different addresses and TTLs and uses the returns to map the Internet. If we have two instances of the application running at the same time, we may not know which packet was sent by which instance, and our results would be compromised. Furthermore: We allow our users to run the application as a service, or as a standalone GUI based program. If we don’t have mutual exclusion, we can run into a situation where a user had installed the service AND the GUI, and starts both, thinking that the GUI just reflects the service. This could very easily lead to corruption in our data, and problems in the whole research.  All because Java singletons aren’t really singletons.

The good news is that in 95% of the cases, the code above would work quite nicely as a singleton. So long as you are staying within the JVM, it’s fine. For the last 5%, there are workarounds that can make mutual exclusion possible in Java. I will post about that some other time, though.

Good Coding,

B.E.