Brainteaser: Overridable methods

Consider the following case of inheritance:

public class  Parent {
   public Parent()  {
	getValue();
   }
   public void getValue()  {

   }
}

public class  Child extends Parent {
   private final Integer integer;
   public Child()  {
	integer = new Integer(888);
   }

   @Override
   public void getValue()  {
	System.out.println(integer);
   }
}

Question: What would the following program print, why?

public class  Test {
   public static void main(String[] args)  {
	Child child = new Child();
	child.getValue();
   }
}

Lets assume that getValue() implementation in Child class was changed to:

@Override
public void getValue()  {
     System.out.println(integer.toString());
}

Question: What would the output of the Test class be now, why?

Brainteaser: Broken Case of Inheritance

Consider the following case of inheritance:

public class ExtendingHashSet<E> extends HashSet<E>  {
   private int counter = 0;

   public ExtendingHashSet() {

   }

   @Override
   public boolean add(E e)  {
      counter++;
      return super.add(e);
   }

   @Override
   public boolean addAll(Collection&lt;? extends E&gt; c)  {
      counter += c.size();
      return super.addAll(c);
   }

   public int getCounter()  {
      return counter;
   }
}

Created instance:

ExtendingHashSet<String> s = new ExtendingHashSet<String>();
s.addAll(Arrays.asList("one", "two", "three"));

Question: What value would s.getCounter() method return at this point and why?

Looking forward for your answers dear readers

Java and Those Frameworks

I came across an interesting article that discusses today’s application developers making extensive use of different frameworks in their applications.

This is the writer’s opinion:

…Todays projects are over bloated from the use of frameworks that dont really produce a real benefit. Developers spend around 75% of their time just on set up and configuration…

The question I would like to ask you dear readers:
Do todays application developers really exaggerate the use of frameworks?

I think it would be a difficult question to answer. First some clarification is needed – what is exaggeration really? The number of frameworks used or the reduced performance as a result of use of these framework? Or the amount of time developer spends on installation and configuration?

I think first as a developer, one must understand the pros and cons of the framework, and how will it affect the performance of the application to be designed. The developer must have clear idea about what is he trying to achieve by using a particular framework in his application, and whether the framework is going to give him the desired result.

As a developer, when designing an application, one may ask questions which framework should be used depending on application’s requirements. Often the will not be just one framework choice, but several frameworks.

Of course not every developer may face the same situation mentioned above. Proprietary developers rely on leading market software vendors to provide the necessary solutions in one big product bundle.

One has to take several things into account such as future enhancements and possible requirements changes by the client. Using several frameworks to support an application may be look exaggerated at start, but on the long run it may turn out as a better decision. The time spent at the start on initial framework configuration will be paid off during further implementation and maintenance.

In conclusion, I think the ability to know which framework to put for use and when, can come only with experience.

Brainteaser: Broken Comparator

Question: The following program returns result “1″, which indicates that first Integer value is greater than the second, why?

import java.util.*;

public class Example  {

   public static void main(String[] args)  {
      System.out.println(&amp;quot;Result: &amp;quot; +
	   naturalOrder.compare(new Integer(90),
				new Integer(90)));
   }

private static Comparator&amp;lt;Integer&amp;gt; naturalOrder =
				new Comparator&amp;lt;Integer&amp;gt;()  {
   public int compare(Integer first, Integer second)  {
	return first &amp;lt; second ? -1 : (first == second ? 0 :1);
   }
  };
}

Please note:
In this case, comparator for natural order on Integer is written for example only, and in practice there is no need to write it.

Looking forward for your answers dear readers

Resources:
Effective Java

Hack any Java class using reflection attack

Have you ever thought how secure your application is? Well reflection attack can demonstrate how vulnerable Java classes are. In this post, I will try to apply reflection attack on a simple Java class to demonstrate vulnerabilities and what can be done to prevent it (in most cases).

Consider a POJO class:

public final class VictimClass  {

	private String password = "default_password";
	private static final int USER_ID = 3452678;
	private String privateFiled = "default_value";

	/**
	 * Private constructor that should
	 * not be invoked
	 */
	private VictimClass()  {
		System.out.println("Oops... " +
		"This private constructor was not " +
			" suppose to be invoked");
	}

	/**
	 * Private accessor
	 */
	private String getPassword()  {
		return password;
	}

	 /**
	 * Private mutator
	 */
	private void setPassword(String password)  {
		this.password = password;
	}

	 /**
	 * Private static method
	 */
	private static int getUsersId()  {
		return USER_ID;
	}
}

The POJO contains private constructor and several private methods and fields, which I will attempt to invoke and modify using reflection attack.

Now, I cannot say that reflection attacks are possible due to a Java bug. No, its simply how Java classes were designed. The core reflection facility was originally designed for component based application builder tools.

In java.lang.reflect, Constructor, Method and Field extend from parent AccessibleObject class. These objects provide access to the class’s methods and fields. By calling inherited parent method setAccessible(), private variables and methods including private constructors become accessible.

My tester class:

import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.lang.ClassNotFoundException;
import java.lang.InstantiationException;
import java.lang.IllegalAccessException;
import java.lang.reflect.InvocationTargetException;
import java.lang.NoSuchMethodException;

public class Tester  {

   private static String CLASS_NAME = "VictimClass";
   private static Class victimClass = null;
   private static Object victimClassObj = null;

   public static void main(String[] args)  {
	victimClass = loadClass(victimClass, CLASS_NAME);
	printClassStructure();
	attack();
   }

    private static Class loadClass(Class clazzor, String className)  {
 	Thread thread = Thread.currentThread();
	ClassLoader classLoader =
			thread.getContextClassLoader();

	try {
		clazzor = Class.forName(className, true, classLoader);
	}
	catch (ClassNotFoundException e) {
		System.err.println("Error: could not find class: "
			+ CLASS_NAME);
	}

	return clazzor;
   }

   private static void printClassStructure()  {

	Constructor[] constructors =
			victimClass.getDeclaredConstructors();
	for (Constructor c : constructors) {
		int modifier = c.getModifiers();
		System.out.println("Declared constructor name: " +
			c.getName() + "ntis accessible: " +
			c.isAccessible() + "ntis private: " +
			Modifier.isPrivate(modifier) + "n");
	}

	Method[] methods = victimClass.getDeclaredMethods();
	for (Method m : methods) {
		int modifier = m.getModifiers();
		System.out.println("Declared method name: " + m.getName() +
			"ntis accessible: " +
			m.isAccessible() +
			 "ntis private: " +
			Modifier.isPrivate(modifier) +
			 "ntis static: " +
			Modifier.isStatic(modifier) + "n");
	}

	Field[] fields = victimClass.getDeclaredFields();
	for (Field f : fields) {
		int modifier = f.getModifiers();
		System.out.println("Declared field name: " + f.getName() +
			"ntis accessible: " +
			f.isAccessible() +
			 "ntis private: " +
			Modifier.isPrivate(modifier) +
			 "ntis static: " +
			Modifier.isStatic(modifier) +
			 "ntis final: " +
			Modifier.isFinal(modifier) + "n");
	}
   }

   private static void attack()  {

     Field[] fields = victimClass.getDeclaredFields();
     Method[] methods = victimClass.getDeclaredMethods();
     Constructor[] constructors =
		victimClass.getDeclaredConstructors();
   //make constructor accessible
   constructors[0].setAccessible(true);

   System.err.println("Initiating reflection attack:");
   try {
   //create new object by invoking private constructor
   victimClassObj = constructors[0].newInstance(new Object[] {});

   //make static method accessible and get its value
   //please note: when invoking static method,
   //object represented by this Method is null
   methods[2].setAccessible(true);
   Object o = methods[2].invoke(null, new Object[] {});
   System.out.println("Got user ID from private static accessor: "
		 + o.toString());

   //make method accessible and get its value
   methods[0].setAccessible(true);
   o = methods[0].invoke(victimClassObj, new Object[] {});
   System.out.println("Got original password from private accessor: "
	+ o.toString());

   //make method accessible and set to it new value
   methods[1].setAccessible(true);
   System.out.println("Injecting new password using private mutator");
   methods[1].invoke(victimClassObj, new Object[] {"injected_password"});

   //get method's its new value
   o = methods[0].invoke(victimClassObj, new Object[] {});
   System.out.println("Got injected password from private accessor: "
	 + o.toString());

   //make field accessible and get its value
   fields[2].setAccessible(true);
   o = fields[2].get(victimClassObj);
   System.out.println("Got private field: " + o);

   //make field accessible and set to it new value
   System.out.println("Injecting value to a private field:");
   fields[2].set(victimClassObj, "new_default_value");

   //get field's its new value
   o = fields[2].get(victimClassObj);
   System.out.println("Got updated private field: " + o);

   //make field accessible and get its value
   fields[1].setAccessible(true);
   o = fields[1].get(victimClassObj);
   System.out.println("Got private static field: " + o);

   //make field accessible and set to it new value
   System.out.println("Injecting value to a private static final field:");
   fields[1].set(null, new Integer(2));

   //get field's its new value
   o = fields[1].get(victimClassObj);
   System.out.println("Got updated private static final field: " + o);

   }
   catch (InstantiationException e) {
	System.err.println("Error: could not instantiate: " + e);
   }

   catch (IllegalAccessException e) {
	System.err.println("Error: could not access: " + e);
   }

   catch (InvocationTargetException e) {
	System.err.println("Error: could not invoke the target: " + e);
   }
  }
}

The call to setAccessible() can be restricted if SecurityManager is set, then any attempt to call the method above will result in exception. If required, it is possible to grant permission java.reflect.ReflectPermission “suppressAccessChecks” using external java.policy file or by applying security policy programmatically. This permission will allow invocation of setAccessible(). My other post How to set SecurityManager and Java security policy programmatically explains how this can be achieved. Please note: by doing so, you can allow malicious access to your classes.

This is what happens when program executes:
I am using reflection, to get a print out of declared constructors, methods and fields. Following that, I am invoking private static and non-static method and attempting to change the value of private declared fields.

The program produces the following output:

Declared constructor name: VictimClass
        is accessible: false
        is private: true

Declared method name: setPassword
        is accessible: false
        is private: true
        is static: false

Declared method name: getUsersId
        is accessible: false
        is private: true
        is static: true

Declared method name: getPassword
        is accessible: false
        is private: true
        is static: false

Declared field name: password
        is accessible: false
        is private: true
        is static: false
        is final: false

Declared field name: USER_ID
        is accessible: false
        is private: true
        is static: true
        is final: true

Declared field name: privateFiled
        is accessible: false
        is private: true
        is static: false
        is final: false

Initiating reflection attack:
Oops... This private constructor was not  suppose to be invoked
Got user ID from private static accessor: 3452678
Got original password from private accessor: default_password
Injecting new password using private mutator
Got injected password from private accessor: injected_password
Got private field: default_value
Injecting value to a private field:
Got updated private field: new_default_value
Got private static field: 3452678
Injecting value to a private static final field:
Error: could not access: java.lang.IllegalAccessException: Field is final

As output shows above, it is not possible to set a value to the filed that is final. Therefore, it would be good idea to make fields final whenever possible. As it was shown before, it prevents reflection attack (when trying to set a new value), plus to that its good for performance optimization (memory allocation).

So what we got so far? When we have a POJO, it is possible to invoke private constructor, private static and non-static methods and change the value of private fields.

Enumerators on other hand do not allow invocation of their private constructors. An attempt to do so will result in IllegalArgumentException exception: “Cannot reflectively create enum objects”. Enums are safe against invocation of private constructors through reflection attacks.

Since enum object instances cannot be created through reflection, private non-static methods cannot be invoked. Having said that, it is still possible to invoke private static methods on enum using reflection, like on any other Java class.

Update: private non-static methods can be invoked on enum class, please refer to comments.

In conclusion, number of steps can be taken, in case someone really wants to prevent reflection attack on non-enum Java classes:

  1. Make fields final whenever possible
  2. Private constructor can throw an exception if there will be an attempt to invoke it.
  3. Applying security policy without ReflectPermission and setting security manager

I hope that I was descriptive enough here, I will appreciate your comments here.

The source code for this post was tested in my Eclipse and is attached.

Cheers

How to Set SecurityManager and Java Security Policy Programmatically

In this example I want to show how to use SecurityManager to prevent unauthorized access to private members of a Java class, for example using reflection to invoke private constructor. Besides that I also want to show how Java security policy can be set programmatically with permission allowing to invoke private constructor through reflection when security manager is in place.

Consider a POJO:

public final class VictimClass  {
	/**
	 * Private constructor that should
	 * not be invoked
	 */
	private VictimClass()  {
	   System.out.println("Instance created");
           System.out.println(
               "Constructor was made accessible");
	}
}

I want to prevent invocation of private constructor, by setting security manager. After first invocation attempt, I do want to invoke private constructor by granting required permission by refreshing current security policy.

This is my tester class:

import java.lang.reflect.Constructor;
import java.lang.ClassNotFoundException;
import java.lang.InstantiationException;
import java.lang.IllegalAccessException;
import java.lang.reflect.InvocationTargetException;
import java.lang.NoSuchMethodException;
import java.security.AccessControlException;
import java.lang.reflect.ReflectPermission;
import java.security.SecurityPermission;

public class Tester  {

	private static String CLASS_NAME = "VictimClass";
	private static Class victimClass = null;

	public static void main(String[] args)  {

	loadClass(victimClass, CLASS_NAME);

	//apply default policy with one permission
	System.setProperty("java.security.policy","default.policy");

	try {
	  //Setting security manager
	  SecurityManager sm = new SecurityManager();
	  System.setSecurityManager(sm);
	} catch (SecurityException e) {
	  System.err.println("Error: could not set security manager: " + e);
	}

	//first attempt to make constructor accessible
	try  {
	  makeConstructorAccessible();
	}
	catch (AccessControlException e) {
	  System.err.println(
		"Could not made constructor accessible: " + e.getMessage());
	}

	System.out.println("Applying ReflectPermission programmatically...");
	SecurityPolicy.getPolicy().addPermission(
		new ReflectPermission("suppressAccessChecks"));
	SecurityPolicy.getPolicy().addPermission(
		new SecurityPermission("setPolicy"));
	SecurityPolicy.getPolicy().refresh();
	makeConstructorAccessible();
	}

private static void loadClass(Class clazzor, String className)  {
	Thread thread = Thread.currentThread();
	ClassLoader classLoader =
				thread.getContextClassLoader();

	try {
	 victimClass = Class.forName(className, true, classLoader);
	}
	catch (ClassNotFoundException e) {
	 System.err.println("Error: could not find class: "
			+ CLASS_NAME);
	}
}

private static void makeConstructorAccessible()  {
	Constructor[] constructors =
			victimClass.getDeclaredConstructors();
	//make constructor accessible
	constructors[0].setAccessible(true);

   try {
	System.out.println(
	"Creating new instance by invoking private constructor");
	constructors[0].newInstance(new Object[] {});
   }
	catch (InstantiationException e) {
	  System.err.println("Error: could not instantiate: " + e);
	}
	catch (IllegalAccessException e) {
	  System.err.println("Error: could not access: " + e);
	}
	catch (InvocationTargetException e) {
	  System.err.println("Error: could not invoke the target: " + e);
	}
  }
}

This is what happens when program executes:

Before setting SecurityManager, I am applying default security policy from external file with security permission “setPolicy”, that will allow me to reset new security policy in the future.

My default security policy:

grant {
	permission java.security.SecurityPermission "setPolicy";
};

When SecurityManager is set, it restricts everything except whats permitted by security policy that was set previously. You can view list of Java permissions that can be set here.

By default, the private constructors,methods and fields are inaccessible. So if you want to use reflection, and invoke private constructor of this POJO, it will result in
IllegalAccessException since the constructor above has private modifier.

This restriction can be bypassed by calling parent method setAccessible(). To remind: java.lang.reflect.Constructor, java.lang.reflect.Method and java.lang.reflect.Field extend from parent java.lang.reflect.AccessibleObject class.

By calling inherited parent method setAccessible(), private variables and methods including private constructors become accessible.

With SecurityManager set, an attempt to invoke setAccessible() will result in AccessControlException. Following that, I am granting required ReflectPermission suppressAccessChecks by applying my own security policy. This will allow me to invoke private constructor in my POJO.

Now, having said that, I have to say that granting ReflectPermission with action suppressAccessChecks can be extremely dangerous as it allows private constructors to become accessible, as the example above shows. Not only constructors, but inaccessible fields and methods can become accessible, which can allow room for reflection attacks. In my other post Hack any Java class using reflection attack I explain how this can be achieved.

When I am applying my own security policy, please note that I am granting again security permission “setPolicy”. Because I am reseting default policy set previously, I have to grant “setPolicy” permission again if I want to keep applying new security policies in the future at run time of this program.

Below is my own implementation of java.security.Policy class, I tried to put enough comments to make things straight forward to you readers:

import java.security.Policy;
import java.security.CodeSource;
import java.lang.reflect.ReflectPermission;
import java.security.SecurityPermission;
import java.security.*;
import java.lang.RuntimePermission;
import java.util.*;

public class SecurityPolicy extends Policy {

	private PermissionCollection perms = null;

    //lazy initialization class holder
    private static class SecurityPolicyHolder {
	private static final SecurityPolicy policy = new SecurityPolicy();
    }

    private SecurityPolicy() {
	perms = new Permissions();
    }

    public static SecurityPolicy getPolicy() {
	return SecurityPolicyHolder.policy;
    }

    public PermissionCollection getPermissions(CodeSource codesource) {
        return perms;
    }

    //invoked when new Permission is added to the current security Policy
	public boolean implies(ProtectionDomain domain, Permission permission)  {

	//get permission collection from the domain
	PermissionCollection domainPermissions = domain.getPermissions();

	//get enumeration of permission elements
	Enumeration<Permission> permissions = domainPermissions.elements();

	//convert to array list (dont have to, i just dont like enumerations)
	ArrayList<Permission> list = Collections.list(permissions);

	//Checks to see if the specified permission is
	//implied (subset of) by the collection of
	//Permission objects held in this PermissionCollection
	if (!domainPermissions.implies(permission)) {

		//permission collection in the domain is read-only,
		//Exception will be thrown if Permission object
		//is added to read-only collection
		if (domainPermissions.isReadOnly()) {

			//Because collection is read-only,
			//add Permission objects to the local
			//permission collection instead
			for (Permission p :list) {
				if (!perms.implies(p)) {
				   perms.add(p);
				}
			}

			//assign local permission collection as a
			//domain permission collection
			domainPermissions = perms;
		}
		else {
			//if domain permission collection is not read only,
			//just add new permission to it
		  domainPermissions.add(permission);
		}

		//check if now domain has the new Permission
		return domainPermissions.implies(permission);
	}

		return false;
	}

	public void addPermission(Permission permission)  {
        perms.add(permission);
	}
        //you can write your own implementation
	//of refresh method
        @Override
	public void refresh() {
         Policy.setPolicy(this);
	}
}

The following shows program output. Please not that first attempt to make private constructor accessible resulted in exception. After required permission was granted, new object instance was succesfully created through reflection:

Could not made constructor accessible:
access denied (java.lang.reflect.ReflectPermission suppressAccessChecks)
Applying ReflectPermission programmatically...
Creating new instance by invoking private constructor
Constructor was made accessible
Instance created

Please note:
I did test this code. But I am not sure whether my SecuriyPolicy class implemented efficiently. The source code for this post is attached.

set java security policy sourcecode

Hibernate – How To Map Two Collections of The Same Type in The Same Entity

Recently during development, I encountered a situation where I had to map two collections in the same entity, having collections and the entity it self of the same type.

I had persistent entity – Rule. Rule could have children rules: “action” rules and “else” rules. Children rules were also of type Rule.

Basically it was a one-to-many relationship mapping of an entity to itself twice:
Entity Rule could have two different collections of the same object type – Rule. The collections represented “action” and “else” rules.

The challenge that I faced was during XML generation of the persisted entity Rule:

I could successfully persist entity Rule with its children Rules to DB. But, when I was generating the XML, Hibernate was not able to differentiate between “action” and “else” rules and was adding every child Rule to each collection. This was causing the same entity to appear once in each collection:

<?xml version="1.0" encoding="UTF-8"?>
<Rule id="1">
	<ruleType>-1</ruleType>
	<actionChildren>
		<rule>1</rule>
		<rule>2</rule>
	</actionChildren>
	<elseChildren>
		<rule>1</rule>
		<rule>2</rule>
	</elseChildren>
</Rule>

I needed to “tell” somehow to Hibernate which child entity Rule should be added to which collection. I am not sure if my solution is the best in this case, but I created a discriminator property inside entity Rule – “ruleType”.

Respectively, in HBM file, in the mappings of one-to-many relationships, I specified by using SQL query, which rules should be added to the collection when XML is generated. The SQL query was inside where attribute of <list> element.

It done the trick for me – when I was adding a child rule to a parent entity, I was specifying child rule type. Therefore, Hibernate was generating XML correctly by adding “action” rules and “else” rules to their respective collections.

Here is entity Rule:

package org.example.rules;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

public class Rule implements
			Serializable {

private static final long
	serialVersionUID = -76784L;

private int idx;
private int ruleType = -1;
private Rule parentRule = null;

private List<Rule> actionChildren =
		new ArrayList<Rule>();

private List<Rule> elseChildren =
		new ArrayList<Rule>();

/**
 * Default constructor
 */
public Rule() {

}

/**
 * @return the 'action' children
 */
public List<Rule> getActionChildren() {
	return actionChildren;
}

/**
 * @param children
 *            'action' children to set
 */
public void setActionChildren(List<Rule> actionChildren) {
	this.actionChildren = actionChildren;
}

/**
 * @return the 'else' children
 */
public List<Rule> getElseChildren() {
	return elseChildren;
}

/**
 * @param children
 *            'else' children to set
 */
public void setElseChildren(List<Rule> elseChildren) {
	this.elseChildren = elseChildren;
}

/**
 * Adds an 'action' child to the current rule
 *
 * @param actionChild
 *            The rule to be added as a child
 */

public void addActionChild(Rule actionChild) {
	if (!this.actionChildren.contains(actionChild)) {
		actionChild.setParentRule(this);
		this.actionChildren.add(actionChild);
	}
}

/**
 * Adds an 'else' child to the current rule
 *
 * @param elseChild
 *            The rule to be added as a child
 */

public void addElseChild(Rule elseChild) {
	if (!this.elseChildren.contains(elseChild)) {
		elseChild.setParentRule(this);
		this.elseChildren.add(elseChild);
	}
}

/**
 * @return the ruleType
 */
public int getRuleType() {
	return ruleType;
}

/**
 * @param ruleType
 *            the ruleType to set
 */
public void setRuleType(int ruleType) {
	this.ruleType = ruleType;
}

/**
 * @return collection index
 */
public int getIdx() {
	return idx;
}

/**
 * Sets collection index
 * @param collection index
 */
public int setIdx(int idx) {
	this.idx = idx;
}

/**
 * @return parent rule of the current rule
 */
public Rule getParentRule() {
	return parentRule;
}

/**
 * @param ruleParent
 *            the ruleParent to set
 */
public void setParentRule(Rule parentRule) {
	this.parentRule = parentRule;
}
}

Rule HBM file:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
<class name="org.example.rules.Rule"
	table="org_example_rules_Rule" node="Rule">

<id name="id" column="id" node="@id"
			unsaved-value="0">
	<generator class="native" />
</id>

<!--
Used to help Hibernate to discriminate
between children rules
-->
<property name="ruleType" column="ruleType"
								node="ruleType" />
<!--
Attribute 'where' holds SQL query used to help Hibernate
to discriminate between children rules of type 'action'
and children rules of type 'else'.

Since two children rule lists in the current HBM are of
the same type (org.example.rules.Rule), Hibernate needs
a 'hint' how to discriminate which rules belong to
which list when XML is generated.

If ruleType equals to '1', it means that the child
rule is 'action' rule.

If ruleType equals to '2', it means that the child
rule is 'else' rule.
-->
<list name="actionChildren" embed-xml="true"
		where="ruleType=1" cascade="all">

	<key column="parentrule_id" />
	<list-index column="idx" base="0" />
	<one-to-many class="org.example.rules.Rule"
		node="rule" embed-xml="false" />
</list>

<!--
If ruleType equals to '2', it means that the child
rule is 'else' rule.
-->
<list name="elseChildren" embed-xml="true"
		where="ruleType=2" cascade="all">

	<key column="parentrule_id" />
	<list-index column="idx" base="0" />
	<one-to-many class="org.example.rules.Rule"
		node="rule" embed-xml="false" />

</list>

<!--
Read-only index column, represents position of
the element in the list
-->
<property name="idx" column="idx" node="idx"
		update="false" insert="false" type="int" />

<!--
Embed XML must be equals to 'false',
otherwise when XML is generated for
children rules, parent XML will be
generated recursively
-->
<many-to-one name="parentRule" node="parentRule"
	column="parentrule_id" class="org.example.rules.Rule"
	not-null="false" insert="false" update="false"
	embed-xml="false" />

</class>
</hibernate-mapping>

Generally, I would not advise to design persistent entities in this way, it can create problem later on. For example if there is a need to delete child entities. It can become a bit tricky, since entity has relationship to it self.

Suggestions? Flames?

Brainteaser: Hidden Iterators

… While locking can prevent iterators from throwing ConcurrentMofdificationException, You have to remember to use locking everywhere a shared collection might be iterated. This is trickier than it sounds …

Brian Goetz p.83-84

Question: The following code could throw ConcurrentMofdificationException, even though add() is synchronized, why?

public class HiddenIterator  {
     private final Set set = new HashSet();

public synchronized void add(Integer i) {
     set.add(i);
}

public synchronized void remove(Integer i) {
     set.remove(i);
}

public void addTenThings() {
   Random r = new Random();
   for (int index = 0; index &lt; 10;  index++;) {
       add(r.nextInt());
   }

   System.out.println("Added ten elements to set: " + set);
}
}

Looking forward for your answers dear readers

Singleton Pattern and Problem With Double Checked Locking

There are several ways to initialize singleton object. Some are thread safe and some are not. Until the last two days I thought that double-checked locking idiom offers the best solution for singleton initialization in multi threaded environment. Well its not.

To begin, I want to describe briefly several ways to initialize singleton:

  • Lazy initialization
  • Eager initialization
  • DCL
  • Class holder lazy initialization
  • Enum singleton

Lazy initialization
The goal of lazy initialization was to defer initialization of an object until it is actually needed, while making sure that initialization is done only once. Lazy initialization example illustrated below:

public class Singleton{

	private static Singleton instance = null;

	private Singleton() {  }

	public static Singleton getInstance() {
		if (instance == null)  {
		instance = new Singleton();
	}
        return instance;
    }
}

This will work fine in single-threaded environment. Unfortunately since getInstance() is not synchronized, two different instances of the object can be returned if two threads will access getInstance() method concurrently. Which makes this lazy initialization unsafe in multi threaded environment.

Unsafe lazy initialization can be fixed by making getInstance() synchronized:


	public class Singleton{

	private static Singleton instance = null;

	private Singleton() {  }

	public static synchronized Singleton getInstance() {
		if (instance == null)  {
			instance = new Singleton();
		}
		return instance;
	}
	}

However, in this case there is performance hit for every invocation of getInstance() method. Synchronized methods runs very slow compared to unsynchronized methods. I haven’t tested this issue my self, so i cannot tell by how much slower.

Eager initialization
By using eager initialization, the synchronization cost incurred for each method call is eliminated:

	public class Singleton{
		private static Singleton instance = new Singleton();

		private Singleton() {  }

		public static Singleton getInstance() {
			return instance;
		}
	}

The problem with eager initialization that Singleton object is instantiated regardless whether it is going to be used or not.

DCL
Double-checked locking (DCL) idiom was created to allow lazy initialization of a singleton object, without performance reducing costs as a result of synchronization. Unfortunately it does not work. Lets have a look why:

public class Singleton {

  private static Singleton instance = null;

  private Singleton() {  }

  public static Singleton getInstance() {
	if (instance == null)  {
		synchronized(Singleton.class)  {
			if (instance == null)  {
				instance = new Singleton();
			}
		}
	}
	return instance;
	}
}

First there is a check whether initialization is needed with out synchronization, and if the instance is not null – then use it.
Otherwise, synchronize and check again if instance is null by making sure that only one thread will initialize the shared Singleton.

The problem with DCL is that code of fetching reference to constructed Singleton object does not require synchronization.
Lets say that thread ‘a’ has entered synchronized block, made the instance not null but hasn’t executed the constructor yet. At this stage thread ‘b’ preempts thread ‘a’. Thread ‘b’ checks if the instance is not null, and since its not, it returns reference to a partially constructed Singleton object.

In other words – thread ‘b’ sees a current value of the Singleton object reference instead of its stale value, which causes the object to be seen in invalid or incorrect state.

Class holder lazy initialization

Instead of DCL, lazy initialization class holder idiom offers better solution for singleton initialization in multi threaded environment, with the same benefits as DCL:

public class SingletonFactory {

  private static class SingletonHolder {
     public static Singleton instance = new Singleton();
  }

  public static Singleton getInstance()  {
     return SingletonHolder.instance;
  }
}

The SingletonHolder class initialization is deferred until its actually used, and because Singleton is initialized with static initializer, no additional synchronization is needed.
The first invocation of getInstance() by any thread causes SingletonHolder to be loaded and initialized during which time the Singleton is initialized through static initializer.

Enum singleton
Joshua Bloch in his book “Effective Java” offers a new interesting solution to initialize a Singleton by using Enum with a single type:

public class SingletonEnum {
  INSTANCE;

  public void someMethod() {
     ...
  }

  public void anotherMethod() {
     ...
  }
}

Joshua claims:

“…a single-element enum type is the best way to implement a singleton…”

Some people may argue against this approach by saying that this is not a class, but an enum – it enumarates plus enums cannot be subclassed. Well in case of a singleton there is no point in subclassing, since singletons have private constructors and singletons dont really ment to be subclassed. Lets have a look if Enum singleton is indeed the best solution so far:

1. Enum singleton is final
2. It is serializable
3. It is a single instance in multithreaded environment
4. Does not allow invokation of private constructors through reflection attacks

I think its quite original solution.

I will appreciate your comments regarding this post. Cheers.

Resources:
Effective Java
Java Concurrency in Practice

Double-checked locking and the Singleton pattern