Patch For Flex Builder 3 Plugin to Work With Eclipse 3.4 (Ganymede)

I installed few days ago new version of Eclipse (Ganymede) and today I tried to install flex builder v3.

The installation went fine, but I got the following exception when trying to open Flex editor in Eclispe: “…org.eclipse.jface.util.Assert$AssertionFailedException: Assertion failed…”.

After Googling for some time I came across the following fix. So… there you go

Australian Citizenship – The lodgement

Finally the moment that I have been anticipating for has come – today I have lodged my application to become Australian citizen. Wooo hoooo :D

I’ve been waiting for this moment for the past 5 years, and now this is a dream come true! I still remember that day, that moment when I was sitting in an airplane and starring outside at Brisbane airport on a rainy July day…

.. and look at me now – I am applying to become a proud citizen of this beautiful and amazing country…

I cant really describe this feeling, but in one word?
Priceless …

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