<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">
  <title>Obi Ezechukwu's blog</title>
  <link rel="alternate" type="text/html" href="http://www.javaworld.com/community/blog/20968"/>
  <link rel="self" type="application/atom+xml" href="http://www.javaworld.com/community/blog/20968/atom/feed"/>
  <id>http://www.javaworld.com/community/blog/20968/atom/feed</id>
  <updated>2009-03-15T08:35:00-04:00</updated>
  <entry>
    <title>Compact Equals</title>
    <link rel="alternate" type="text/html" href="http://www.javaworld.com/community/node/8013" />
    <id>http://www.javaworld.com/community/node/8013</id>
    <published>2011-06-22T10:29:47-04:00</published>
    <updated>2011-06-22T10:29:48-04:00</updated>
    <author>
      <name>Obi Ezechukwu</name>
    </author>
    <category term="fast compact legible java equals" />
    <summary type="html"><![CDATA[<!--paging_filter--><p>
Reposted from: <a href='http://www.obix-labs.com/blogs/highOctaneJava/' rel="nofollow" rel="nofollow">http://www.obix-labs.com/blogs/highOctaneJava/</a>
</p>
    ]]></summary>
    <content type="html"><![CDATA[<!--paging_filter--><p>
Reposted from: <a href='http://www.obix-labs.com/blogs/highOctaneJava/' rel="nofollow">http://www.obix-labs.com/blogs/highOctaneJava/</a>
</p>
<p>
In this post, I will demonstrate an effective and compact way to override Java's <a href='http://download.oracle.com/javase/6/docs/api/java/lang/Object.html#equals(java.lang.Object)' rel="nofollow">equals(...)</a> method. To begin, please <a href='https://www.obix-labs.com/blogs/highOctaneJava/resource/2011/compact-equals.zip' rel="nofollow">download</a> the reference source code for the article and open it up in your preferred IDE. When laid out in the <a href='http://www.eclipse.org/ ' rel="nofollow">Eclipse IDE</a>, the project will look as follows:
</p>
<p></p>
<p>
The sample consists of two implementations of an address class, both of which are identical in every way except for their respective implementations of <a href='http://download.oracle.com/javase/6/docs/api/java/lang/Object.html#equals(java.lang.Object)' rel="nofollow">equals(...)</a>. The first class <a href='https://www.obix-labs.com/blogs/highOctaneJava/resource/2011/compact-equals.zip' rel="nofollow">Address.java</a> implements <a href='http://download.oracle.com/javase/6/docs/api/java/lang/Object.html#equals(java.lang.Object)' rel="nofollow">equals(...)</a> in the more common longform fashion, whilst  <a href='https://www.obix-labs.com/blogs/highOctaneJava/resource/2011/compact-equals.zip' rel="nofollow">AddressV2.java</a> uses my compact solution. Before looking at the alternative implementations, let us first list the attributes of these classes on which the equality test will be based:</p>
<p></p>
<p>	private Integer houseNumber;<br />
	private String street;<br />
	private String city;<br />
	private String stateOrProvince;<br />
	private String country;</p>
<p>
</p>
<p>
Now, let us look at the longform equality test based on these attributes, as implemented in <a href='https://www.obix-labs.com/blogs/highOctaneJava/resource/2011/compact-equals.zip' rel="nofollow">Address.java</a>, and, which is excerpted below. As you can see, it works by initially comparing the object references and type, and then proceeds to test each individual class attribute against the matching attribute value taken from the argument. It is this later part that consumes the most real estate, and which I also find more tedious to follow and code. </p>
<p></p>
<p>	@Override<br />
	public boolean equals(Object obj)<br />
	{<br />
		if (this == obj)<br />
			return true;<br />
		if (obj == null)<br />
			return false;<br />
		if (getClass() != obj.getClass())<br />
			return false;</p>
<p>		Address other = (Address) obj;</p>
<p>		if (city == null)<br />
		{<br />
			if (other.city != null)<br />
				return false;<br />
		}<br />
		else if (!city.equals(other.city))<br />
			return false;</p>
<p>		if (country == null)<br />
		{<br />
			if (other.country != null)<br />
				return false;<br />
		}<br />
		else if (!country.equals(other.country))<br />
			return false;</p>
<p>		if (houseNumber == null)<br />
		{<br />
			if (other.houseNumber != null)<br />
				return false;<br />
		}<br />
		else if (!houseNumber.equals(other.houseNumber))<br />
			return false;</p>
<p>		if (stateOrProvince == null)<br />
		{<br />
			if (other.stateOrProvince != null)<br />
				return false;<br />
		}<br />
		else if (!stateOrProvince.equals(other.stateOrProvince))<br />
			return false;</p>
<p>		if (street == null)<br />
		{<br />
			if (other.street != null)<br />
				return false;<br />
		}<br />
		else if (!street.equals(other.street))<br />
			return false;</p>
<p>		return true;<br />
	}</p>
<p>
</p>
<p>
What if it was possible to remove the need for the longform attribute comparisons? Surely this would make the method considerably shorter and easier to follow? This is precisely the approach taken in <a href='https://www.obix-labs.com/blogs/highOctaneJava/resource/2011/compact-equals.zip' rel="nofollow">AddressV2.java</a>, whose <a href='http://download.oracle.com/javase/6/docs/api/java/lang/Object.html#equals(java.lang.Object)' rel="nofollow">equals(...)</a> implementation is excerpted below.</p>
<p></p>
<p>	@Override<br />
	public boolean equals(Object obj)<br />
	{<br />
		boolean result;</p>
<p>		if (this == obj)<br />
			result = true;<br />
		else if (obj!=null &amp;&amp; getClass() == obj.getClass())<br />
		{<br />
			AddressV2 other = (AddressV2) obj;</p>
<p>			Object[] fields =<br />
				{houseNumber, street, city, stateOrProvince, country};</p>
<p>			Object[] otherFields =<br />
						{other.houseNumber, other.street, other.city,<br />
						other.stateOrProvince, other.country};</p>
<p>			result = Arrays.equals(fields, otherFields);<br />
		}<br />
		else result = false;</p>
<p>		return result;<br />
	}</p>
<p></p>
<p>I hope the reader will agree that the above implementation is not only considerably shorter but also more legible. It works simply by encapsulating the attribute values to be compared in two arrays: one for the instance on which the method is invoked; and the other for the object being compared to it. The two arrays can then simply be compared using the <a href='http://download.oracle.com/javase/6/docs/api/java/util/Arrays.html#equals(java.lang.Object[], java.lang.Object[])' rel="nofollow">Arrays.equals(...)</a> method; thus leading to a much more compact piece of code – hence the name of the technique.
</p>
<p>
Note however that if one of your class attributes is an array in itself, then you may want to consider performing the array comparison with the <a href='http://download.oracle.com/javase/6/docs/api/java/util/Arrays.html#deepEquals(java.lang.Object[], java.lang.Object[])' rel="nofollow">Arrays.deepEquals(...)</a> method, which is better suited to comparing arrays of arbitrary depth.
</p>
    ]]></content>
  </entry>
  <entry>
    <title>Obix Labs XConfig now available.</title>
    <link rel="alternate" type="text/html" href="http://www.javaworld.com/community/node/5732" />
    <id>http://www.javaworld.com/community/node/5732</id>
    <published>2010-11-04T05:13:42-04:00</published>
    <updated>2010-11-04T05:13:42-04:00</updated>
    <author>
      <name>Obi Ezechukwu</name>
    </author>
    <category term="Java Configuration Spring Property Annotations" />
    <summary type="html"><![CDATA[<!--paging_filter--><p>
Obix Labs are pleased to announce the official release of XConfig: a Spring compatiable Java/XML configuration library. It supports auto-reload, annotations, Spring property placeholders etc. Unlike Spring Config (JConfig) it does not require users to write new classes or to use property files.
</p>
    ]]></summary>
    <content type="html"><![CDATA[<!--paging_filter--><p>
Obix Labs are pleased to announce the official release of XConfig: a Spring compatiable Java/XML configuration library. It supports auto-reload, annotations, Spring property placeholders etc. Unlike Spring Config (JConfig) it does not require users to write new classes or to use property files.
</p>
<p>
For example, it can be integrated into a Spring application like so:</p>
<ul>
<li>
Annotations which are handled by the bean factory. For example: <br />
<div class="codeblock"><code>@FromConfiguration(&quot;/@London&quot;)<br />private String greetingInLondon;</code></div>
</li>
<li>
Property placeholders like:<br />
<div class="codeblock"><code>&lt;property name=&quot;greetingInLondon&quot; value=&quot;${/@London}&quot;/&gt;</code></div>
</li>
</ul>
</p>
<p>
XConfig supports modular XML configuration files. This modularity not only allows better organization of configuration data, but also means that you can seperate out configuration data based on deployment roles/profiles. For example database or production sensitive information which is only set by system administrators at deploy time can be encapsulated in a seperate and easy to understand file.
</p>
<p>
XConfig also supports auto-reload. This means that configuration changes can be detected almost immediately at runtime, thus removing the need to stop and restart applications when making configuration changes--although<br />
this feature is not enabled for Spring annotations or placeholders.
</p>
<p>
For more information, go to the site: <a href="http://www.obix-labs.com/display/jsp/technology/xconfig.jsp" title="http://www.obix-labs.com/display/jsp/technology/xconfig.jsp" rel="nofollow">http://www.obix-labs.com/display/jsp/technology/xconfig.jsp</a>
</p>
    ]]></content>
  </entry>
  <entry>
    <title>Epsilon 1.0.2 now available</title>
    <link rel="alternate" type="text/html" href="http://www.javaworld.com/community/node/5283" />
    <id>http://www.javaworld.com/community/node/5283</id>
    <published>2010-10-05T03:23:31-04:00</published>
    <updated>2010-10-05T03:23:32-04:00</updated>
    <author>
      <name>Obi Ezechukwu</name>
    </author>
    <category term="Java Latency Performance Monitoring" />
    <summary type="html"><![CDATA[<!--paging_filter--><p>Obix Labs are pleased to announce release 1.0.2 of the Epsilon performance/latency monitoring library. Epsilon allows you to define performance criterion for your applications and to monitor these during the application’s lifetime. Its API is as simple as that of a common logger. It even provides annotations, thereby removing the need to use its API directly.<br />
Its benefits can be summarised as follows:</p>
<ul>
<li> Spring Annotations and AOP support </li>
<li> Statistics collection/persistence </li>
<li> Lightweight and highly performant </li>
    ]]></summary>
    <content type="html"><![CDATA[<!--paging_filter--><p>Obix Labs are pleased to announce release 1.0.2 of the Epsilon performance/latency monitoring library. Epsilon allows you to define performance criterion for your applications and to monitor these during the application’s lifetime. Its API is as simple as that of a common logger. It even provides annotations, thereby removing the need to use its API directly.<br />
Its benefits can be summarised as follows:</p>
<ul>
<li> Spring Annotations and AOP support </li>
<li> Statistics collection/persistence </li>
<li> Lightweight and highly performant </li>
<li> Support for custom notifications, e.g. log alerts, email etc </li>
<li> Easy to extend </li>
<li> Free and open source </li>
</ul>
<p>For more details, please see the link: <a href="http://www.obix-labs.com/display/jsp/technology/epsilon.jsp" title="http://www.obix-labs.com/display/jsp/technology/epsilon.jsp" rel="nofollow">http://www.obix-labs.com/display/jsp/technology/epsilon.jsp</a></p>
    ]]></content>
  </entry>
  <entry>
    <title>Generating Passwords in Java using the obix commons library</title>
    <link rel="alternate" type="text/html" href="http://www.javaworld.com/community/node/4687" />
    <id>http://www.javaworld.com/community/node/4687</id>
    <published>2010-07-20T04:30:56-04:00</published>
    <updated>2010-07-20T04:30:56-04:00</updated>
    <author>
      <name>Obi Ezechukwu</name>
    </author>
    <category term="commons" />
    <category term="Generate" />
    <category term="java" />
    <category term="obix" />
    <category term="Password" />
    <summary type="html"><![CDATA[<!--paging_filter--><p>Learn how to generate strong and secure passwords in Java using functionality available in the latest release of the obix commons library.</p>
<p>To access the sample application and related documentation, please see the URL: <a href="http://www.obix-labs.com/wiki/bin/view/Commons/PasswordGenerator" title="http://www.obix-labs.com/wiki/bin/view/Commons/PasswordGenerator" rel="nofollow" rel="nofollow">http://www.obix-labs.com/wiki/bin/view/Commons/PasswordGenerator</a>. The samples and documentation demonstrate the generation of simple passwords to strong passwords encapsulating a variety of rules e.g. mixture of lower and upper case, numbers and punctuation symbols.</p>
    ]]></summary>
    <content type="html"><![CDATA[<!--paging_filter--><p>Learn how to generate strong and secure passwords in Java using functionality available in the latest release of the obix commons library.</p>
<p>To access the sample application and related documentation, please see the URL: <a href="http://www.obix-labs.com/wiki/bin/view/Commons/PasswordGenerator" title="http://www.obix-labs.com/wiki/bin/view/Commons/PasswordGenerator" rel="nofollow">http://www.obix-labs.com/wiki/bin/view/Commons/PasswordGenerator</a>. The samples and documentation demonstrate the generation of simple passwords to strong passwords encapsulating a variety of rules e.g. mixture of lower and upper case, numbers and punctuation symbols.</p>
    ]]></content>
  </entry>
  <entry>
    <title>Handling command line and console input in Java</title>
    <link rel="alternate" type="text/html" href="http://www.javaworld.com/community/node/4624" />
    <id>http://www.javaworld.com/community/node/4624</id>
    <published>2010-07-13T12:01:16-04:00</published>
    <updated>2010-07-13T12:01:16-04:00</updated>
    <author>
      <name>Obi Ezechukwu</name>
    </author>
    <category term="Command" />
    <category term="console" />
    <category term="Input" />
    <category term="java" />
    <category term="Line" />
    <summary type="html"><![CDATA[<!--paging_filter--><p>Learn how to handle command line and console input in Java using functionality available in the latest<br />
<a href="http://www.obix-labs.com/display/jsp/technology/commons.jsp" rel="nofollow" rel="nofollow">obix commons</a> release. The functionality removes the untidy code associated with prompting for input, validating input and handling input errors. It provides concise code and classes which can be used to read and validate several different types of input e.g. multi-choice input, numeric input, file paths and email validation.</p>
    ]]></summary>
    <content type="html"><![CDATA[<!--paging_filter--><p>Learn how to handle command line and console input in Java using functionality available in the latest<br />
<a href="http://www.obix-labs.com/display/jsp/technology/commons.jsp" rel="nofollow">obix commons</a> release. The functionality removes the untidy code associated with prompting for input, validating input and handling input errors. It provides concise code and classes which can be used to read and validate several different types of input e.g. multi-choice input, numeric input, file paths and email validation.</p>
<p>For more details, please see associated <a href="http://www.obix-labs.com/wiki/bin/view/Commons/ConsoleInputHandling" rel="nofollow">wiki entries</a></p>
    ]]></content>
  </entry>
  <entry>
    <title>Performance Monitoring with Spring AOP</title>
    <link rel="alternate" type="text/html" href="http://www.javaworld.com/community/node/3763" />
    <id>http://www.javaworld.com/community/node/3763</id>
    <published>2009-11-30T03:24:32-05:00</published>
    <updated>2009-11-30T03:29:12-05:00</updated>
    <author>
      <name>Obi Ezechukwu</name>
    </author>
    <category term="AOP" />
    <category term="JAMon" />
    <category term="performance" />
    <category term="Spring" />
    <summary type="html"><![CDATA[<!--paging_filter--><p>
Functional requirements for mission critical applications often include software service level agreements (SLAs), which specify the maximum allowable latency for specific operations. Such requirements necessitate the monitoring of application performance, either at system testing stage or post deployment. This article will demonstrate how real-time performance tracing/monitoring can be achieved for spring applications using the functionality provided in <a href="http://www.springframework.org/" rel="nofollow" rel="nofollow">Spring AOP</a> and the <a href="http://logging.apache.org/log4j/1.2/index.html" rel="nofollow" rel="nofollow">Apache Log4j</a> toolkit.
</p>
    ]]></summary>
    <content type="html"><![CDATA[<!--paging_filter--><p>
Functional requirements for mission critical applications often include software service level agreements (SLAs), which specify the maximum allowable latency for specific operations. Such requirements necessitate the monitoring of application performance, either at system testing stage or post deployment. This article will demonstrate how real-time performance tracing/monitoring can be achieved for spring applications using the functionality provided in <a href="http://www.springframework.org/" rel="nofollow">Spring AOP</a> and the <a href="http://logging.apache.org/log4j/1.2/index.html" rel="nofollow">Apache Log4j</a> toolkit.
</p>
<p><strong>Introduction</strong></p>
<p>
Assume that as a solution developer/designer, you are given a list of semi-feasible functional requirements which a proposed application has to meet. Whilst reading through the list you parrot the seemingly non-controversial contents back to yourself. That is of course until you reach a line that reads something along the lines of "requests of type ‘y’ have to complete in ‘x’ seconds at the most".
</p>
<p>
Given that a typical application will have several points of failure which are not within your control as a solution designer, you will be forgiven for going back to your user base and explaining that such a requirement is quite simply not feasible. If you are really unlucky, you may have to go home and start working on yet another revision of your curriculum vitae. But since most users are actually reasonable people, you will probably achieve a compromise along the lines of "if requests of type ‘y’ are taking longer than ‘x’, then perform this action". Suffice it to say that the action to be performed falls under the general heading "details"; but you would have at least reduced your requirement to something a bit more tractable.
</p>
<p>
This type of functional requirement is no longer uncommon and is often referred to, interchangeably either as a Latency Requirement or Software Service Level Agreement (SLA for short). SLAs generally take the form "operations of type 'y' must complete within 'x' units of time". As an example, the backend for an online stock trading platform might include a restriction of the form "all trades must be submitted to the exchange within 5 seconds of being placed".
</p>
<p>
The challenges that performance SLAs present to software developers are two-fold. At the design and implementation phase, the emphasis is on ensuring that the application is built in such a way as to encourage fast enough throughput in order to bring the average-case latency in line with the SLA. The second challenge concerns the monitoring of the application's performance in real-time, either at system testing stage or post deployment, so as to detect/predict possible breaches of its SLA.
</p>
<p>
In this tutorial, we will focus on how to leverage the functionality of the <a href="http://www.springframework.org/" rel="nofollow">Spring Framework</a> to achieve real-time performance measurement and monitoring. This is a hands-on tutorial, so please download the companion <a href="http://www.obix-labs.com/staff/obi/jw/pmwsa/code-archive.zip" rel="nofollow">source archive</a> and load the files into your preferred IDE. The source files which comprise the archive are shown in <a href="http://www.obix-labs.com/staff/obi/jw/pmwsa/images/figure1.JPG" rel="nofollow">Figure 1</a>.
</p>
<p align="center">
</p>
<p>
Note that, in addition to the Spring binaries, the lib folder of the companion archive also contains the binaries for the following open-source dependencies:</p>
<ul>
<li><a href="http://logging.apache.org/log4j/1.2/index.html" rel="nofollow">Apache Log4J</a></li>
<li><a href="http://jamonapi.sourceforge.net/" rel="nofollow">JAMon</a></li>
</ul>
</p>
<p>
Although not strictly necessary, it is advisable to download <a href="http://logging.apache.org/chainsaw/index.html" rel="nofollow">Apache’s Chainsaw</a> application, which can be used for viewing the logs of remote applications.
</p>
<p>
For the benefit of the uninitiated, we will begin with a very simple primer on Aspect Oriented Programming (AOP); this will cover the basics needed to follow the examples in this article. For more detailed information, please see the links provided in the resources section. If you are already familiar with AOP, it may well be better to skip the next subsection altogether.
</p>
<p><strong>A Primer on AOP</strong></p>
<p>
Object Oriented (OO) programming provides for application entities and behaviour to be encapsulated in a set of classes. Although this is quite effective, and would suffice for most application, the truth is that there is certain behaviour in applications that appear everywhere and yet do not really belong anywhere. Examples abound when you look at non-AOP code in detail: the logging of entry and exit trace messages, operation-level authentication and authorization, and transaction control to name but a few.
</p>
<p>
AOP, or Aspect Oriented Programming to give it its full name, is a means of modularizing and externalizing functionality that spans multiple classes. In AOP terminology such functionality are referred to as cross cutting concerns. If we go back to the example on logging, a logging/error-reporting strategy actually spans multiple classes, and may not really be relevant to the functionality encapsulated by the logged classes. With AOP the log strategy can be externalized as a concern to which classes and methods can be added as and when necessary.
</p>
<p>
The main concepts from AOP which we are interested in for the purposes of this tutorial are: cross cutting concerns; advice; pointcut; and aspect. The first of these has already been described in the preceding paragraphs; the others are described next.
</p>
<p><ul>
<li>
Advice:  Encapsulates externalized behaviour which can be applied to class instances at configured points during the execution of an application; for example, the logging of an entry or exit trace message can be thought of as advice types. Advice can also be thought of as the physical code which models/implements the logic of a cross cutting concern.
</li>
<li>
Pointcut:  A point in the execution of a program at which cross cutting concerns should be applied. This is the point at which the code encapsulated by an advice is executed.
</li>
<li>
Aspect:  An aspect is the combination of an advice and one or more pointcut definitions.
</li>
</ul>
</p>
<p>
For more information on AOP, please see the resources section of this article. In the next section we will look at a basic service implementation, whose performance we will monitor via Spring AOP.
</p>
<p><strong>The Service to Monitor</strong></p>
<p>
The service to monitor is defined by the contract interface <code>com.myorg.service.MyService</code>, where the operation being monitored are implementations of the <code>epsilon()</code> method.
</p>
<p>
The objective of this tutorial is to show how the start and end time of invocations of this method can be intercepted, so as to provide the duration of such invocations.
</p>
<p>
We will focus on two means of monitoring with Spring AOP, with Spring's own <code>PerformanceMonitorInterceptor</code> and the <code>JamonPerformanceMonitorInterceptor</code>. The latter, although part of the spring distribution, relies on the JAMon application monitoring library. It is worth stating that the full features of JAMon (specifically the monitoring web-based UI) is only really available to web applications, and not standalone Java apps.
</p>
<p>
Although separate implementations of the service are provided for the Spring and JAMon interceptor examples, this is not a necessity for real world implementations. As you will see, the reason for doing so is merely to ensure clarity of object hierarchies in the tutorial's Spring configuration file.
</p>
<p>
The first example, covered in the following section, looks at Spring's <code>PerformanceMonitorInterceptor</code>.
</p>
<p><strong>Monitoring with Spring's PerformanceMonitorInterceptor</strong></p>
<p>
Using Spring's performance monitor is quite simple and can be done without embedding profiling code directly into application classes. To examine how this is done, we first of all need an implementation of the service interface <code>com.myorg.service.MyService</code>; this is provided by the class <code>com.myorg.service.springmon.MyServiceSpringImpl</code> which is shown in Listing 1.
</p>
<p>Listing 1: MyServiceSpringImpl</p>
<p>
<div class="codeblock"><code>package com.myorg.service.springmon;<br /><br />import com.myorg.service.MyService;<br /><br />public class MyServiceSpringImpl implements MyService<br />{<br />	protected static final long DEFAULT_SLEEP_INTERVAL = 100;<br />	private long sleepInterval;<br /><br />	public MyServiceSpringImpl()<br />	{<br />		setSleepInterval(DEFAULT_SLEEP_INTERVAL);<br />	}	<br />	<br />	public void epsilon()<br />	{<br />		try{<br />			Thread.sleep(getSleepInterval());	<br />		}catch (InterruptedException int_exce){<br />			throw new RuntimeException(&quot;Service interrpted. Exiting.&quot;, <br />										int_exce);<br />		}<br />	}<br /><br />	public long getSleepInterval()<br />	{return sleepInterval;}<br /><br />	public void setSleepInterval(long sleepInterval)<br />	{this.sleepInterval = sleepInterval;}<br />}</code></div>
</p>
<p>
The implementation of the contract method <code>epsilon()</code> simply causes the thread to sleep for a preset interval. Consequently, we should expect the performance monitor to register a value reasonably close to the sleep interval.
</p>
<p>
To make use of this service, we have to declare it in the application's Spring configuration file. Not only that, but we also have to indicate that the <code>epsilon()</code> method is a pointcut at which we want monitoring advice executed in any thread of execution cutting across it. The snippet of the configuration to which this relates is shown in Listing 2, which is an excerpt of the application configuration file <code>beans-context.xml</code>.
</p>
<p><strong>Listing 2: beans-context.xml</strong></p>
<p>
<div class="codeblock"><code>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;<br />&lt;beans xmlns=&quot;http://www.springframework.org/schema/beans&quot;<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; xmlns:aop=&quot;http://www.springframework.org/schema/aop&quot;<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; xsi:schemaLocation=&quot;http://www.springframework.org/schema/beans 		<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 	<a href="http://www.springframework.org/schema/beans/spring-beans-2.0.xsd<br />" title="http://www.springframework.org/schema/beans/spring-beans-2.0.xsd<br />" rel="nofollow">http://www.springframework.org/schema/beans/spring-beans-2.0.xsd<br /></a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 	<a href="http://www.springframework.org/schema/aop" title="http://www.springframework.org/schema/aop" rel="nofollow">http://www.springframework.org/schema/aop</a> 	<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 	<a href="http://www.springframework.org/schema/aop/spring-aop-2.0.xsd&quot;&gt;<br />" title="http://www.springframework.org/schema/aop/spring-aop-2.0.xsd&quot;&gt;<br />" rel="nofollow">http://www.springframework.org/schema/aop/spring-aop-2.0.xsd&quot;&gt;<br /></a>	&lt;bean id=&quot;springMonitoredService&quot;<br />		class=&quot;com.myorg.service.springmon.MyServiceSpringImpl&quot;/&gt;<br /><br /><br />	&lt;bean id=&quot;springMonitoringAspectInterceptor&quot; 		<br />class=&quot;org.springframework.aop.interceptor.PerformanceMonitorInterceptor&quot;&gt;<br />		&lt;property name=&quot;loggerName&quot; 	<br />				value=&quot;com.myorg.SPRING_MONITOR&quot;/&gt;		<br />	&lt;/bean&gt;<br />	<br />		<br />	&lt;aop:config&gt;<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 		&lt;aop:pointcut id=&quot;springMonitoringPointcut&quot;<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; expression=&quot;execution(* com.myorg.service..MyServiceSpringImpl.epsilon(..))&quot;/&gt;<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 	<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <br /><br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 		&lt;aop:advisor pointcut-ref=&quot;springMonitoringPointcut&quot; <br />			advice-ref=&quot;springMonitoringAspectInterceptor&quot;/&gt;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <br />	&lt;/aop:config&gt;<br />	<br />&lt;/beans&gt;</code></div>
</p>
<p>
The configuration file opens with a definition of the service bean, with id <code> springMonitoredService</code>, and then a declaration of the performance monitor <code>springMonitoringAspectInterceptor</code>. The latter of these serves as the advice which we want applied at the invocation of the service's <code>epsilon()</code> method.
</p>
<p>
Having defined the service, and a representation of the advice, we specify the pointcut at which we want the advice applied. This is done within the <code>&lt;aop:config&gt;</code> element of the bean definition file. This contains a pointcut with id <code>springMonitoringPointcut</code>, which specifies a regular expression that matches all invocations of the <code>epsilon()</code> method in objects of type <code>com.myorg.service..MyServiceSpringImpl</code>. Observe the use of the double period (<code>..</code>) notation in the specification of the class name. This is akin to the pattern <code>com.myorg.service.*.MyServiceSpringImpl</code>. Observe also that the pointcut is actually a bean in itself.
</p>
<p>
Finally, all we need to complete this example is a definition of the aspect; which, if you recall, is a combination of the pointcut and the advice. This is contained in the element <code>&lt;aop:advisor&gt;</code>, which references both the pointcut and the advice to form an aspect.
</p>
<p>
Before we move onto the client application, please note that a log4j properties file is included in the config folder of the companion archive. This specifies appenders and layouts that will process the log statements generated by the sample application. At this point you may be wondering where such log messages will come from since we have not actually performed any logging thus far. The answer lies in the logic of the Spring performance monitor, which actually prints task durations via log4j using a <code>TRACE</code> level message.
</p>
<p>
Observe that the log4j file provided declares a <code>SocketHubAppender</code>, which will allow viewing of log messages with Apache's chainsaw. The use of chainsaw is not strictly necessary for this example, but is provided simply as a means of demonstrating how a complete solution can be setup in the real world. This is more relevant for the JAMon example as we do not have recourse to the JAMon GUI--it is only really applicable to web applications. </p>
<p><p>
All that is left to do is to provide a client for invoking the service. A single client application is used for this tutorial; however, a different method is provided for invoking each example. As such, some light and judicious use of Java's commenting construct will be required to exclude the examples that you do not want to run. Listing 3 shows the main contents of the example client <code>com.myorg.MyClientApp</code>.
</p>
<p><strong>Listing 3: MyClientApp</strong></p>
<p>
<div class="codeblock"><code>package com.myorg;<br /><br />import org.springframework.context.ApplicationContext;<br />import org.springframework.context.support.ClassPathXmlApplicationContext;<br /><br />import com.myorg.service.MyService;<br /><br />public class MyClientApp<br />{<br />	private static final int SIMULATED_INVOCATION_COUNT = 100;<br />	<br />	private static void executeExampleWithEmbeddedSpringMonitoring(<br />						ApplicationContext context)<br />	{<br />		MyService service = <br />					(MyService)context.getBean(<br />					&quot;serviceWithEmbeddedSpringProfilling&quot;);<br />		for (int i=0;i&lt;SIMULATED_INVOCATION_COUNT;i++)<br />			service.epsilon();<br />	}<br />	<br />	private static void executeSpringMonitoringExample(<br />				ApplicationContext context)<br />	{<br />		MyService service = (MyService)context.getBean(<br />							&quot;springMonitoredService&quot;);<br /><br />		for (int i=0;i&lt;SIMULATED_INVOCATION_COUNT;i++)<br />			service.epsilon();<br />	}<br /><br />	private static void executeJamonMonitoringExample(<br />							ApplicationContext context)<br />	{<br />		MyService service = (MyService)context.getBean(<br />						&quot;jamonMonitoredService&quot;);<br /><br />		for (int i=0;i&lt;SIMULATED_INVOCATION_COUNT;i++)<br />			service.epsilon();<br />	}<br />	<br />	<br />	public static void main(String[] args)<br />	{<br />		ApplicationContext context = <br />			new ClassPathXmlApplicationContext(&quot;beans-context.xml&quot;);		<br />		executeExampleWithEmbeddedSpringMonitoring(context);<br />		executeSpringMonitoringExample(context);<br />		executeJamonMonitoringExample(context);<br />		<br />		while (true){<br />			//do nothing and just <br />			//keep the application alive<br />			//long enough for us to admire output<br />		}<br />	}<br /><br />}</code></div>
</p>
<p>
The main method simply loads the application context, and calls the three methods which respectively invoke the service implementations corresponding to the examples provided in this tutorial. In this case, we are only concerned with the invocation<br />
<code> executeSpringMonitoringExample(context);</code>, and as such we can comment out the other invocations at this stage.
</p>
<p>
Executing the example client results in output not too dissimilar to the following.
</p>
<p>
<div class="codeblock"><code>RACE main - StopWatch &#039;com.myorg.service.MyService.epsilon&#039;: running time (millis) = 94<br />TRACE main - StopWatch &#039;com.myorg.service.MyService.epsilon&#039;: running time (millis) = 110<br />TRACE main - StopWatch &#039;com.myorg.service.MyService.epsilon&#039;: running time (millis) = 93<br />TRACE main - StopWatch &#039;com.myorg.service.MyService.epsilon&#039;: running time (millis) = 110<br />TRACE main - StopWatch &#039;com.myorg.service.MyService.epsilon&#039;: running time (millis) = 93<br />TRACE main - StopWatch &#039;com.myorg.service.MyService.epsilon&#039;: running time (millis) = 110<br />TRACE main - StopWatch &#039;com.myorg.service.MyService.epsilon&#039;: running time (millis) = 94</code></div>
</p>
<p>
When viewed via chainsaw (i.e. by setting up a <code>SocketHubReceiver</code> on the port specified in log4j.properties), the output is of the form shown in <a href="http://www.obix-labs.com/staff/obi/jw/pmwsa/images/figure2.JPG" rel="nofollow">Figure 2</a>.
</p>
<p align="center">
</p>
<p>
If you examine the output closely, you will note references to <code>StopWatch</code>; this, in fact, is the name of the Spring class that performs the actual task of timekeeping. To see how the class works, we will try to replicate the functionality in the last example without the benefit of AOP. In other words, we will actually embed the profiling logic directly in our service implementation. Apart from providing a more in depth view of how the monitoring code works underneath, the extra coding required should hopefully dissuade most people from doing this. And, as such, drive home the logic behind using AOP in place of anything else!
</p>
<p>
The class <code>com.myorg.service.springmon.MyServiceWithEmbeddedSpringProfilling</code>, which is shown in listing 4, is a different implementation of the service that invokes the performance monitoring functionality explicitly within the <code>epsilon()</code> method. It is easy to observe from inspection of the source code that performance monitoring is accomplished by simply instantiating a new instance of the class <code>org.springframework.util.StopWatch</code>.
</p>
<p><strong>Listing 4: MyServiceWithEmbeddedSpringProfilling</strong></p>
<p>
<div class="codeblock"><code>package com.myorg.service.springmon;<br /><br />import org.springframework.util.StopWatch;<br /><br />public class MyServiceWithEmbeddedSpringProfilling extends MyServiceSpringImpl<br />{	<br />	public void epsilon()<br />	{<br />		StopWatch monitor = new StopWatch();<br />		monitor.start(&quot;epsilon&quot;);<br />		<br />		super.epsilon();<br />		<br />		monitor.stop();		<br />	}<br />}</code></div>
</p>
<p>
Like its physical namesake, the stopwatch simply records the time between the invocation of its <code>start(...)</code> and <code>stop()</code> methods. Information about the tasks performed between starting and stopping the monitor can be obtained by calling the <code>getTaskInfo()</code> method.
</p>
<p>
To execute this example, simply comment out all other invocations in the main method of the test client <code>MyClientApp</code> with the exception of <div class="codeblock"><code>executeExampleWithEmbeddedSpringMonitoring(context);</code></div>. Doing so will execute the code for the above example in isolation of the other two, and should produce output similar to the following excerpt.
</p>
<p>
<div class="codeblock"><code>TRACE main - StopWatch &#039;com.myorg.service.MyService.epsilon&#039;: running time (millis) = 110<br />TRACE main - StopWatch &#039;com.myorg.service.MyService.epsilon&#039;: running time (millis) = 93<br />TRACE main - StopWatch &#039;com.myorg.service.MyService.epsilon&#039;: running time (millis) = 110<br />TRACE main - StopWatch &#039;com.myorg.service.MyService.epsilon&#039;: running time (millis) = 94<br />TRACE main - StopWatch &#039;com.myorg.service.MyService.epsilon&#039;: running time (millis) = 109</code></div>
</p>
<p>
You will note that the above output is quite similar to the output from the first example. In essence, we have achieved not very much extra (in terms of functionality) by embedding the monitoring code directly in our application; other than of course cluttering the solution needlessly.
</p>
<p>
In the next section we will look at monitoring with the JAMon library.
</p>
<p><strong>Monitoring with Spring's JamonPerformanceMonitorInterceptor</strong></p>
<p>
JAMon consists of a library for performing latency monitoring as well as a web GUI which can be used in web applications to view the output from the monitoring library. Given that a number of applications do not run in a web container, the GUI is not a feasible option for many solutions. However, its base package offers functionality quite similar to that which is native in spring. Also, the spring distribution includes a performance monitor interceptor (<code>JamonPerformanceMonitorInterceptor</code>) which serves as a bridge to the JAMon toolkit. This can be combined with Apache's Chainsaw to replicate functionality that is not too dissimilar (for practical purposes) to that of the JAMon GUI.
</p>
<p>
Although not necessary in any other context, we will use a separate implementation of the service to illustrate monitoring with the JAMon interceptor. This implementation is shown in listing 5, and is only provided for the clarity of the Spring AOP configuration. As such, you will note that it is identical to the implementation of the service shown in the first example.
</p>
<p>
<strong>Listing 5: MyServiceJamonImpl</strong><br />
<div class="codeblock"><code>package com.myorg.service.jamon;<br /><br />import com.myorg.service.MyService;<br /><br />public class MyServiceJamonImpl implements MyService<br />{<br />	protected static final long DEFAULT_SLEEP_INTERVAL = 100;<br />	private long sleepInterval;<br /><br />	public MyServiceJamonImpl()<br />	{setSleepInterval(DEFAULT_SLEEP_INTERVAL);}	<br />	<br />	public void epsilon()<br />	{<br />		try{<br />			Thread.sleep(getSleepInterval());	<br />		}catch (InterruptedException int_exce){<br />			throw new RuntimeException(&quot;Service interrpted. Exiting.&quot;, <br />							int_exce);<br />		}<br />	}<br /><br />	public long getSleepInterval()<br />	{return sleepInterval;}<br /><br />	public void setSleepInterval(long sleepInterval)<br />	{this.sleepInterval = sleepInterval;}	<br />}</code></div>
</p>
<p>
The definition of the service and the spring aspect are shown in the following excerpt from the spring configuration file <code>beans-context.xml</code>. Note that the only material difference between this and the first example is that the advice bean is an instance of the class <code> org.springframework.aop.interceptor.JamonPerformanceMonitorInterceptor</code>.
</p>
<p><strong>Listing 6: beans-context.xml</strong></p>
<p>
<div class="codeblock"><code>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;<br />&lt;beans .............&gt;<br /><br />	&lt;bean id=&quot;jamonMonitoredService&quot;<br />		class=&quot;com.myorg.service.jamon.MyServiceJamonImpl&quot;/&gt;<br /><br />	<br />	&lt;bean id=&quot;jamonMonitoringAspectInterceptor&quot; <br />class=&quot;org.springframework.aop.interceptor.JamonPerformanceMonitorInterceptor&quot;&gt;<br />		&lt;property name=&quot;loggerName&quot; <br />			value=&quot;com.myorg.JAMON_MONITOR&quot;/&gt;<br />	&lt;/bean&gt;<br />	<br />	&lt;aop:config&gt;<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 		&lt;aop:pointcut id=&quot;jamonMonitoringPointcut&quot;<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 	expression=<br />		&quot;execution(* com.myorg.service..MyServiceJamonImpl.epsilon(..))&quot;/&gt;<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 		&lt;aop:advisor pointcut-ref=&quot;jamonMonitoringPointcut&quot; <br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 				advice-ref=&quot;jamonMonitoringAspectInterceptor&quot;/&gt;<br />	&lt;/aop:config&gt;<br />	<br />&lt;/beans&gt;</code></div>
</p>
<p>
To execute this example in isolation of the other two, comment out all invocations in the main method of the test client <code>MyClientApp.java</code> with the exception of the line <code>executeJamonMonitoringExample(context);</code>. The output generated by doing so should be similar to the following listing.
</p>
<p>
<div class="codeblock"><code>TRACE main - JAMon performance statistics for method [com.myorg.service.MyService.epsilon]:<br />JAMon Label=com.myorg.service.MyService.epsilon, Units=ms.: (LastValue=94.0, Hits=1.0, Avg=94.0, Total=94.0, Min=94.0, Max=94.0, Active=0.0, Avg Active=1.0, Max Active=1.0, First Access=Sun May 03 20:05:11 BST 2009, Last Access=Sun May 03 20:05:11 BST 2009)<br />TRACE main - JAMon performance statistics for method [com.myorg.service.MyService.epsilon]:<br />JAMon Label=com.myorg.service.MyService.epsilon, Units=ms.: (LastValue=93.0, Hits=2.0, Avg=93.5, Total=187.0, Min=93.0, Max=94.0, Active=0.0, Avg Active=1.0, Max Active=1.0, First Access=Sun May 03 20:05:11 BST 2009, Last Access=Sun May 03 20:05:12 BST 2009)<br />TRACE main - JAMon performance statistics for method [com.myorg.service.MyService.epsilon]:<br />JAMon Label=com.myorg.service.MyService.epsilon, Units=ms.: (LastValue=110.0, Hits=3.0, Avg=99.0, Total=297.0, Min=93.0, Max=110.0, Active=0.0, Avg Active=1.0, Max Active=1.0, First Access=Sun May 03 20:05:11 BST 2009, Last Access=Sun May 03 20:05:12 BST 2009)<br />........................</code></div>
</p>
<p>
<a href="http://www.obix-labs.com/staff/obi/jw/pmwsa/images/figure3.JPG" rel="nofollow">Figure 3</a> illustrates the output of this example as seen through the Chainsaw GUI. Note that this example actually utilises the JAMon binaries which are included in the lib folder of the companion archive. An interesting exercise for the reader to perform is to export the service implementation as a web service, package and deploy the application to a web container taking care to also configure the JAMon GUI in the web application descriptor.
</p>
<p>
In the next section, we will examine some alternative techniques for performance monitoring, which do not fall within the remit of this tutorial.
</p>
<p align="center">
</p>
<p><strong>Other Solutions for Performance Monitoring</strong></p>
<p>
To be clear, the technique described in this tutorial is reliant on AOP and may be difficult to apply to legacy applications&#173;&#173;especially if the applications are not built with the spring framework. That said performance analysis of legacy/existing applications can also be accomplished with a number of commercial tools (e.g. JProfiler) which allow developers to identify potential bottlenecks in existing code.
</p>
<p>
There are also more intrusive commercial third-party infrastructure components, such as JVMs, which offer facilities for real-time performance monitoring. Amongst the products in this space is RTPM from Azul systems. Choosing one of these tools obviously involves making implementation/deployment choices which may take solution developers down a route which is less travelled by those in their respective organizations.
</p>
<p>
Having said that, there are some real drawbacks to the Spring AOP approach. The most important of which is that there is no facility for asynchronous notification. If monitoring is enabled in the deployment environment, then it would be nice to have some means of issuing notifications when the application performance has degraded beyond a pre-set watermark.
</p>
<p>
If your monitoring requirements are complex in nature, than you may well be better off investigating a dedicated and commercial solution to the problem.
</p>
<p><strong>Summary</strong></p>
<p>
The emphasis of this tutorial was on how to augment spring applications, in a non intrusive manner, so as to obtain real-time performance metrics which can either be used to provide feedback to an iterative design process, or to monitor the behaviour/performance of applications in their deployment environment/home habitat.
</p>
<p>
The tutorial has provided a number of examples which demonstrate how to use classes native to the Spring application framework to achieve real-time performance reporting and monitoring. It has provided an example to show how Spring AOP can be combined with the JAMon application monitoring tool.
</p>
    ]]></content>
  </entry>
  <entry>
    <title>Epsilon 1.0.0 Alpha Preview Now Available</title>
    <link rel="alternate" type="text/html" href="http://www.javaworld.com/community/node/3119" />
    <id>http://www.javaworld.com/community/node/3119</id>
    <published>2009-06-25T08:25:51-04:00</published>
    <updated>2009-06-25T08:29:52-04:00</updated>
    <author>
      <name>Obi Ezechukwu</name>
    </author>
    <category term="java" />
    <category term="latency" />
    <category term="monitoring" />
    <category term="performance" />
    <category term="Spring" />
    <summary type="html"><![CDATA[<!--paging_filter--><p>
<a href="http://www.obix-labs.com" rel="nofollow" rel="nofollow">Epsilon</a> is a lightweight tool for monitoring and tracking the performance of Java applications in real time. It supports integration and configuration via Spring, including Spring AOP. Download from: <a href="http://www.obix-labs.com" title="http://www.obix-labs.com" rel="nofollow" rel="nofollow">http://www.obix-labs.com</a>
</p>
    ]]></summary>
    <content type="html"><![CDATA[<!--paging_filter--><p>
<a href="http://www.obix-labs.com" rel="nofollow">Epsilon</a> is a lightweight tool for monitoring and tracking the performance of Java applications in real time. It supports integration and configuration via Spring, including Spring AOP. Download from: <a href="http://www.obix-labs.com" title="http://www.obix-labs.com" rel="nofollow">http://www.obix-labs.com</a>
</p>
<p>
<a href="http://www.obix-labs.com" rel="nofollow">Epsilon</a> allows developers to set processing/performance benchmarks for an application, and monitors these in real-time as the application services requests. In cases where these benchmarks are breached, it can issue a notification (e.g. via email or by logging an alert) to one or more destinations. Amongst its many features are:
</p>
<p><ul>
<li>
<a href="http://www.springframework.org" rel="nofollow">Spring</a> support: Epsilon can be integrated and configured via Spring.
</li>
<li>
Non-intrusive: It can be embedded into applications by employing a <a href="http://www.springframework.org" rel="nofollow">Spring AOP</a> interceptor; thus removing the need for explicit references in application code.
</li>
<li>
Simple to embed: Epsilon can also be embedded directly into application code in a manner similar to that used for logging.
</li>
<li>
Statistical and fixed benchmarks: Application performance can be monitored in reference to the historically observed performance/latency of an application. Alternatively monitoring can be based on fixed latency caps.
</li>
<li>
Notifications callback: Email and log alert functionality is provided in the current release; however, users can also implement a simple callback interface to provide custom notification functionality.
</li>
<li>
Highly performant and lightweight: Epsilon will not skew the performance of the monitored application as it functions in an asynchronous and non-blocking manner. Neither will it add unnecessarily to the memory footprint of the monitored application.
</li>
<li>
Historical data: It can be configured to keep a specified amount of historical data, thus making it possible to utilize the collected data for other purposes.
</li>
<li>
Easy to extend
</li>
<li>
Free and open source
</li>
</ul>
</p>
    ]]></content>
  </entry>
  <entry>
    <title>Deadlock anti-patterns #3: Incremental Locking</title>
    <link rel="alternate" type="text/html" href="http://www.javaworld.com/community/node/2789" />
    <id>http://www.javaworld.com/community/node/2789</id>
    <published>2009-04-16T18:26:06-04:00</published>
    <updated>2009-04-22T05:06:43-04:00</updated>
    <author>
      <name>Obi Ezechukwu</name>
    </author>
    <category term="concurrency" />
    <category term="deadlock" />
    <category term="hold and wait" />
    <category term="java" />
    <category term="threads" />
    <summary type="html"><![CDATA[<!--paging_filter--><!--paging_filter--><p>
In the <a href='http://www.javaworld.com/community/node/2747'>
previous instalment</a> of this three part series, I examined 
the 'Worker Aggregation' anti-pattern. I also listed 
a number of ways to modify it so as to reduce the 
probability of its implementations leading to deadlock. 
Code samples were provided to demonstrate the pattern in 
both its raw and modified form, with the latter serving 
as practical demonstration of the deadlock avoidance 
modifications discussed. 
</p>    ]]></summary>
    <content type="html"><![CDATA[<!--paging_filter--><p>
In the <a href='http://www.javaworld.com/community/node/2747'>
previous instalment</a> of this three part series, I examined 
the 'Worker Aggregation' anti-pattern. I also listed 
a number of ways to modify it so as to reduce the 
probability of its implementations leading to deadlock. 
Code samples were provided to demonstrate the pattern in 
both its raw and modified form, with the latter serving 
as practical demonstration of the deadlock avoidance 
modifications discussed. 
</p>

<p>
In this concluding instalment I will examine the simple and 
well known incremental locking anti-pattern, which, 
despite being well documented, is unfortunately still a 
frequent mistake. Chances are that most people who have 
had the misfortune of debugging deadlocking code would 
have come across this pattern at some point in their career.
</p>
<!--break --> 

<p>
Note that this instalment also involves working through code examples, 
so please download the series’ companion 
<a href='http://www.javaworld.com/javaworld/jw-03-2009/hpj032309-src.zip'>
source code archive</a> and load the files into your 
preferred IDE.
</p>

<p>
Formally, incremental locking occurs when a process 'A' 
acquires a series of resources T<sub>1</sub>,....T<sub>x</sub>, 
in such a manner that: at the acquisition of resource 
T<sub>x</sub>, the process holds resources 
T<sub>1</sub>....T<sub>x-1</sub>. 
</p>

<p>
Strictly speaking, although incremental locking can lead 
to circular waits, it potency for havoc is not as a 
result of this but instead because it intentionally plays to 
two other deadlock conditions: resource hold and wait; 
and no pre-emption. By its very definition and nature, 
incremental locking actually enforces ‘hold and wait’; 
and more often than not, it is impossible to force 
Java processes to give up locked resources--especially 
after deadlock. 
</p>

<p>
All that said, one actually hesitates to term incremental 
locking an anti-pattern, because there are requirements 
which make it a necessity. It is however the programming 
equivalent of making financial predictions based on 
normally distributed random variables; even if things look 
ok most of the time, when they go wrong, it is generally 
in unexpected and quite abrupt fashion. As such it should 
not be done without some basic safeguards in place, and 
most certainly should not be encouraged.
</p>

<p>
To be clear, when acquiring locks incrementally, it is 
imperative that a strict acquisition order is followed and 
maintained. This goes a long way in reducing the risks 
involved. But what happens when such an order cannot 
be followed or enforced? This is the scenario that we will 
focus on here. We will examine some example code that 
demonstrates how this pattern can trigger deadlock, 
and also examine an established technique for preventing this.
</p>

<p>
The code referenced in this tip is contained in the 
package <code>example.incrementallock</code> which is 
available in the 
<a href=’http://www.javaworld.com/javaworld/jw-03-2009/hpj032309-src.zip’>
code archive</a> which accompanies this series. The package 
consists of the following source files:
<div class="codeblock"><code>+example.incrementallock<br />	-ExampleThread.java<br />	-ExampleThread2.java<br />	-SharedResource.java<br />	-ExampleRunner.java<br />	-ExampleRunner2.java</code></div>
</p>

<p>
We start with examining the class <code>SharedResource</code>, 
shown in listing 10, which encapsulates two locks 
'<code>A</code>' and '<code>B</code>'. We pretend that 
processing threads, in order to make use of an instance of 
this class, will have to acquire both lock <code>A</code> and 
lock <code>B</code>, either in the order <code>A-&gt;B</code> or 
<code>B-&gt;A</code>. 
</p>

<h4>Listing 11: example.incrementallock.SharedResource</h4>
<p>
<div class="codeblock"><code>import java.util.concurrent.locks.Lock;<br />import java.util.concurrent.locks.ReentrantLock;<br /><br />public class SharedResource <br />{<br />	private Lock lockA;<br />	private Lock lockB;<br />	<br />	public SharedResource() <br />	{<br />		lockA = new ReentrantLock();<br />		lockB = new ReentrantLock();<br />	}<br />	<br />	public Lock getLockA() {return lockA;}	<br />	public Lock getLockB(){return lockB;}<br />}</code></div>
</p>

<p>
The process/thread behaviour is modelled by the class 
<code>ExampleThread</code>, which is detailed in listing 11. 
Pay particular attention to the constructor, in which you 
will note that the lock acquisition order can be varied 
based on the value of the argument 
<code>invertLockAcquisitionOrder</code>. When true, 
lock 'A' is treated as the primary lock and 'B' as the secondary; 
otherwise, the converse applies. 
</p>

<p> 
In the <code>run</code> method, the thread tries to acquire 
the secondary lock post the acquisition of the primary lock.
The aim here of course is to demonstrate what happens when 
two threads with different acquisition orders try to share 
the same set of locks.
</p>

<h4>Listing 11: example.incrementallock.ExampleThread</h4>
<p>
<div class="codeblock"><code>package example.incrementallock;<br /><br />import java.util.concurrent.locks.Lock;<br /><br />public class ExampleThread extends Thread<br />{<br />	protected int threadIndex;<br />	protected Lock primaryLock;<br />	protected Lock secondaryLock;<br />	<br /><br />	public ExampleThread(	SharedResource sharedResource,<br />					boolean invertLockAcquisitionOrder,<br />					int threadIndex)<br />	{<br />		this.threadIndex = threadIndex;<br />		<br />		if (invertLockAcquisitionOrder)<br />		{<br />			this.primaryLock = sharedResource.getLockA();<br />			this.secondaryLock = sharedResource.getLockB();<br />		}<br />		else<br />		{<br />			this.primaryLock = sharedResource.getLockB();<br />			this.secondaryLock = sharedResource.getLockA();<br />		}<br />	}<br /><br />	@Override<br />	public void run()<br />	{<br />		try<br />		{<br />			primaryLock.lock();<br />			System.out.println(&quot;Thread &quot; + getName() <br />						+ &quot;&#039; obtained read-lock&quot;);<br /><br />			// do something<br />			Thread.sleep(1000*threadIndex);<br /><br />			secondaryLock.lock();<br />			System.out.println(&quot;Thread &quot; + getName() <br />						+ &quot;&#039; obtained write-lock&quot;);<br />		}<br />		catch (InterruptedException exce)<br />		{<br />			return;<br />		}<br /><br />		finally<br />		{<br />			secondaryLock.unlock();<br />			primaryLock.unlock();<br />		}<br /><br />		System.out.println(&quot;Thread &quot; + getName() + <br />					&quot;&#039; terminating&quot;);<br />	}<br />}</code></div>
</p>

<p>
To run this model, execute the target <code>ExampleRunner.java</code>, 
which is shown in listing 12. Observe that 
this class creates two <code>ExampleThread</code> instances, 
reversing the lock ordering on the second. 
When executed, this class should produce the following output, 
and then deadlock.
</p>

<p>
<div class="codeblock"><code>Thread Thread-0&#039; obtained read-lock<br />Thread Thread-1&#039; obtained read-lock</code></div>
</p>
<h4>Listing 12: example.incrementallock.ExampleRunner</h4>
<p>
<div class="codeblock"><code>package example.incrementallock;<br /><br />public class ExampleRunner <br />{	<br />	public static void main(String[] args) <br />					throws InterruptedException <br />	{<br />		ExampleThread thread1;<br />		ExampleThread thread2;<br />		SharedResource sharedResource;<br />		<br />		sharedResource = new SharedResource();<br />		<br />		thread1 = new ExampleThread(sharedResource, false, 1);<br />		thread1.start();<br />		<br />		thread2 = new ExampleThread(sharedResource,true, 2);<br />		thread2.start();<br />	}<br />}</code></div>
</p>

<p>
The cause of the deadlock is that <code>thread1</code> on 
acquiring lock '<code>A</code>', proceeds to ask for lock 
'<code>B</code>', which is already held by <code>thread2</code>. 
The latter of course also tries to obtain lock '<code>A</code>', 
and with each of the threads waiting for the other's resource, 
the application goes into a state of deadlock.
</p>

<p>
The problem here is not simply the circular wait that forms; 
in fact, it is, in itself, actually a symptom of the bad decision 
made to introduce <b>hold and wait</b> logic into the application. 
Equally bad is the fact that even though the code 
incorporates <b>hold and wait</b>, it does nothing to cater 
for scenarios where the resource being watched cannot be 
freed i.e. there is no logic for resource release--voluntary 
or otherwise.
</p>

<p>
Considering that deadlock can only hold if all four of 
its preconditions are in place, how would you go 
about modifying this example so that it is less prone to 
deadlock? Whilst there are undoubtedly more ways to achieve 
this than there are to skin the proverbial cat, let us borrow 
a technique from our friends in electronics to illustrate a 
very simple solution to the problem. 
</p>

<p> 
Examine the class <code>ExampleThread2</code> shown
in listing 13. Note that the call to acquire the secondary lock
is to the <code>tryLock()</code> method instead of <code>lock()</code>.
This means that if the secondary lock is in use, this call will
return false, and the thread will consequently release the
primary lock. This simple change means that not only do we
prevent a circular wait from forming, but we also willingly give
up the resource collected to date, thus allowing the other
thread to proceed to completion. This technique can be
summarised quite simply as thus: when a process already holds
one or more resources and fails to acquire an additional
resource, the process should immediately relinquish all the
resources which it currently holds.
</p>

<h4>Listing 13: example.incrementallock.ExampleThread2</h4>
<p>
<div class="codeblock"><code>public class ExampleThread2 extends ExampleThread<br />{	<br />	public ExampleThread2(	SharedResource sharedResource, <br />					boolean invertLockAcquisitionOrder,<br />					int threadIndex)<br />	{<br />		super(	sharedResource, <br />				invertLockAcquisitionOrder,<br />				threadIndex);<br />	}<br />	<br />	@Override<br />	public void run() <br />	{<br />		boolean success=false;<br />		try<br />		{<br />			primaryLock.lock();<br />			System.out.println(&quot;Thread &quot; + getName() + <br />						&quot;&#039; obtained read-lock&quot;);			<br />			<br />			//simulate some work<br />			Thread.sleep(1000 * threadIndex);<br />			<br />			if (secondaryLock.tryLock())<br />			{<br />				System.out.println(&quot;Thread &quot; + getName() + <br />							&quot;&#039; obtained write-lock&quot;);<br />				success = true;<br />			}<br />			else System.out.println(&quot;Thread &quot; +getName()+&quot; 							failed to acquire write lock.&quot; + <br />						&quot; Relinquishing first lock&quot;);<br />		}<br />		catch (InterruptedException exce)<br />		{<br />			return;<br />		}<br />		finally<br />		{<br />			primaryLock.unlock();<br />			if (success) secondaryLock.unlock();<br />		}<br />		System.out.println(&quot;Thread &quot; + getName() + <br />					&quot;&#039; terminating&quot;);<br />	}	<br />}</code></div>
</p>

<p> The disadvantage of the above solution of course is that only one of
the threads actually completes its work successfully. However the failed
process can be retried at a later date, perhaps when the system is less
busy or prone to deadlock. A more complex and comprehensive implementation
of this idea is to force threads to publish the list of resources they
currently hold when requesting new ones. That way a controller or
arbitrator may be used to decide if the new requests are likely to lead to
deadlock. Note that the 
<a href='http://www.javaworld.com/community/node/2701'>first instalment of this series</a> has
already described the concept of arbitration, and that the same idea can be
applied here.
</p>

<p>
The modified model can be invoked via the 
class <code>ExampleRunner2</code>, shown in listing 14, and 
its output should be as follows:
</p>

<p>
<div class="codeblock"><code>Thread Thread-0&#039; obtained read-lock<br />Thread Thread-1&#039; obtained read-lock<br />Thread Thread-0 failed to acquire write lock. Relinquishing first lock<br />Thread Thread-0&#039; terminating<br />Thread Thread-1&#039; obtained write-lock<br />Thread Thread-1&#039; terminating</code></div>
</p>

<h4>Listing 14: example.incrementallock.ExampleRunner2</h4>
<p>
<div class="codeblock"><code>public class ExampleRunner2<br />{	<br />	public static void main(String[] args) <br />					throws InterruptedException <br />	{<br />		ExampleThread2 thread1;<br />		ExampleThread2 thread2;<br />		SharedResource sharedResource;<br />		<br />		sharedResource = new SharedResource();<br />		<br />		thread1 = new ExampleThread2(sharedResource,true,1);<br />		thread1.start();<br />		<br />		thread2 = new ExampleThread2(sharedResource,false,2);<br />		thread2.start();<br />	}<br />}</code></div>
</p>

<p>
From the output listing, we can confirm that <code>Thread-0</code> is
unable to acquire the second resource, and, as a consequence, relinquishes
control of the lock which it already holds. This allows <code>Thread-1</code> to proceed to termination.
</p>

<h2>Conclusion</h2>

<p> 
This series of posts have explored the pre-requisites of application
deadlock, and discussed three concurrency anti-patterns which often lead to
the occurrence of these pre-requisites, and, consequently, application
deadlock itself. Code examples were provided to illustrate these anti-
patterns, and to demonstrate their weaknesses. 
</p> 
<p> 
Possible means of counteracting the negative downsides of the 
presented anti-patterns were also discussed. It was shown through 
the use of code examples that: application deadlock can be avoided 
by modifying the implementation of the anti-patterns 
such that at least one of the deadlock pre-requisites is
prevented from being valid. 
</p>
    ]]></content>
  </entry>
  <entry>
    <title>Deadlock anti-patterns #2: Worker Aggregation</title>
    <link rel="alternate" type="text/html" href="http://www.javaworld.com/community/node/2747" />
    <id>http://www.javaworld.com/community/node/2747</id>
    <published>2009-04-06T17:18:29-04:00</published>
    <updated>2009-04-06T17:18:29-04:00</updated>
    <author>
      <name>Obi Ezechukwu</name>
    </author>
    <category term="concurrency" />
    <category term="deadlock" />
    <category term="java" />
    <category term="threads" />
    <summary type="html"><![CDATA[<!--paging_filter--><!--paging_filter--><p>
In the first installment of this three part <a href='http://www.javaworld.com/community/node/2701'>series</a>, I described the problem of deadlock; focusing on the logical conditions that are necessary for a deadlock to occur. I also introduced the deadlock-prone <a href=’ http://www.javaworld.com/community/node/2701’>No Arbitration</a> anti-pattern which is evident in applications where interdependent processes are allowed to contend for resources without effective arbitration to determine priority of access at critical junctures.    ]]></summary>
    <content type="html"><![CDATA[<!--paging_filter--><p>
In the first installment of this three part <a href='http://www.javaworld.com/community/node/2701'>series</a>, I described the problem of deadlock; focusing on the logical conditions that are necessary for a deadlock to occur. I also introduced the deadlock-prone <a href=’ http://www.javaworld.com/community/node/2701’>No Arbitration</a> anti-pattern which is evident in applications where interdependent processes are allowed to contend for resources without effective arbitration to determine priority of access at critical junctures. An example of this was provided in the form of a train simulator.
</p>
<p>
This installment will examine yet another deadlock-prone anti-pattern, which we shall refer to by the moniker 
‘Worker Aggregation’. Note that this installment also involves working through code samples, 
so please feel free to download this series' companion 
<a href='http://www.javaworld.com/javaworld/jw-03-2009/hpj032309-src.zip'>source code archive</a> 
and load the files into your preferred IDE.
</p>
<h2>Worker Aggregation</h2>

<p>
An interesting experiment to try is as follows: 
<ol>
	<li>divert all voice calls from phone A to B</li>
	<li>simultaneously divert all calls from B to A</li>
	<li>attempt a call to phone A and observe the result</li>
</ol>
What happened to your call? Did it simply end up in your voicemail inbox? 
Did you get some auto generated error-message threatening you with the wrath of the evil Emperor Zurg for your audacity? 
Or did it go through? Not surprisingly, this is a scenario that telecoms switch designers had to anticipate 
quite early on in the evolution of voice networks. Various manufacturers and operators came up with rather 
ingenious ways around it. Some simply, and rather unceremoniously, ruled out second-hop diverts; 
others chose to forward all second-level diverts to voicemail. A few even went further, 
and permitted larger divert chains under very specific and strict conditions, but also 
implemented algorithms to test for chain cyclicity. All are valid approaches, which undoubtedly 
saved some poor designers the few strands of hair they had remaining!
</p>
<p>
Have no fear, we are not about to write a telecoms switch simulator! The above example only serves to 
exemplify the conditions one must take into account when building systems that incorporate autonomous 
processes capable of self aggregation. Examples of self aggregating software include, but are not limited to,
systems where processes can: cooperate with each other to break-down and perform composite tasks; <i>divert</i> 
portions of their tasks to other processes; subjugate pooled processes to perform sub-units of work.
Process aggregation inevitably leads to chains of workers performing tasks in concert. 
In such architectures, a problem which 
becomes clear sooner or later is how to enforce acyclicity of process chains. Where cycles do occur, 
there is every possibility that the chains in question will never terminate, and in some cases may even deadlock. 
</p>
<p>
Consider processes <i>P<sub>1</sub> ,P<sub>2</sub>,</i> and <i>P<sub>n</sub></i>, such that 
they form a cyclic task chain of the form <i>{ P<sub>1</sub>,P<sub>2</sub>,...,P<sub>n</sub>,
P<sub>1</sub>}</i>, where <i>P<sub>n</sub></i> holds a resource which is required by <i>P<sub>1</sub></i>, 
and <i>P<sub>n</sub></i> cannot release the resource until <i>P<sub>1</sub></i> has terminated.
In such a scenario neither process will be able to proceed further; the chain will simply deadlock.  
</p>
<p>
Let us simplify the above example by examining the same concept expressed in code. To do so we will use the compilation units contained in the package <code>example.workeraggregation</code>, 
which illustrates what happens when worker thread dependencies become cyclic. 
The package consists of the following source files:
</p>
<p>
<div class="codeblock"><code>+example.workeraggregation<br />	-Worker.java<br />	-Worker2.java<br />	-WorkerRunner.java<br />	-WorkerRunner.java</code></div>
</p>
<p>
The <code>Worker</code> class, shown in listing 6, models a worker process. Worker recruitment 
is encapsulated in the field <code>coWorker</code>. The worker also maintains an internal 
lock which is held whilst it is in service. Thus when a co-worker is involved in performing a task, 
its lock is held by the recruiting thread.  This can be seen more clearly by examining 
the <code>run()</code> method.

<h4>Listing 6: example.workeraggregation.Worker</h4>

<div class="codeblock"><code>public class Worker extends Thread<br />{<br />	protected Lock lock;<br />	protected Worker coWorker;<br />	protected int workerIndex;<br />	<br />	public Worker(int workerIndex)<br />	<br />	public void setCoWorker(Worker coWorker)	<br />	public void lock(){lock.lock();}<br />	public void unlock(){lock.unlock();}<br />	<br />	@Override<br />	public void run()<br />	{		<br />		lock();<br />		System.out.println(&quot;Thread &quot; + getName()+ &quot; started ...&quot;);<br />				<br />		try<br />		{<br />			//simulate some work<br />			Thread.sleep(1000 *workerIndex);<br />			if (coWorker!=null)<br />			{<br />				coWorker.lock();<br />				System.out.println(&quot;Thread &quot; + getName()+ <br />							&quot; co-opted co-worker &quot; +<br />							coWorker.getName());<br />			}<br />		}<br />		catch (InterruptedException exce)<br />		{<br />			return;<br />		}<br />		finally<br />		{<br />			coWorker.unlock();<br />			unlock();<br />		}<br />	}<br />	<br />}</code></div>
</p>

<p>
Note that a staggered sleep is used to simulate work before the co-worker is engaged. 
Now consider what would happen if we created two worker threads <code>worker1</code> and <code>worker2</code> 
such that the dependencies between them is as follows: <code>worker1 -&gt; worker2 -&gt; worker1</code>? 
This question is answered by executing the class <code>WorkerRunner</code> which is detailed in listing 7.

<h4>Listing 7: example.workeraggregation.WorkerRunner</h4>
<div class="codeblock"><code>public class WorkerRunner<br />{<br />	public static void main(String[] args)<br />	{<br />		Worker worker1 = new Worker(1);<br />		Worker worker2 = new Worker(2);<br />		<br />		worker1.setCoWorker(worker2);<br />		worker2.setCoWorker(worker1);<br />		<br />		worker1.start();<br />		worker2.start();		<br />	}<br />}</code></div>

<br></br>
Doing so, produces the following output, and promptly deadlocks.
<br></br>


<div class="codeblock"><code>Thread Thread-0 started ...<br />Thread Thread-1 started ...</code></div>
</p>
<p>
Examining, or stepping through the code, you will notice that <code>worker2</code> tries to acquire a lock already held 
by <code>worker1</code>, which in turn cannot terminate and release the lock until <code>worker2</code> has completed. 
Voila, deadlock! </p>
<p>
There are of course many ways to go about solving this particular conundrum. A brute force approach would simply be 
to adopt the same strategy applied by some telecoms engineers: prevent the dependency chain from exceeding a 
pre-determined size. A more complex solution is to build and enforce an acyclic worker-dependency graph in 
real-time as the application progresses.
</p>
<p>
To simplify the illustration, we will use the former approach to show how this situation can be prevented from 
occurring. Listing 8 details an extension <code>Worker2</code> of the class <code>Worker</code> which includes a 
<code>chainSize</code> attribute that is used to track the size of the dependency chain. This attribute is also 
used to ensure that all second-hop dependencies are ignored.
</p>

<h4>Listing 8: example.workeraggregation.Worker2</h4>
<div class="codeblock"><code>package example.workeraggregation;<br /><br />public class Worker2 extends Worker<br />{<br />	private int chainSize;<br />	<br />	public void setCoWorker(Worker coWorker, <br />					int chainSize)<br />	<br />	@Override<br />	public void run()<br />	{<br />		lock();<br />		System.out.println(&quot;Thread &quot; + getName()+ <br />						&quot; started ...&quot;);<br />		<br />		boolean coOptedWorker=false;<br />		try<br />		{<br />			//simulate some work			<br />			Thread.sleep(1000 *workerIndex);<br />			if (coWorker!=null &amp;&amp; chainSize&lt;2)<br />			{<br />				coWorker.lock();<br />				coOptedWorker=true;<br />				System.out.println(&quot;Thread &quot; + getName()+ <br />							&quot; co-opted co-worker &quot; + <br />							coWorker.getName());<br />			}<br />			else System.out.println(getName() <br />						+ &quot; working solo today...&quot;);<br />		}<br />		catch (InterruptedException exce)<br />		{<br />			return;<br />		}<br />		finally<br />		{<br />			if (coOptedWorker)coWorker.unlock();			<br />			unlock();<br />		}<br />	}<br />}</code></div>

<p>
<code>WorkerRunner</code> is also replaced with <code>WorkerRunner2</code> (shown in listing 9) 
which is responsible for specifying the dependency chain size. Executing this class, produces the following output:
<div class="codeblock"><code>Thread Thread-0 started ...<br />Thread Thread-1 started ...<br />Thread-1 working solo today...<br />Thread Thread-0 co-opted co-worker Thread-1</code></div>
<br></br>
Notice that thread#1 does not bother trying to co-opt its co-worker because it is aware that the 
dependency chain has grown to a point where circular waits are possible. Note that this is not the only 
solution to this problem, but is intended to serve as a simple example of how this concurrency pattern can be 
modified so that it does not lead to circular waits. Readers as always are strongly encouraged to contribute 
alternatives, however inspired.
</p>
<p>
<h4>Listing 9: example.workeraggregation.WorkerRunner2</h4>
<div class="codeblock"><code>public class WorkerRunner2<br />{<br />	public static void main(String[] args)<br />	{<br />		Worker2 worker1 = new Worker2(1);<br />		Worker2 worker2 = new Worker2(2);<br />		<br />		int chainSize = 0;<br />		worker1.setCoWorker(worker2,++chainSize);<br />		worker2.setCoWorker(worker1,++chainSize);<br />		<br />		worker1.start();<br />		worker2.start();	<br />	}<br />}</code></div>
</p>
<h2>Summary</h2>
<p>
In this installment, we have looked at the problems involved in worker aggregation; 
specifically focusing on how cyclic worker chains can lead to application deadlock.
Code examples were provided to demonstrate this, as well as to show how this anti-pattern can 
be modified so as to reduce the risk of deadlock. 
</p>
<p>
The next, and final, installment of this <a href='http://www.javaworld.com/community/node/2701'>series</a> 
will examine the incremental locking anti-pattern.
</p>

    ]]></content>
  </entry>
  <entry>
    <title>Deadlock anti-patterns #1: No arbitration</title>
    <link rel="alternate" type="text/html" href="http://www.javaworld.com/community/node/2701" />
    <id>http://www.javaworld.com/community/node/2701</id>
    <published>2009-03-29T19:21:52-04:00</published>
    <updated>2009-04-06T16:31:12-04:00</updated>
    <author>
      <name>Obi Ezechukwu</name>
    </author>
    <category term="concurrency" />
    <category term="deadlock" />
    <category term="java" />
    <category term="threads" />
    <summary type="html"><![CDATA[<!--paging_filter--><!--paging_filter--><p> 
Starvation occurs when one or more threads of execution are prevented from proceeding beyond a given point due to a predicate that will never be satisfied. Deadlock is a special form of starvation where threads of execution are prevented from making progress due to predicate conditions that are directly dependent on them. To illustrate, consider threads A and B, with shared resources R1 and R2. If thread A holds resource R1, and thread B holds resource R2; a deadlock will occur if thread A needs resource R2 to proceed and thread B is waiting on thread A to release resource R1.    ]]></summary>
    <content type="html"><![CDATA[<!--paging_filter--><p> 
Starvation occurs when one or more threads of execution are prevented from proceeding beyond a given point due to a predicate that will never be satisfied. Deadlock is a special form of starvation where threads of execution are prevented from making progress due to predicate conditions that are directly dependent on them. To illustrate, consider threads A and B, with shared resources R1 and R2. If thread A holds resource R1, and thread B holds resource R2; a deadlock will occur if thread A needs resource R2 to proceed and thread B is waiting on thread A to release resource R1. Since neither thread releases the resource it is holding, and both need each other’s resource to continue, they both become engaged in a deadly embrace and cannot proceed any further. 
</p> 
<p> 
Considering that parallel threads of execution quite often have to rely on shared/mutual state, and that locking is used as the predominant means of preventing destructive updates, it is not surprising that deadlocks are an issue that multi-threaded application developers have to contend with at some point or another. 
</p> 
<p>
The adage “prevention is better than cure” is rather prescient when considering the problem of deadlocks. Actually, anyone who has had the displeasure of diagnosing deadlock will probably agree that the British and Australian version “an ounce of prevention is more valuable than a pound of cure” probably does a better job of emphasizing the contrast between the effort involved in preventing and fixing deadlocks respectively.
</p>
<p>
Thankfully (or sadly, depending on which way you look at it), deadlocks are mostly “man made” i.e. down to programmer error. Thus, preventing them can simply be a case of avoiding concurrency anti-patterns that have been shown to trigger them. We know from E.G. Coffman’s 1971 article that there must be four conditions for a deadlock to take place. These are:</p>

<p>
<ol>
	<li>
<b>Mutual exclusion:</b> The concurrent threads of execution must share state which cannot be accessed by more than one thread (or class of threads) at any given point in time.
	</li>
<li>
<b>Resource hold and wait:</b> Processes are not prevented from requesting new resources regardless of whether or not they are already holding other resources.
	</li>	
<li>
<b>No Preemption:</b> A processes may not be forcibly deprived of the resources which it currently holds. 
	</li>	
	<li>
<b>A circular wait condition:</b> This is the final and most identifiable condition required for a deadlock. It occurs when one or more resources form an interdependent and circular chain, such that each process T<sub>i</sub> in the chain waits for a resource that is already held by the next process T<sub>x</sub> in the chain, and T<sub>x</sub> equally requires (directly or indirectly) the resource held by T<sub>i</sub>.
	</li>
</ol>
</p>
<p>
Thus, preventing deadlock can be as simple as ensuring that all of the above four conditions never hold at the same time. Unfortunately life is not that simple. In reality, the first three conditions are actually quite useful for a variety of reasons which most concurrent application developers are fully aware off. For this reason, deadlock prevention often centres on preventing the final condition taking root.
</p>
<p>
In the following series of posts, I will explore three concurrency anti-patterns that can lead to circular wait conditions. In addition to describing these anti-patterns, this series will also show code samples to illustrate each one, and discuss solutions and workarounds to counteract them. Please note that the aim of this series is not to be a comprehensive collection of anti-patterns, but rather to encourage discussion around the topic. As such, readers are invited to contribute additional anti-patterns that they have come across—preferably with code samples. 
</p>

<p>
This series is hands-on, so you are advised to download the companion 
source code archive, located at <a href="http://www.javaworld.com/javaworld/jw-03-2009/hpj032309-src.zip" title="http://www.javaworld.com/javaworld/jw-03-2009/hpj032309-src.zip">http://www.javaworld.com/javaworld/jw-03-2009/hpj032309-src.zip</a>, and load the source files into your favourite IDE.
</p>

<p>
For this installment, let us begin with a relatively simple anti pattern, which I refer to as the ‘No Arbitration’ pattern.
</p>

<h2>No Arbitration</h2>
<p>
For a rather amusing take on deadlock-making functional requirements, examine this piece of legislation passed in the Midwestern US State of Kansas: <i>"When two trains approach each other at a crossing, both shall come to a full stop and neither shall start up again until the other has gone"</i>.
</p>
<p> 
One can only speculate as to the sequence of events that occurred the first time that two trains did actually happen upon each other at a crossing or indeed how long this statute lasted on the books.
</p>
<p>
The pertinent question however is: what would happen if we modelled this statute in software? To answer that question, we will use the <code>example.noarbitration</code> package in the companion source archive. The package consists of the following compilation units:
</p>

<div class="codeblock"><code>+example.noarbitration<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; -CrossingSimulator.java<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; -Train.java<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; -CrossingSimulator2.java<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; -Train2.java<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; -TrainArbitrator.java</code></div>

<p>
We will first of all explore the <code>Train</code> class which extends <code>java.lang.Thread</code> and which, as its name implies, models the behaviour of a train. This class is outlined in listing 1.
</p>
 
<h4>Listing 1: example.noarbitration.Train</h4>
<div class="codeblock"><code>public class Train extends Thread<br />{<br />	private Train other;<br />	<br />	protected boolean stopped;<br />	private String trainId;<br /><br />	public Train(String trainId)<br /><br />	public void setOther(Train other)<br /><br />	protected synchronized void waitUntilMoved()<br />	<br />	protected synchronized void moveTrain()<br />	<br />	@Override<br />	public void run()<br />	{<br />		System.out.println( this + &quot; reached barrier...&quot;);<br /><br />		try<br />		{<br />			other.waitUntilMoved();<br />			moveTrain();<br />		}<br />		catch (InterruptedException exce)<br />		{<br />			System.out.println(&quot;Thread halted ...&quot;);<br />		}<br />	}<br /><br />}</code></div>
<p>
Observe that the <code>other</code> attribute holds a reference to the other train at the crossing. As dictated by the statute, the run method models what takes place the moment the train arrives at the crossing. It waits for the other train to move before it itself starts to move. 
</p>
<p>
We use the <code>CrossingSimulator</code> class, shown in listing 2, to encapsulate the behaviour of both trains as it relates to the crossing. As can be seen from the listing, the code creates and starts two train simulators (one southbound and the other eastbound). 
</p>
<h4>Listing 2: example.noarbitration.CrossingSimulator</h4>
<div class="codeblock"><code>public class CrossingSimulator<br />{<br />	<br />	public static void main(String[] args)<br />	{<br />		Train train1 = new Train(&quot;Southbound Train&quot;);<br />		Train train2 = new Train(&quot;Eastbound Train&quot;);<br />		train1.setOther(train2);<br />		train2.setOther(train1);<br />		<br />		train1.start();<br />		train2.start();<br />	}<br />}</code></div> 
<p>
If we run the code in the previous listing, we should get the following output:

<div class="codeblock"><code>Southbound Train reached barrier...<br />Eastbound Train reached barrier...</code></div>
</p>
<p>
Not surprisingly, our trains never go anywhere once they reach the crossing; both threads quite simply deadlock, each waiting for the other to move. A rather perfect example of how not to run trains! 
</p>
<p>
The question then is: what exactly is wrong with the model of concurrency on which this example is built? The answer in this particular case is quite simple; there is no arbitration between the trains to decide who gets to go first when conflict occurs. A situation that can quite easily occur when building systems based on independent and co-operative processes of equal priority and which rely on each other's internal state for deciding direction.
</p>
<p>
More formally, when there is contention between different threads of execution, a means must be present to determine the order in which the threads are granted access to the area or state in contention. 
</p>
<p>
A simple solution is to introduce an arbitrator, which, when contention of this nature is detected, decides, based on some well defined scheme, which of the competing processes gains the upper hand. To apply this to the example model, some modifications are required to the <code>Train</code> and <code>CrossingSimulator</code> class logic, as well as some dedicated logic to provide arbitration. 
</p>
<p>
The <code>Train</code> class is extended by <code>Train2</code>, as shown in listing 3, in order to provide three methods which play a key part in arbitration. 

<h4>Listing 3: example.noarbitration.Train2</h4>
<div class="codeblock"><code>public class Train2 extends Train<br />{<br />	private long arrivalTime;<br />	<br />	public synchronized boolean isStopped()<br />	<br />	protected void forceTrainToMove()<br />	<br />	public long getArrivalTime()<br />}</code></div>
</p>
<p>
The <code>isStopped()</code> method indicates that the train is stationary; and <code>forceTrainToMove()</code> is invoked by the arbitrator to force the train to move. Finally, <code>getArrivalTime()</code> provides the time at which the train arrived at the crossing. 
</p>
<p>
The arbitrator implementation is encapsulated in class <code>TrainArbitrator</code>, and is shown in listing 4. As is evident from the <code>run()</code> method, the arbitrator simply forces the train which has been at the crossing the longest to start moving. This will, in turn, enable the other train to move also.

<h4>Listing 4: example.noarbitration.TrainArbitrator</h4>
<div class="codeblock"><code>public class TrainArbitrator extends Thread<br />{<br />	private Train2 trainA;<br />	private Train2 trainB;<br />	<br />	public TrainArbitrator(	Train2 trainA, <br />Train2 trainB)<br />	<br />	public void run()<br />	{<br />		while (trainA.isStopped() &amp;&amp; trainB.isStopped())<br />		{<br />			if (trainA.getArrivalTime()<br />&lt;trainB.getArrivalTime())<br />			{<br />				trainA.forceTrainToMove();<br />				break;<br />			}<br />			else<br />			{<br />				trainB.forceTrainToMove();<br />				break;<br />			}<br />		}<br />	}<br />}</code></div>
</p>
<p>
The executor class <code>CrossingSimulator</code> is also replaced by <code>CrossingSimulator2</code>, which is detailed in listing 5.

<h4>Listing 5: example.noarbitration.CrossingSimulator2</h4>
<div class="codeblock"><code>public class CrossingSimulator2<br />{<br />	public static void main(String[] args) throws InterruptedException<br />	{<br />		Train2 train1 = new Train2(&quot;Southbound Train&quot;);<br />		Train2 train2 = new Train2(&quot;Eastbound Train&quot;);<br />		train1.setOther(train2);<br />		train2.setOther(train1);<br />		<br />		train1.start();<br />		train2.start();<br />				<br />		Thread.sleep(1000);<br />		TrainArbitrator arbitrator = new<br />						TrainArbitrator(train1,train2);<br />		arbitrator.start();<br />	}<br />}</code></div>
</p>
<p>
If we execute <code>CrossingSimulator2</code>, we should get the following output:

<div class="codeblock"><code>Southbound Train reached barrier...<br />Eastbound Train reached barrier...<br />Eastbound Train now moving ..<br />Southbound Train now moving ..</code></div>
</p>
<p>
The output shows that when the arbitrator thread starts, it detects that both trains are standstill, and forces the eastbound train to move on, thus opening up the crossing for the second train.
</p>
<p>
<h2>Summary</h2>
To summarise, where there is contention between equal priority and interdependent threads, consider introducing a controller or arbitrator to enforce judgement at execution junctures where deadlock is highly probable. 
</p>
<p>
Please note that the term <i>arbitrator</i> is used here in an abstract context. There are many ways to implement/achieve the same behaviour, and in fact, you may be able to achieve the same effect using concurrency constructs available in standard edition Java—depending of course on the structure of your problem and solution.
</p>

<p>
In the next installment, we will examine the Worker Aggregation anti-pattern.
</p>


    ]]></content>
  </entry>
  <entry>
    <title>Annotations, to do or not to do?</title>
    <link rel="alternate" type="text/html" href="http://www.javaworld.com/community/node/2613" />
    <id>http://www.javaworld.com/community/node/2613</id>
    <published>2009-03-15T08:35:00-04:00</published>
    <updated>2009-03-15T08:35:00-04:00</updated>
    <author>
      <name>Obi Ezechukwu</name>
    </author>
    <category term="annotations" />
    <category term="design" />
    <category term="ORM" />
    <summary type="html"><![CDATA[<!--paging_filter--><p>It goes without saying that annotations have been something of a massive boon to enterprise Java developers. In fact, we can safely say that it is one of the key weapons in a developer's arsenal when battling the complexity of various deployment descriptor and mapping specifications. </p>
    ]]></summary>
    <content type="html"><![CDATA[<!--paging_filter--><p>It goes without saying that annotations have been something of a massive boon to enterprise Java developers. In fact, we can safely say that it is one of the key weapons in a developer's arsenal when battling the complexity of various deployment descriptor and mapping specifications. </p>
<p>All that said though, is it possible that annotations can actually be considered a bad thing? Specifically, when should we use annotations and when should we avoid them? To focus on a basic example, consider the case of OR mapping, e.g. Hibernate or Entity Beans. Is there a case for not using annotations when mapping POJOs to database entities?</p>
<p>This is a question that has perplexed me all week, and I have spent an inordinate amount of time soliciting opinions for and against. To date, the case for the pro camp can be summarised as follows:</p>
<ul>
<li>Annotations reduce configuration source files, and in a lot of cases mean that you no longer require XML configuration.</li>
<li>They provide transparency, so that it easy to observe a type's intended use from simply examining the source file</li>
<li>Annotations are self-documenting and condense a large amount of information into simple constructs</li>
</ul>
<p>So far so good. When presented with these arguments though, the naysayers retort with the following:</p>
<ul>
<li>Annotations add deployment context to classes. A POJO, which models a domain concept, arguably should be generic enough that it can be used throughout that domain (e.g. web application, GUI, mid-tier web-service, server side) without any reference to how it is persisted, or how it should behave in a particular context.</li>
<li>They can also introduce imports (library dependencies) which reduce the flexibility of the solution. For example, using OR annotations can introduce import statements into your code which you do not necessarily want. This not only reduces deployment scope, but also can interfere with design principles such as IOC and dependency injection. </li>
<li>Annotations can limit reuse. Now this is a fairly controversial one, and it took me a while to appreciate where the contributor was coming from. It is best appreciated with a very simple and straight to the point example: how do you cleanly map the same POJO to two different persistence stores using annotations? Or even better, how do you specify two different transaction contexts for the same service implementation using annotations?</li>
</ul>
</p>
<p>This has all the makings of a controversial topic and will probably take on religious fervour as time goes on. In the meantime, please feel free to contribute your penny's worth to the debate! </p>
    ]]></content>
  </entry>
</feed>

