Singletons que no son single

Desde hace un buen rato he sabido que los singletons pueden no ser tan singles usando reflection.

pero ¿cómo es que esto puede suceder?


package single;

import java.lang.reflect.Constructor;

public class Main {

public static void main(String[] args) throws Exception {

Single sin = Single.getInstance();
Single sin2 = Single.getInstance();

if(sin ==sin2){
  System.out.println(" - TEST from singleton equals- ");
}else{
  System.out.println(" - Ouch1  - ");
}

Class<?> forName = Class.forName("single.Single"); //get the class
Constructor<?>[] declaredConstructors = forName.getDeclaredConstructors(); //get constructors fr4om Class
Constructor<?> constructor = declaredConstructors[0]; //get the first constructor (the only one)
constructor.setAccessible(true);//set accesible
Single newInstance = (Single)constructor.newInstance(null);//here we go

if(newInstance == sin){
  System.out.println(" - newInstace and singleton equals - ");
}else{
  System.out.println(" - Singleton is not so single  1 - ");
}

if(newInstance == sin2){
  System.out.println(" - newInstace and singleton2 aARE equals - ");
}else{
  System.out.println(" - Singleton is not so single  22 - ");
}

}

}
package single;

public class Single {

private static final Single instance = new Single();

private Single(){}

public static Single getInstance(){return instance;}

}

El resultado es:

- TEST from singleton equals-
- Singleton is not so single  1 -
- Singleton is not so single  22 -

Una forma más segura de que un singleton sea singleton es usando el approach de enum, Joshua Bloch lo describe en el Item 3 de Effective Java (2nd Edition), el mismo Bloch menciona otro punto en el que hay que tener cuidado: a la hora de deserializar.

Tambien vale la pena revisar revisar el tutorial sobre reflection, viene muy sencillo y preciso:

http://java.sun.com/docs/books/tutorial/reflect/member/index.html

Advertisements

One thought on “Singletons que no son single

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s