<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:media="http://search.yahoo.com/mrss/"
	>

<channel>
	<title>Collaborative Creativity</title>
	<atom:link href="http://jaksa.wordpress.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://jaksa.wordpress.com</link>
	<description>Programming, Software Engineering, Computer Science</description>
	<pubDate>Thu, 09 Oct 2008 15:53:45 +0000</pubDate>
	<generator>http://wordpress.org/?v=MU</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Tuning the EJB3 Implementation</title>
		<link>http://jaksa.wordpress.com/2008/10/09/tuning-the-ejb3-implementation/</link>
		<comments>http://jaksa.wordpress.com/2008/10/09/tuning-the-ejb3-implementation/#comments</comments>
		<pubDate>Thu, 09 Oct 2008 15:53:45 +0000</pubDate>
		<dc:creator>jaksa</dc:creator>
		
		<category><![CDATA[Uncategorized]]></category>

		<category><![CDATA[eager fetching]]></category>

		<category><![CDATA[ejb3]]></category>

		<category><![CDATA[hybernate]]></category>

		<category><![CDATA[jpa]]></category>

		<category><![CDATA[lazy fetching]]></category>

		<category><![CDATA[performance]]></category>

		<category><![CDATA[transactions]]></category>

		<category><![CDATA[tuning]]></category>

		<guid isPermaLink="false">http://jaksa.wordpress.com/?p=38</guid>
		<description><![CDATA[During my evaluation of highly scalable technologies I incurred in some performance problems with the EJB3 implementation. It seems to me that it is a quite common problem
Yesterday I was getting very dissappointing results from the benchmarks of the EJB3 implementation of the sample application. I have discovered some nice hints for optimizing Hybernate and EJB3 [...]]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>During my <a href="http://code.google.com/p/cloudspeed/">evaluation</a> of highly scalable technologies I incurred in some performance problems with the EJB3 implementation. It seems to me that it is a quite common problem</p>
<p>Yesterday I was getting <a href="http://jaksa.wordpress.com/2008/10/08/measuring-the-speed-of-clouds/">very dissappointing results </a>from the benchmarks of the EJB3 implementation of the <a href="http://code.google.com/p/cloudspeed/wiki/ApplicationSpecification">sample application</a>. I have discovered some nice <a href="http://blogs.jboss.com/blog/acoliver/2006/01/23/Hibernate_EJB3_Tuning.txt">hints</a> for optimizing Hybernate and EJB3 applications and a very good <a href="http://www.infoq.com/presentations/ejb-3">video on EJB3</a>. This hepled me understand why my EJBs were not updated properly, but most of all why I was getting such poor performance.</p>
<p>The performance problem was due to the use of eager fetching on a many to many relationship. The relationship in question was friendship between users. This is a many to many relationship with itself. This means eager fetching is propagated transitively, so each time I loaded a user, all the friends were loaded as well, and also the friends of the friends and the friends of&#8230; basically the whole table.</p>
<p>By default many to many relationships use lazy fetching, but I changed this to eager when I wrote the application. The reason I had eager fetching on this relationship is that when I tried to get the number of friends a user had, my appserver was complaining that it couldn&#8217;t be done with lazy fetching. My error was in performing this through user.getFriends().size(). What I&#8217;m doing now instead is asking the database to give me the number of friends by using a query like &#8220;SELECT count(f) FROM user u JOIN u.friends f WHERE&#8230;&#8221;.</p>
<p>After that I changed some transaction attributes so that read only operations do not require transactions. Given the semantic of the methods I don&#8217;t require a strong level on consistency, so it&#8217;s relatively safe to do this. This minimizes delays due to contention and increases the paralellizability (try pronouncing this aloud) of the applications.</p>
<p>The result was that now my application runs 10 times faster. Now I&#8217;m getting 79 requests per second if I run the server on an EC2 instance and the client on my machine. This is just a little slower than the 100 requests per second obtained by the pojo in memoty solution, which means that EJB3 is pretty fast. I still have to test this without the communication bottleneck to be sure of the actual performance.</p>
Posted in Uncategorized&nbsp;&nbsp;&nbsp;Tagged: eager fetching, ejb3, hybernate, jpa, lazy fetching, performance, transactions, tuning&nbsp;&nbsp;&nbsp;<a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/jaksa.wordpress.com/38/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/jaksa.wordpress.com/38/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/jaksa.wordpress.com/38/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/jaksa.wordpress.com/38/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/jaksa.wordpress.com/38/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/jaksa.wordpress.com/38/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/jaksa.wordpress.com/38/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/jaksa.wordpress.com/38/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/jaksa.wordpress.com/38/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/jaksa.wordpress.com/38/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=jaksa.wordpress.com&blog=2662408&post=38&subd=jaksa&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://jaksa.wordpress.com/2008/10/09/tuning-the-ejb3-implementation/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Measuring the Speed of Clouds</title>
		<link>http://jaksa.wordpress.com/2008/10/08/measuring-the-speed-of-clouds/</link>
		<comments>http://jaksa.wordpress.com/2008/10/08/measuring-the-speed-of-clouds/#comments</comments>
		<pubDate>Wed, 08 Oct 2008 16:39:24 +0000</pubDate>
		<dc:creator>jaksa</dc:creator>
		
		<category><![CDATA[Uncategorized]]></category>

		<category><![CDATA[cloud computing]]></category>

		<category><![CDATA[benchmark]]></category>

		<category><![CDATA[ec2]]></category>

		<category><![CDATA[ejb3]]></category>

		<category><![CDATA[jee]]></category>

		<category><![CDATA[servlets]]></category>

		<category><![CDATA[j2ee]]></category>

		<category><![CDATA[jboss]]></category>

		<category><![CDATA[mysql]]></category>

		<category><![CDATA[amazon]]></category>

		<category><![CDATA[jpa]]></category>

		<category><![CDATA[scalability]]></category>

		<category><![CDATA[performance]]></category>

		<guid isPermaLink="false">http://jaksa.wordpress.com/?p=36</guid>
		<description><![CDATA[
I have started a project for benchmarking highly scalable technologies. My plan is to use cloud computing platforms and implement the same application using different stacks of technologies. The aspect I want to evaluate is performance when the number of nodes grows a lot.
Application specification
The application I&#8217;m using for benchmarking is a simplified model of [...]]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><div dir="ltr">
<div dir="ltr">I have started a project for benchmarking highly scalable technologies. My plan is to use cloud computing platforms and implement the same application using different stacks of technologies. The aspect I want to evaluate is performance when the number of nodes grows a lot.<span id="more-36"></span></div>
<div dir="ltr"><strong>Application specification</strong></div>
<div dir="ltr">The application I&#8217;m using for benchmarking is a simplified model of Facebook.</div>
<div dir="ltr"></div>
<div dir="ltr"><strong>Implementations</strong></div>
<div dir="ltr">Currently I have 2 implementations:</div>
<div dir="ltr">Servlets + EJB3</div>
<div dir="ltr">Servlets + in memory Java</div>
<div dir="ltr"></div>
<div dir="ltr"><strong>Benchmark</strong></div>
<div dir="ltr">As benchmarking client I&#8217;m using JMeter.</div>
<div dir="ltr">The benchmark looks like this: a number of threads will start iterating over the following sequence</div>
<div dir="ltr">
<ol>
<li>load first page (redirection)</li>
<li>load login page</li>
<li>login</li>
<li>load main page</li>
<li>add post</li>
<li>add friend</li>
<li>logout</li>
</ol>
</div>
<div dir="ltr">There are no pauses so in theory, this should test the capacity of the server.</div>
<div dir="ltr">Ideally there would be a very large number of threads (users) performing requests occasionally.</div>
<div dir="ltr"></div>
<div dir="ltr"><strong>Configurations tested</strong></div>
<div dir="ltr">I have tested everything <strong>on my machine </strong>before deploying on EC2. I have used JBoss and MySql for the EJB solution.</div>
<div dir="ltr">The performance I obtained was around 10 requests per second, which is dissapointing. Probably I have a bottleneck somewhere and need to configure things properly.</div>
<div dir="ltr">The In Memory Java implementation achieves more than 1000 requests per second, which is 100 times faster than using EJBs. However it occasionally throws ConcurrentModificationExceptions because I&#8217;m not synchronozing properly (fixing this will lower performance).</div>
<div dir="ltr">Then I deployed everything on <strong>one EC2 instance</strong>.</div>
<div dir="ltr">When I run the client on the outside I get around 100 requests per second, which may be due to my internet connection speed. But when I execute the client on another EC2 instance, I expect no communication bottlenecks. Instead I get 3 requests per second. Either there is a huge traffic jam on the EC2 internal network or I have misconfigured the benchmark client.</div>
<div dir="ltr">Running the benchmark on the EJB3 implementation shows a performance of 7 requests per second.</div>
<div dir="ltr"></div>
</div>
<div dir="ltr">Next thing I need to do is some EJB3 tuning. I have the feeling I have not set up transactions correctly.</div>
<div dir="ltr">If you have any suggestion or wish your technology stack to be evaluated or perhaps want to contribute, please leave a comment.</div>
Posted in Uncategorized&nbsp;&nbsp;&nbsp;Tagged: amazon, benchmark, cloud computing, ec2, ejb3, j2ee, jboss, jee, jpa, mysql, performance, scalability, servlets&nbsp;&nbsp;&nbsp;<a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/jaksa.wordpress.com/36/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/jaksa.wordpress.com/36/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/jaksa.wordpress.com/36/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/jaksa.wordpress.com/36/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/jaksa.wordpress.com/36/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/jaksa.wordpress.com/36/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/jaksa.wordpress.com/36/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/jaksa.wordpress.com/36/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/jaksa.wordpress.com/36/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/jaksa.wordpress.com/36/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=jaksa.wordpress.com&blog=2662408&post=36&subd=jaksa&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://jaksa.wordpress.com/2008/10/08/measuring-the-speed-of-clouds/feed/</wfw:commentRss>
		</item>
		<item>
		<title>foreach in Java</title>
		<link>http://jaksa.wordpress.com/2008/09/19/foreach-in-java/</link>
		<comments>http://jaksa.wordpress.com/2008/09/19/foreach-in-java/#comments</comments>
		<pubDate>Fri, 19 Sep 2008 13:23:31 +0000</pubDate>
		<dc:creator>jaksa</dc:creator>
		
		<category><![CDATA[programming]]></category>

		<category><![CDATA[java]]></category>

		<category><![CDATA[generics]]></category>

		<category><![CDATA[closures]]></category>

		<category><![CDATA[dynamic proxy]]></category>

		<category><![CDATA[reflection]]></category>

		<category><![CDATA[for]]></category>

		<category><![CDATA[loop]]></category>

		<category><![CDATA[collection]]></category>

		<guid isPermaLink="false">http://jaksa.wordpress.com/?p=13</guid>
		<description><![CDATA[Here&#8217;s a cool but unfortunately useless example of java generics, combined with reflection, combined with dynamic proxies.

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.ArrayList;
import java.util.List;

import sun.reflect.generics.reflectiveObjects.NotImplementedException;
import sun.reflect.generics.tree.ReturnType;

public class Foreach {
  @SuppressWarnings("unchecked")
  public static &#60;T&#62; T foreach(T... elements) {
    ApplyOnArrray&#60;T&#62; handler = new ApplyOnArrray&#60;T&#62;(elements);
    return (T) Proxy.newProxyInstance(elements[0].getClass().getClassLoader(),
     [...]]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>Here&#8217;s a cool but unfortunately useless example of java generics, combined with reflection, combined with dynamic proxies.</p>
<p><span id="more-13"></span></p>
<pre><span><strong>import java.lang.reflect.InvocationHandler;</strong></span>
<span><strong>import java.lang.reflect.Method;</strong></span>
<span><strong>import java.lang.reflect.Proxy;</strong></span>
<span><strong>import java.util.ArrayList;</strong></span>
<span><strong>import java.util.List;</strong></span>

<span><strong>import sun.reflect.generics.reflectiveObjects.NotImplementedException;</strong></span>
<span><strong>import sun.reflect.generics.tree.ReturnType;</strong></span>

<strong>public</strong> <strong>class</strong> <span style="color:#2040a0;">Foreach</span> <span><strong>{</strong></span>
  @<span style="color:#2040a0;">SuppressWarnings</span><span><strong>(</strong></span><span style="color:#008000;">"unchecked"</span><span><strong>)</strong></span>
<strong>  public</strong> <strong>static</strong> <span>&lt;</span><span style="color:#2040a0;">T</span><span>&gt;</span> <span style="color:#2040a0;">T</span> <span style="color:#2040a0;">foreach</span><span><strong>(</strong></span><span style="color:#2040a0;">T</span>... <span style="color:#2040a0;">elements</span><span><strong>)</strong></span> <span><strong>{</strong></span>
<span style="color:#2040a0;">    ApplyOnArrray</span><span>&lt;</span><span style="color:#2040a0;">T</span><span>&gt;</span> <span style="color:#2040a0;">handler</span> <span>=</span> <strong>new</strong> <span style="color:#2040a0;">ApplyOnArrray</span><span>&lt;</span><span style="color:#2040a0;">T</span><span>&gt;</span><span><strong>(</strong></span><span style="color:#2040a0;">elements</span><span><strong>)</strong></span><span>;</span>
<strong>    return</strong> <span><strong>(</strong></span><span style="color:#2040a0;">T</span><span><strong>)</strong></span> <span style="color:#2040a0;">Proxy</span>.<span style="color:#2040a0;">newProxyInstance</span><span><strong>(</strong></span><span style="color:#2040a0;">elements</span><span><strong>[</strong></span><span style="color:#ff0000;">0</span><span><strong>]</strong></span>.<span style="color:#2040a0;">getClass</span><span><strong>(</strong></span><span><strong>)</strong></span>.<span style="color:#2040a0;">getClassLoader</span><span><strong>(</strong></span><span><strong>)</strong></span>,
<strong>      new</strong> <span style="color:#2040a0;">Class</span><span><strong>[</strong></span><span><strong>]</strong></span> <span><strong>{</strong></span> <span style="color:#2040a0;">elements</span><span><strong>[</strong></span><span style="color:#ff0000;">0</span><span><strong>]</strong></span>.<span style="color:#2040a0;">getClass</span><span><strong>(</strong></span><span><strong>)</strong></span>.<span style="color:#2040a0;">getInterfaces</span><span><strong>(</strong></span><span><strong>)</strong></span><span><strong>[</strong></span><span style="color:#ff0000;">0</span><span><strong>]</strong></span> <span><strong>}</strong></span>,
<span style="color:#2040a0;">      handler</span><span><strong>)</strong></span><span>;</span>
<span><strong>  }</strong></span>

<strong>  public</strong> <strong>static</strong> <span>&lt;</span><span style="color:#2040a0;">ReturnType</span><span>&gt;</span> <span style="color:#2040a0;">List</span><span>&lt;</span><span style="color:#2040a0;">ReturnType</span><span>&gt;</span> <span style="color:#2040a0;">get</span><span><strong>(</strong></span><span style="color:#2040a0;">ReturnType</span> <span style="color:#2040a0;">returnValue</span><span><strong>)</strong></span> <span><strong>{</strong></span>
<span style="color:#2040a0;">    Collector</span> <span style="color:#2040a0;">collector</span> <span>=</span> <span><strong>(</strong></span><span style="color:#2040a0;">Collector</span><span><strong>)</strong></span> <span style="color:#2040a0;">Proxy</span>.<span style="color:#2040a0;">getInvocationHandler</span><span><strong>(</strong></span><span style="color:#2040a0;">returnValue</span><span><strong>)</strong></span><span>;</span>
<strong>    return</strong> <span style="color:#2040a0;">collector</span>.<span style="color:#2040a0;">getReturnValues</span><span><strong>(</strong></span><span><strong>)</strong></span><span>;</span>
<span><strong>  }</strong></span>

<strong>  public</strong> <strong>static</strong> <strong>void</strong> <span style="color:#2040a0;">main</span><span><strong>(</strong></span><span style="color:#2040a0;">String</span><span><strong>[</strong></span><span><strong>]</strong></span> <span style="color:#2040a0;">args</span><span><strong>)</strong></span> <span><strong>{</strong></span>
<span style="color:#2040a0;">    IFoo</span> <span style="color:#2040a0;">f1</span> <span>=</span> <strong>new</strong> <span style="color:#2040a0;">Foo</span><span><strong>(</strong></span><span><strong>)</strong></span><span>;</span>
<span style="color:#2040a0;">    IFoo</span> <span style="color:#2040a0;">f2</span> <span>=</span> <strong>new</strong> <span style="color:#2040a0;">Foo</span><span><strong>(</strong></span><span><strong>)</strong></span><span>;</span>
<span style="color:#2040a0;">    IFoo</span> <span style="color:#2040a0;">f3</span> <span>=</span> <strong>new</strong> <span style="color:#2040a0;">Foo</span><span><strong>(</strong></span><span><strong>)</strong></span><span>;</span>
<span style="color:#2040a0;">    IFoo</span> <span style="color:#2040a0;">f4</span> <span>=</span> <strong>new</strong> <span style="color:#2040a0;">Foo</span><span><strong>(</strong></span><span><strong>)</strong></span><span>;</span>

<span style="color:#2040a0;">    List</span><span>&lt;</span><span style="color:#2040a0;">IString</span><span>&gt;</span> <span style="color:#2040a0;">list</span> <span>=</span> <span style="color:#2040a0;">get</span><span><strong>(</strong></span><span style="color:#2040a0;">foreach</span><span><strong>(</strong></span><span style="color:#2040a0;">f1</span>, <span style="color:#2040a0;">f2</span>, <span style="color:#2040a0;">f3</span>, <span style="color:#2040a0;">f4</span><span><strong>)</strong></span>.<span style="color:#2040a0;">sayFoo</span><span><strong>(</strong></span><span><strong>)</strong></span><span><strong>)</strong></span><span>;</span>
<span style="color:#2040a0;">    System</span>.<span style="color:#2040a0;">out</span>.<span style="color:#2040a0;">println</span><span><strong>(</strong></span><span style="color:#2040a0;">list</span><span><strong>)</strong></span><span>;</span>
<span><strong>  }</strong></span>
<span><strong>}</strong></span>

<strong>class</strong> <span style="color:#2040a0;">Collector</span> <strong>implements</strong> <span style="color:#2040a0;">InvocationHandler</span> <span><strong>{</strong></span>
<strong>  private</strong> <strong>final</strong> <span style="color:#2040a0;">List</span> <span style="color:#2040a0;">returnValues</span><span>;</span>

<strong>  public</strong> <span style="color:#2040a0;">Collector</span><span><strong>(</strong></span><span style="color:#2040a0;">List</span> <span style="color:#2040a0;">returnValues</span><span><strong>)</strong></span> <span><strong>{</strong></span>
<strong>    this</strong>.<span style="color:#2040a0;">returnValues</span> <span>=</span> <span style="color:#2040a0;">returnValues</span><span>;</span>
<span><strong>  }</strong></span>

<strong>  public</strong> <span style="color:#2040a0;">List</span> <span style="color:#2040a0;">getReturnValues</span><span><strong>(</strong></span><span><strong>)</strong></span> <span><strong>{</strong></span>
<strong>    return</strong> <span style="color:#2040a0;">returnValues</span><span>;</span>
<span><strong>  }</strong></span>

<strong>  public</strong> <span style="color:#2040a0;">Object</span> <span style="color:#2040a0;">invoke</span><span><strong>(</strong></span><span style="color:#2040a0;">Object</span> <span style="color:#2040a0;">proxy</span>, <span style="color:#2040a0;">Method</span> <span style="color:#2040a0;">method</span>, <span style="color:#2040a0;">Object</span><span><strong>[</strong></span><span><strong>]</strong></span> <span style="color:#2040a0;">args</span><span><strong>)</strong></span> <strong>throws</strong> <span style="color:#2040a0;">Throwable</span> <span><strong>{</strong></span>
<span style="color:#444444;">    // TODO get(foreach(elements).method(args))</span>
<strong>    throw</strong> <strong>new</strong> <span style="color:#2040a0;">NotImplementedException</span><span><strong>(</strong></span><span><strong>)</strong></span><span>;</span>
<span><strong>  }</strong></span>
<span><strong>}</strong></span>

<strong>interface</strong> <span style="color:#2040a0;">IString</span> <span><strong>{</strong></span> <span style="color:#2040a0;">String</span> <span style="color:#2040a0;">toString</span><span><strong>(</strong></span><span><strong>)</strong></span><span>;</span> <span><strong>}</strong></span>

<strong>  class</strong> <span style="color:#2040a0;">StringImpl</span> <strong>implements</strong> <span style="color:#2040a0;">IString</span> <span><strong>{</strong></span>
<strong>    private</strong> <span style="color:#2040a0;">String</span> <span style="color:#2040a0;">s</span><span>;</span>
<strong>    public</strong> <span style="color:#2040a0;">StringImpl</span><span><strong>(</strong></span><span style="color:#2040a0;">String</span> <span style="color:#2040a0;">s</span><span><strong>)</strong></span> <span><strong>{</strong></span> <strong>this</strong>.<span style="color:#2040a0;">s</span> <span>=</span> <span style="color:#2040a0;">s</span><span>;</span> <span><strong>}</strong></span>
<strong>    public</strong> <span style="color:#2040a0;">String</span> <span style="color:#2040a0;">toString</span><span><strong>(</strong></span><span><strong>)</strong></span> <span><strong>{</strong></span> <strong>return</strong> <span style="color:#2040a0;">s</span><span>;</span> <span><strong>}</strong></span>
<span><strong>  }</strong></span>

<strong>interface</strong> <span style="color:#2040a0;">IFoo</span> <span><strong>{</strong></span> <span style="color:#2040a0;">IString</span> <span style="color:#2040a0;">sayFoo</span><span><strong>(</strong></span><span><strong>)</strong></span><span>;</span> <span><strong>}</strong></span><span>;</span>

<strong>class</strong> <span style="color:#2040a0;">Foo</span> <strong>implements</strong> <span style="color:#2040a0;">IFoo</span> <span><strong>{</strong></span>
<strong>  public</strong> <span style="color:#2040a0;">IString</span> <span style="color:#2040a0;">sayFoo</span><span><strong>(</strong></span><span><strong>)</strong></span> <span><strong>{</strong></span>
<span style="color:#2040a0;">    System</span>.<span style="color:#2040a0;">out</span>.<span style="color:#2040a0;">println</span><span><strong>(</strong></span><span style="color:#008000;">"foo"</span><span><strong>)</strong></span><span>;</span>
<strong>    return</strong> <strong>new</strong> <span style="color:#2040a0;">StringImpl</span><span><strong>(</strong></span><span style="color:#008000;">"foo"</span><span><strong>)</strong></span><span>;</span>
<span><strong>  }</strong></span>
<span><strong>}</strong></span><span>;</span>

<strong>class</strong> <span style="color:#2040a0;">ApplyOnArrray</span><span>&lt;</span><span style="color:#2040a0;">T</span><span>&gt;</span> <strong>implements</strong> <span style="color:#2040a0;">InvocationHandler</span> <span><strong>{</strong></span>
<strong>  private</strong> <strong>final</strong> <span style="color:#2040a0;">T</span><span><strong>[</strong></span><span><strong>]</strong></span> <span style="color:#2040a0;">elements</span><span>;</span>

<strong>  public</strong> <span style="color:#2040a0;">ApplyOnArrray</span><span><strong>(</strong></span><span style="color:#2040a0;">T</span>... <span style="color:#2040a0;">elements</span><span><strong>)</strong></span> <span><strong>{</strong></span> <strong>this</strong>.<span style="color:#2040a0;">elements</span> <span>=</span> <span style="color:#2040a0;">elements</span><span>;</span> <span><strong>}</strong></span>

<strong>  public</strong> <span style="color:#2040a0;">Object</span> <span style="color:#2040a0;">invoke</span><span><strong>(</strong></span><span style="color:#2040a0;">Object</span> <span style="color:#2040a0;">proxy</span>, <span style="color:#2040a0;">Method</span> <span style="color:#2040a0;">method</span>, <span style="color:#2040a0;">Object</span><span><strong>[</strong></span><span><strong>]</strong></span> <span style="color:#2040a0;">args</span><span><strong>)</strong></span> <strong>throws</strong> <span style="color:#2040a0;">Throwable</span> <span><strong>{</strong></span>
<span style="color:#2040a0;">    Method</span> <span style="color:#2040a0;">targetMethod</span> <span>=</span> <span style="color:#2040a0;">elements</span><span><strong>[</strong></span><span style="color:#ff0000;">0</span><span><strong>]</strong></span>.<span style="color:#2040a0;">getClass</span><span><strong>(</strong></span><span><strong>)</strong></span>.<span style="color:#2040a0;">getMethod</span><span><strong>(</strong></span><span style="color:#2040a0;">method</span>.<span style="color:#2040a0;">getName</span><span><strong>(</strong></span><span><strong>)</strong></span>, <span style="color:#2040a0;">method</span>.<span style="color:#2040a0;">getParameterTypes</span><span><strong>(</strong></span><span><strong>)</strong></span><span><strong>)</strong></span><span>;</span>

<span style="color:#2040a0;">    List</span> <span style="color:#2040a0;">returnValues</span> <span>=</span> <strong>new</strong> <span style="color:#2040a0;">ArrayList</span><span><strong>(</strong></span><span><strong>)</strong></span><span>;</span>
<strong>    for</strong> <span><strong>(</strong></span><span style="color:#2040a0;">T</span> <span style="color:#2040a0;">element</span> <span>:</span> <span style="color:#2040a0;">elements</span><span><strong>)</strong></span> <span style="color:#2040a0;">returnValues</span>.<span style="color:#2040a0;">add</span><span><strong>(</strong></span><span style="color:#2040a0;">targetMethod</span>.<span style="color:#2040a0;">invoke</span><span><strong>(</strong></span><span style="color:#2040a0;">element</span>, <span style="color:#2040a0;">args</span><span><strong>)</strong></span><span><strong>)</strong></span><span>;</span>

<span style="color:#444444;">    // return a proxy for the result</span>
<strong>    return</strong> <span><strong>(</strong></span><span style="color:#2040a0;">T</span><span><strong>)</strong></span> <span style="color:#2040a0;">Proxy</span>.<span style="color:#2040a0;">newProxyInstance</span><span><strong>(</strong></span><span style="color:#2040a0;">elements</span><span><strong>[</strong></span><span style="color:#ff0000;">0</span><span><strong>]</strong></span>.<span style="color:#2040a0;">getClass</span><span><strong>(</strong></span><span><strong>)</strong></span>.<span style="color:#2040a0;">getClassLoader</span><span><strong>(</strong></span><span><strong>)</strong></span>,
<strong>    new</strong> <span style="color:#2040a0;">Class</span><span><strong>[</strong></span><span><strong>]</strong></span> <span><strong>{</strong></span> <span style="color:#2040a0;">targetMethod</span>.<span style="color:#2040a0;">getReturnType</span><span><strong>(</strong></span><span><strong>)</strong></span> <span><strong>}</strong></span>,
<strong>    new</strong> <span style="color:#2040a0;">Collector</span><span><strong>(</strong></span><span style="color:#2040a0;">returnValues</span><span><strong>)</strong></span><span><strong>)</strong></span><span>;</span>
<span><strong>  }</strong></span>

<span><strong>}</strong></span></pre>
<p><code><span style="font-family:'Lucida Grande';">I had this idea in a dream (too much work) and fortunately I could still remember it in the morning. Who knows, I might have dreamt also a solution that works with classes.</span><br />
</code></p>
Posted in programming&nbsp;&nbsp;&nbsp;Tagged: closures, collection, dynamic proxy, for, generics, java, loop, reflection&nbsp;&nbsp;&nbsp;<a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/jaksa.wordpress.com/13/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/jaksa.wordpress.com/13/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/jaksa.wordpress.com/13/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/jaksa.wordpress.com/13/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/jaksa.wordpress.com/13/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/jaksa.wordpress.com/13/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/jaksa.wordpress.com/13/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/jaksa.wordpress.com/13/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/jaksa.wordpress.com/13/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/jaksa.wordpress.com/13/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=jaksa.wordpress.com&blog=2662408&post=13&subd=jaksa&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://jaksa.wordpress.com/2008/09/19/foreach-in-java/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Eclipse Action with Generics</title>
		<link>http://jaksa.wordpress.com/2008/05/30/eclipse-action-with-generics/</link>
		<comments>http://jaksa.wordpress.com/2008/05/30/eclipse-action-with-generics/#comments</comments>
		<pubDate>Fri, 30 May 2008 15:21:39 +0000</pubDate>
		<dc:creator>jaksa</dc:creator>
		
		<category><![CDATA[programming]]></category>

		<category><![CDATA[eclipse]]></category>

		<category><![CDATA[generics]]></category>

		<category><![CDATA[java]]></category>

		<guid isPermaLink="false">http://jaksa.wordpress.com/?p=12</guid>
		<description><![CDATA[I wrote this code a couple of weeks ago. It&#8217;s a nice idea on how to use generics in order to reduce the pain of using the Eclipse API.

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.eclipse.jface.action.IAction;

import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.IObjectActionDelegate;
import org.eclipse.ui.IWorkbenchPart;

/**
 * An eclipse action delegate that performs operations on objects of the
 * specified type. Automatically handles [...]]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>I wrote this code a couple of weeks ago. It&#8217;s a nice idea on how to use generics in order to reduce the pain of using the Eclipse API.</p>
<p><span id="more-12"></span></p>
<pre><span style="color:#0000ff;"><strong>import java.util.ArrayList;</strong></span>
<span style="color:#0000ff;"><strong>import java.util.Iterator;</strong></span>
<span style="color:#0000ff;"><strong>import java.util.List;</strong></span>

<span style="color:#0000ff;"><strong>import org.eclipse.jface.action.IAction;</strong></span>

<span style="color:#0000ff;"><strong>import org.eclipse.jface.viewers.ISelection;</strong></span>
<span style="color:#0000ff;"><strong>import org.eclipse.jface.viewers.StructuredSelection;</strong></span>
<span style="color:#0000ff;"><strong>import org.eclipse.swt.widgets.Shell;</strong></span>
<span style="color:#0000ff;"><strong>import org.eclipse.ui.IObjectActionDelegate;</strong></span>
<span style="color:#0000ff;"><strong>import org.eclipse.ui.IWorkbenchPart;</strong></span>

<span style="color:#444444;"><em>/**
 * An eclipse action delegate that performs operations on objects of the
 * specified type. Automatically handles multiple selections. Extend this class
 * specifying the type parameter of the object that the action operates on.
 * Implement the main logic in {@link #runOn(Object, IAction)}.
 *
 * @author Jaksa Vuckovic (vuckovja)
 *
 * @param
 */</em></span>
<strong>public</strong> <strong>abstract</strong> <strong>class</strong> <span style="color:#2040a0;">TypedAction</span> <strong>implements</strong> <span style="color:#2040a0;">IObjectActionDelegate</span> <span style="color:#4444ff;"><strong>{</strong></span>

  <strong>protected</strong> <span style="color:#2040a0;">List</span> <span style="color:#2040a0;">selectedElements</span> <span style="color:#4444ff;">=</span> <strong>new</strong> <span style="color:#2040a0;">ArrayList</span><span style="color:#4444ff;"><strong>(</strong></span><span style="color:#4444ff;"><strong>)</strong></span><span style="color:#4444ff;">;</span>
  <strong>protected</strong> <span style="color:#2040a0;">Shell</span> <span style="color:#2040a0;">shell</span><span style="color:#4444ff;">;</span>

  <strong>public</strong> <strong>void</strong> <span style="color:#2040a0;">setActivePart</span><span style="color:#4444ff;"><strong>(</strong></span><span style="color:#2040a0;">IAction</span> <span style="color:#2040a0;">action</span>, <span style="color:#2040a0;">IWorkbenchPart</span> <span style="color:#2040a0;">targetPart</span><span style="color:#4444ff;"><strong>)</strong></span> <span style="color:#4444ff;"><strong>{</strong></span>
    <strong>this</strong>.<span style="color:#2040a0;">shell</span> <span style="color:#4444ff;">=</span> <span style="color:#2040a0;">targetPart</span>.<span style="color:#2040a0;">getSite</span><span style="color:#4444ff;"><strong>(</strong></span><span style="color:#4444ff;"><strong>)</strong></span>.<span style="color:#2040a0;">getShell</span><span style="color:#4444ff;"><strong>(</strong></span><span style="color:#4444ff;"><strong>)</strong></span><span style="color:#4444ff;">;</span>
  <span style="color:#4444ff;"><strong>}</strong></span>

  <span style="color:#444444;"><em>/**
   * The default implementation will iterate over all the selected elements and
   * invoke {@link #runOn(Object, IAction)} on every on of them.
   *
   * @see org.eclipse.ui.IActionDelegate#run(org.eclipse.jface.action.IAction)
   */</em></span>
  <strong>public</strong> <strong>void</strong> <span style="color:#2040a0;">run</span><span style="color:#4444ff;"><strong>(</strong></span><span style="color:#2040a0;">IAction</span> <span style="color:#2040a0;">action</span><span style="color:#4444ff;"><strong>)</strong></span> <span style="color:#4444ff;"><strong>{</strong></span>
    <strong>for</strong> <span style="color:#4444ff;"><strong>(</strong></span><span style="color:#2040a0;">T</span> <span style="color:#2040a0;">element</span> <span style="color:#4444ff;">:</span> <span style="color:#2040a0;">selectedElements</span><span style="color:#4444ff;"><strong>)</strong></span> <span style="color:#4444ff;"><strong>{</strong></span>
      <span style="color:#2040a0;">runOn</span><span style="color:#4444ff;"><strong>(</strong></span><span style="color:#2040a0;">element</span>, <span style="color:#2040a0;">action</span><span style="color:#4444ff;"><strong>)</strong></span><span style="color:#4444ff;">;</span>
    <span style="color:#4444ff;"><strong>}</strong></span>
  <span style="color:#4444ff;"><strong>}</strong></span>

  <span style="color:#444444;"><em>/**
   * Implement this to invoke the operation on one of the selected elements.
   * This method is called by {@link #run(IAction)} on every selected element.
   *
   * @param selectedElement one of the selected elements
   * @param action the action that has been run
   */</em></span>
  <strong>protected</strong> <strong>abstract</strong> <strong>void</strong> <span style="color:#2040a0;">runOn</span><span style="color:#4444ff;"><strong>(</strong></span><span style="color:#2040a0;">T</span> <span style="color:#2040a0;">selectedElement</span>, <span style="color:#2040a0;">IAction</span> <span style="color:#2040a0;">action</span><span style="color:#4444ff;"><strong>)</strong></span><span style="color:#4444ff;">;</span>

  <span style="color:#444444;"><em>/**
   * The default implementation will enable the action if all the selected
   * elements are of type T.
   *
   * @see org.eclipse.ui.IActionDelegate#selectionChanged(org.eclipse.jface.action.IAction,
   *      org.eclipse.jface.viewers.ISelection)
   */</em></span>
  <strong>public</strong> <strong>void</strong> <span style="color:#2040a0;">selectionChanged</span><span style="color:#4444ff;"><strong>(</strong></span><span style="color:#2040a0;">IAction</span> <span style="color:#2040a0;">action</span>, <span style="color:#2040a0;">ISelection</span> <span style="color:#2040a0;">selection</span><span style="color:#4444ff;"><strong>)</strong></span> <span style="color:#4444ff;"><strong>{</strong></span>
    <span style="color:#2040a0;">selectedElements</span>.<span style="color:#2040a0;">clear</span><span style="color:#4444ff;"><strong>(</strong></span><span style="color:#4444ff;"><strong>)</strong></span><span style="color:#4444ff;">;</span>

    <strong>boolean</strong> <span style="color:#2040a0;">enabled</span> <span style="color:#4444ff;">=</span> <strong>false</strong><span style="color:#4444ff;">;</span>

    <strong>if</strong> <span style="color:#4444ff;"><strong>(</strong></span><span style="color:#2040a0;">selection</span> <strong>instanceof</strong> <span style="color:#2040a0;">StructuredSelection</span><span style="color:#4444ff;"><strong>)</strong></span> <span style="color:#4444ff;"><strong>{</strong></span>
      <span style="color:#2040a0;">enabled</span> <span style="color:#4444ff;">=</span> <strong>true</strong><span style="color:#4444ff;">;</span>

      <strong>for</strong> <span style="color:#4444ff;"><strong>(</strong></span><span style="color:#2040a0;">Iterator</span> <span style="color:#2040a0;">it</span> <span style="color:#4444ff;">=</span> <span style="color:#4444ff;"><strong>(</strong></span><span style="color:#4444ff;"><strong>(</strong></span><span style="color:#2040a0;">StructuredSelection</span><span style="color:#4444ff;"><strong>)</strong></span> <span style="color:#2040a0;">selection</span><span style="color:#4444ff;"><strong>)</strong></span>.<span style="color:#2040a0;">iterator</span><span style="color:#4444ff;"><strong>(</strong></span><span style="color:#4444ff;"><strong>)</strong></span><span style="color:#4444ff;">;</span> <span style="color:#2040a0;">it</span>.<span style="color:#2040a0;">hasNext</span><span style="color:#4444ff;"><strong>(</strong></span><span style="color:#4444ff;"><strong>)</strong></span><span style="color:#4444ff;">;</span><span style="color:#4444ff;"><strong>)</strong></span> <span style="color:#4444ff;"><strong>{</strong></span>
        <strong>try</strong> <span style="color:#4444ff;"><strong>{</strong></span>
          <span style="color:#2040a0;">T</span> <span style="color:#2040a0;">selectedElement</span> <span style="color:#4444ff;">=</span> <span style="color:#4444ff;"><strong>(</strong></span><span style="color:#2040a0;">T</span><span style="color:#4444ff;"><strong>)</strong></span> <span style="color:#2040a0;">it</span>.<span style="color:#2040a0;">next</span><span style="color:#4444ff;"><strong>(</strong></span><span style="color:#4444ff;"><strong>)</strong></span><span style="color:#4444ff;">;</span>
          <span style="color:#2040a0;">selectedElements</span>.<span style="color:#2040a0;">add</span><span style="color:#4444ff;"><strong>(</strong></span><span style="color:#2040a0;">selectedElement</span><span style="color:#4444ff;"><strong>)</strong></span><span style="color:#4444ff;">;</span>
        <span style="color:#4444ff;"><strong>}</strong></span> <strong>catch</strong> <span style="color:#4444ff;"><strong>(</strong></span><span style="color:#2040a0;">ClassCastException</span> <span style="color:#2040a0;">e</span><span style="color:#4444ff;"><strong>)</strong></span> <span style="color:#4444ff;"><strong>{</strong></span>
          <span style="color:#2040a0;">enabled</span> <span style="color:#4444ff;">=</span> <strong>false</strong><span style="color:#4444ff;">;</span>
          <strong>break</strong><span style="color:#4444ff;">;</span>
        <span style="color:#4444ff;"><strong>}</strong></span>
      <span style="color:#4444ff;"><strong>}</strong></span>
    <span style="color:#4444ff;"><strong>}</strong></span>
    <span style="color:#2040a0;">action</span>.<span style="color:#2040a0;">setEnabled</span><span style="color:#4444ff;"><strong>(</strong></span><span style="color:#2040a0;">enabled</span><span style="color:#4444ff;"><strong>)</strong></span><span style="color:#4444ff;">;</span>
  <span style="color:#4444ff;"><strong>}</strong></span>
<span style="color:#4444ff;"><strong>}</strong></span></pre>
<p>Try to refactor your actions to extend this class and you will find a significant reduction in code size</p>
<p>PS: <em>syntax highlighted by <a href="http://www.palfrader.org/code2html">Code2HTML</a>, v. 0.9.1</em></p>
<img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/jaksa.wordpress.com/12/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/jaksa.wordpress.com/12/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/jaksa.wordpress.com/12/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/jaksa.wordpress.com/12/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/jaksa.wordpress.com/12/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/jaksa.wordpress.com/12/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/jaksa.wordpress.com/12/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/jaksa.wordpress.com/12/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/jaksa.wordpress.com/12/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/jaksa.wordpress.com/12/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/jaksa.wordpress.com/12/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/jaksa.wordpress.com/12/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=jaksa.wordpress.com&blog=2662408&post=12&subd=jaksa&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://jaksa.wordpress.com/2008/05/30/eclipse-action-with-generics/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Graph Algorithms with fork/join</title>
		<link>http://jaksa.wordpress.com/2008/04/22/graph-algorithms-with-forkjoin/</link>
		<comments>http://jaksa.wordpress.com/2008/04/22/graph-algorithms-with-forkjoin/#comments</comments>
		<pubDate>Tue, 22 Apr 2008 09:52:38 +0000</pubDate>
		<dc:creator>jaksa</dc:creator>
		
		<category><![CDATA[concurrency]]></category>

		<category><![CDATA[fork]]></category>

		<category><![CDATA[join]]></category>

		<guid isPermaLink="false">http://jaksa.wordpress.com/?p=10</guid>
		<description><![CDATA[The equivalent of the hello world for parallel languages is the quicksort algorithm. The quicksort algorithm is based on the divide et impera principle, which makes it a good candidate for parallelization. In this article we will go past arrays and apply parallelism to more complex data structures such as graphs.
We will start by performing [...]]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>The equivalent of the hello world for parallel languages is the quicksort algorithm. The quicksort algorithm is based on the divide et impera principle, which makes it a good candidate for parallelization. In this article we will go past arrays and apply parallelism to more complex data structures such as graphs.<span id="more-10"></span></p>
<p>We will start by performing a DFS (Depth First Search). Given a starting node, visit all other reachable nodes. This algorithm can be adapted to solve many problems. Let&#8217;s see the basic form of this algorithm:</p>
<pre>public void dfs(Node n) {
  Set&lt;Node&gt; visitedNodes = new HashSet&lt;Node&gt;();
  dfs(n, visitedNodes);
}

private void dfs(Node n, Set&lt;Node&gt; visitedNodes) {
  if (!visitedNodes.contains(n)) {
    doSomeStuff(n);
    visitedNodes.add(n);
    for(Node neighbor: n.getNeighbors()) {
      dfs(neighbor, visitedNodes);
    }
  }
}</pre>
<p>The straightforward translation using the fork/join framework would look like:</p>
<pre>public class DFS extends RecursiveAction {
  public DFS(Node n) { this(n, new HashSet&lt;Node&gt;()); }

  private DFS(Node n, Set&lt;Node&gt; visitedNodes) {
    this.n = n;
    this.visitedNodes = visitedNodes;
  }

  public void compute() {
    if (!visitedNodes.contains(n)) {
      doSomeStuff(n);
      visitedNodes.add(n);
      DFS[] subtasks = new DFS[n.getNeighbors().size()];
      for(int i = 0; i &lt; n.getNeighbors().size(); i++) {
        subtasks[i] = new DFS(n.getNeighbors().get(i), visitedNodes);
      }
      forkJoin(subtasks);
    }
  }
}</pre>
<p>You may have noticed that this code is actually not thread safe. If we have a subgraph with a diamond topology, we may end up visiting a node more than once. In the failing scenario one thread will check whether node has been visited, and while it&#8217;s visiting the node, another thread would arrive to the same node via a different route, seeing that the node hasn&#8217;t been visited and start visiting it.</p>
<p>In order to fix that we must add a bit of synchronization. First of all we will mark a node as being visited even before visiting it, then we will define a critical section around the check and mark operations:</p>
<pre>  public void compute() {
    boolean shouldVisit;
    synchronized(visitedNodes) {
      shouldVisit = !visitedNodes.contains(n);
      visitedNodes.add(n);
    }
    if (shouldVisit) {
      doSomeStuff(n);
      DFS[] subtasks = new DFS[n.getNeighbors().size()];
      for(int i = 0; i &lt; n.getNeighbors().size(); i++) {
        subtasks[i] = new DFS(n.getNeighbors().get(i), visitedNodes);
      }
      forkJoin(subtasks);
    }
  }</pre>
<p>Ok, so now we have a working algorithm, but there still is a problem. Can you spot it? Try to figure out a solution.<br />
I will post the solution in my next post and talk a little bit about a parallel BFS (Breadth First Search).</p>
<img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/jaksa.wordpress.com/10/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/jaksa.wordpress.com/10/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/jaksa.wordpress.com/10/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/jaksa.wordpress.com/10/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/jaksa.wordpress.com/10/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/jaksa.wordpress.com/10/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/jaksa.wordpress.com/10/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/jaksa.wordpress.com/10/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/jaksa.wordpress.com/10/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/jaksa.wordpress.com/10/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/jaksa.wordpress.com/10/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/jaksa.wordpress.com/10/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=jaksa.wordpress.com&blog=2662408&post=10&subd=jaksa&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://jaksa.wordpress.com/2008/04/22/graph-algorithms-with-forkjoin/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Class Invariants</title>
		<link>http://jaksa.wordpress.com/2008/04/16/class-invariants/</link>
		<comments>http://jaksa.wordpress.com/2008/04/16/class-invariants/#comments</comments>
		<pubDate>Wed, 16 Apr 2008 11:54:33 +0000</pubDate>
		<dc:creator>jaksa</dc:creator>
		
		<category><![CDATA[programming]]></category>

		<category><![CDATA[design]]></category>

		<category><![CDATA[invariants]]></category>

		<category><![CDATA[validation]]></category>

		<guid isPermaLink="false">http://jaksa.wordpress.com/?p=9</guid>
		<description><![CDATA[Class invariants are a powerful design technique that is often underestimated. Here's an scenario on how I've used them to refactor. some code]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>Recently I came across a class used to store some application configuration. The configuration was stored in an XML file which was parsed in the constructor of the class. Each method of the class started with getting the root element of the XML file and if that element did not exist it needed to be created. That was a lot of code repetition that could be extracted into a common private method. But before I started changing the code, I realized it could be done in a more elegant way.<span id="more-9"></span></p>
<p>Instead of performing the check at every method invocation, I would do it only in the constructor and ensure that no method breaks that condition. This is called a <a href="http://en.wikipedia.org/wiki/Class_invariant">class invariant</a>.</p>
<p>An <a href="http://portal.acm.org/citation.cfm?coll=GUIDE&amp;dl=GUIDE&amp;id=944356">invariant</a> is a condition which is always true in any state of the object (or system). Invariants are used heavily when designing algorithms, but a lot of programmers somehow forget about them.</p>
<p>In my case it is pretty simple, the invariant says: &#8220;the document has the root element&#8221;. The document is loaded when the class is created and if there is no root element, one is created. No method of the class will reload the document, nor delete the root element.</p>
<p><strong>Requirements for Using Invariants</strong></p>
<p>Having good ecapsulation is necessary when using invariants, because you don&#8217;t want to have a method outside of your class that can break the invariant.</p>
<p>Invariants need to be documented, anyone who modifies your class should be aware of the invariants. So put a section of comments at the top of your class stating all the invariants.</p>
<p>Invariants need to be tested: put assertions at the end of each test.</p>
<p><strong>Pitfalls</strong></p>
<p>As with everything there are downsides on using invariants.</p>
<p>When using invariants in combination with inheritance, things may get complicated. If you extend a class that preserves some invariants, first of all, you need to be aware of the invariants, and then ensure that you don&#8217;t break them. For example if you have a template method in the parent class, and you implement one of the abstract methods used by the template method, you would need to run the tests of the parent class on your subclass. You can make an invariant unbreakable by the sublcasses by declaring the relative data structures as private (as opposed to protected).</p>
<p>Your invariant might be too strong. On a previous project, I needed to create a file system structure (assuming it won&#8217;t be modified externally) with a lot of files that had naming conventions. There were also a lot of conditions like file A must exist, if file C exists then we need file B etc. These conditions were required in order to run a sequence of legacy tools on the files. We performed all the validation at the beginning so we were sure that you could run all the tools.</p>
<p>But running all the tools wasn&#8217;t always required. So instead of maintaining all the conditions as invariants, we refactored to use a minimal set of conditions as invariant, and express all the others as preconditions to running the relative tools, and verifying preconditions at the beginning of the method.</p>
<p>If you realize that you are maintaining too many invariants, it might be the case that you need to decompose your class into several classes. You might even end up inventing some reusable primitives (<a href="http://en.wikipedia.org/wiki/Monitor_%28synchronization%29">monitors</a>, <a href="http://en.wikipedia.org/wiki/Database_transaction">transactions</a>, <a href="http://en.wikipedia.org/wiki/Atomic_broadcast">atomic bcast</a>)</p>
<img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/jaksa.wordpress.com/9/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/jaksa.wordpress.com/9/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/jaksa.wordpress.com/9/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/jaksa.wordpress.com/9/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/jaksa.wordpress.com/9/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/jaksa.wordpress.com/9/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/jaksa.wordpress.com/9/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/jaksa.wordpress.com/9/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/jaksa.wordpress.com/9/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/jaksa.wordpress.com/9/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/jaksa.wordpress.com/9/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/jaksa.wordpress.com/9/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=jaksa.wordpress.com&blog=2662408&post=9&subd=jaksa&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://jaksa.wordpress.com/2008/04/16/class-invariants/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Concurrency with fork/join in JDK 7</title>
		<link>http://jaksa.wordpress.com/2008/04/08/concurrency-with-forkjoin-in-jdk-7/</link>
		<comments>http://jaksa.wordpress.com/2008/04/08/concurrency-with-forkjoin-in-jdk-7/#comments</comments>
		<pubDate>Tue, 08 Apr 2008 16:24:07 +0000</pubDate>
		<dc:creator>jaksa</dc:creator>
		
		<category><![CDATA[concurrency]]></category>

		<category><![CDATA[programming]]></category>

		<category><![CDATA[fork]]></category>

		<category><![CDATA[java]]></category>

		<category><![CDATA[jdk 7]]></category>

		<category><![CDATA[join]]></category>

		<category><![CDATA[parallel]]></category>

		<guid isPermaLink="false">http://jaksa.wordpress.com/?p=8</guid>
		<description><![CDATA[A few days ago, Brian Goetz came to visit a colleague of mine in our offices and I had the opportunity to hear some of the new concurrency features coming in JDK 7. We talked about the fork/join framework and Brian kindly showed us the presentation he gave at JavaOne.
The new fork/join model is a [...]]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>A few days ago, <a href="http://www.briangoetz.com/">Brian Goetz</a> came to visit a colleague of mine in our offices and I had the opportunity to hear some of the new concurrency features coming in JDK 7. We talked about the <a href="http://www.ibm.com/developerworks/java/library/j-jtp11137.html">fork/join framework</a> and Brian kindly showed us the presentation he gave at JavaOne.<span id="more-8"></span></p>
<p>The new fork/join model is a Java implementation of a parallel loop. It allows you to perform concurrent processing on relatively large amounts of data by distributing the load among different threads. So if your hardware platform has a lot of CPUs/cores you will be able to see significant performance improvement.</p>
<p>This is how it works: you create a number of tasks and you split the workload among them. Then you run all of your tasks concurrently using the coInvoke() method. Tasks are allocated to a pool of workers for processing. After all of your tasks have executed the coInvoke() method will terminate. This allows you to run many independant operations on a number of data.</p>
<p>Moreover the framework supports recursion, which means, that tasks can create and execute other tasks. This is very important because it allows you to parallelize practically any divide-et-impera algorithm. The example Brian has shown was Mergesort, but you are not limited to array data structures, you could for example do a <a href="http://en.wikipedia.org/wiki/Breadth-first_search">BFS</a> on a graph, or solve the maximum flow problem.</p>
<p>On top of the fork/join model a very useful <a href="http://www.ibm.com/developerworks/java/library/j-jtp03048.html?S_TACT=105AGX02&amp;S_CMP=ART">parallel array</a> data structure has been implemented that allows you to perform map, filter, sort and reduce operations. This is where things get interesting, because you start to express your application logic in terms of array operations.</p>
<p>The framework is nicely designed, smartly implemented and will be very useful with the forthcoming growth of the number of processor cores. But is this really the best framework available? There are several libraries for Java that already implement the worker farm model and moreover there are many languages that have native support for such things (<a href="http://www.hpjava.org/">HPJava</a>, <a href="http://en.wikipedia.org/wiki/Fortran#Fortran_90">Fortran</a>, <a href="http://en.wikipedia.org/wiki/Occam_programming_language">Occam</a>).  Some libraries even go one level further and distribute the load on a cluster of machines (<a href="http://labs.google.com/papers/mapreduce-osdi04.pdf">Map/Reduce</a>, <a href="http://hadoop.apache.org/core/">Hadoop</a>).</p>
<p>What struck me most of all was that they didn&#8217;t integrate this parallelism in the language and the JVM. This was their most significant advantage over the existing solutions and they didn&#8217;t make use of it. It would have resulted in a much cleaner syntax and important optimizations could have been done at the JVM level. Maybe this will be a good testbed to something more radical in JDK8&#8230; or perhaps Scala?</p>
<p>PS: I apologize about some missing references, I&#8217;ll try to add these asap.</p>
<img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/jaksa.wordpress.com/8/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/jaksa.wordpress.com/8/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/jaksa.wordpress.com/8/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/jaksa.wordpress.com/8/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/jaksa.wordpress.com/8/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/jaksa.wordpress.com/8/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/jaksa.wordpress.com/8/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/jaksa.wordpress.com/8/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/jaksa.wordpress.com/8/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/jaksa.wordpress.com/8/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/jaksa.wordpress.com/8/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/jaksa.wordpress.com/8/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=jaksa.wordpress.com&blog=2662408&post=8&subd=jaksa&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://jaksa.wordpress.com/2008/04/08/concurrency-with-forkjoin-in-jdk-7/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Centralized VS Distributed SCM</title>
		<link>http://jaksa.wordpress.com/2008/02/28/centralized-vs-distributed-scm/</link>
		<comments>http://jaksa.wordpress.com/2008/02/28/centralized-vs-distributed-scm/#comments</comments>
		<pubDate>Thu, 28 Feb 2008 17:10:46 +0000</pubDate>
		<dc:creator>jaksa</dc:creator>
		
		<category><![CDATA[Uncategorized]]></category>

		<category><![CDATA[bazaar]]></category>

		<category><![CDATA[distributed scm]]></category>

		<category><![CDATA[git]]></category>

		<category><![CDATA[mercurial]]></category>

		<category><![CDATA[scm]]></category>

		<category><![CDATA[source control management]]></category>

		<category><![CDATA[subversion]]></category>

		<category><![CDATA[svk]]></category>

		<category><![CDATA[svn]]></category>

		<guid isPermaLink="false">http://jaksa.wordpress.com/?p=7</guid>
		<description><![CDATA[Distributed Source Control Management systems have become a trend in the last years: bazaar, git, mercurial, svk. Distributed SCM is a fascinating concept, but how well does it perform in practice? Some say that it leads to a phenomenon called branch proliferation.
I have researched optimistic replication for one year at  the beginning of my [...]]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><div dir="ltr">Distributed Source Control Management systems have become a trend in the last years: <a href="http://bazaar-vcs.org/">bazaar</a>, <a href="http://git.or.cz/">git</a>, <a href="http://www.selenic.com/mercurial/wiki/">mercurial</a>, <a href="http://svk.bestpractical.com/view/HomePage">svk</a>. Distributed SCM is a fascinating concept, but how well does it perform in practice? Some say that it leads to a phenomenon called branch proliferation.<span id="more-7"></span></div>
<div dir="ltr">I have researched optimistic replication for one year at  the beginning of my PhD. A distributed SCM, or correctly called multiprimary  approach, has the benefits of reduced latency and availability under network  partitions (when you can&#8217;t reach the server). The downside is the difficulty of  reconciliation: as you permit your replicas to diverge further the probability  of conflicts grows (practically exponentially). These conclusions don&#8217;t come  only from theory, reconciliation based systems existed since the 80s and never had too much  success in industry because their implementation was too complex and divergence  soon made the systems unusable.</div>
<div dir="ltr">I can confirm all of this by my experience  as a consultant at &lt;censored&gt;one of the major banks&lt;/censored&gt;. Having even 3 active branches is enough to seriously decrease your  productivity. We&#8217;re not really using a distributed SCM. We&#8217;re just using <a href="http://subversion.tigris.org/">Subversion</a>, but we&#8217;ve adopted a  branching policy (that someone called &#8220;early branching&#8221;, as if it was a common  pattern) where a branch is created for a version as soon as there is something  planned for that version.</div>
<div dir="ltr">The consequence of this is that every  change made to the current version has to be merged with all the future  versions. When you are lucky there are no conflicts, when you are a little less  lucky there are conflicts detected by SVN, but if you&#8217;re not lucky you have  &#8220;semantic&#8221; conficts that are detected only when running the overnight tests, and  it is not easy to figure out that tests are failing due to inconsistencies  caused by merges.</div>
<div dir="ltr">The patch to the problem was to  put one of the most senior developers to do the merging. Quickly enough this had  become his only job and actually keeping up with a number of conflicts generated  by 100 developers couldn&#8217;t be handled. Just a couple of days ago I found out that  the guy got sick of merging and is leaving. Now the developers are in charge of  merging their changes into the other branches as soon as possible. And finally  managers (who are apparently responsible for this error) are beginning to  realize that branching doesn&#8217;t come for free.</div>
<p>With this I don&#8217;t want to say distributed SCMs are not the way to go. On the countrary. They just need to put in place mechanisms to prevent branch proliferation, but still take advantage of a decentralized architecture and fault tollerance.</p>
<img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/jaksa.wordpress.com/7/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/jaksa.wordpress.com/7/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/jaksa.wordpress.com/7/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/jaksa.wordpress.com/7/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/jaksa.wordpress.com/7/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/jaksa.wordpress.com/7/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/jaksa.wordpress.com/7/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/jaksa.wordpress.com/7/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/jaksa.wordpress.com/7/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/jaksa.wordpress.com/7/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/jaksa.wordpress.com/7/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/jaksa.wordpress.com/7/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=jaksa.wordpress.com&blog=2662408&post=7&subd=jaksa&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://jaksa.wordpress.com/2008/02/28/centralized-vs-distributed-scm/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Playing with Jazz</title>
		<link>http://jaksa.wordpress.com/2008/02/26/playing-with-jazz/</link>
		<comments>http://jaksa.wordpress.com/2008/02/26/playing-with-jazz/#comments</comments>
		<pubDate>Tue, 26 Feb 2008 17:51:25 +0000</pubDate>
		<dc:creator>jaksa</dc:creator>
		
		<category><![CDATA[Uncategorized]]></category>

		<category><![CDATA[application lifecycle management]]></category>

		<category><![CDATA[ibm]]></category>

		<category><![CDATA[issue tracking]]></category>

		<category><![CDATA[jazz]]></category>

		<category><![CDATA[rational]]></category>

		<category><![CDATA[scm]]></category>

		<category><![CDATA[source control management]]></category>

		<guid isPermaLink="false">http://jaksa.wordpress.com/?p=4</guid>
		<description><![CDATA[Yeah, you read correctly: &#8220;Playing with Jazz&#8221;. Jazz is the new Application Lifecycle Management software developed by IBM Rational. In other words it is an all-in-one Source Control Management, Continuous Integration and Issue Tracking server. Currently I&#8217;m developing a lot of plugins for my client that are meant to integrate Jira, Subversion, Maven, ClearCase, our [...]]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>Yeah, you read correctly: &#8220;Playing with Jazz&#8221;. <a href="http://jazz.net/pub/index.jsp" target="_blank">Jazz</a> is the new Application Lifecycle Management software developed by <a href="http://www.ibm.com/software/rational/jazz/" target="_blank">IBM Rational</a>. In other words it is an all-in-one Source Control Management, Continuous Integration and Issue Tracking server. Currently I&#8217;m developing a lot of plugins for my client that are meant to integrate Jira, Subversion, Maven, ClearCase, our custom bug tracking software, our custom made overnight testing and reporting, Eclipse IDE etc. Jazz is supposed to provide these features and much more out-of-the-box.  I&#8217;ve seen the <a href="https://jazz.net/pub/learn/videos/videos.jsp" target="_blank">demos</a> and I was really impressed. So, now that it&#8217;s open for download, I registered and downloaded the server and the client.</p>
<p>Well, things are not that impressive when you start working with it. The product isn&#8217;t that ergonomic. It presents a relatively steep learing curve for the basic functionality.</p>
<p>Ideally an administrator would:</p>
<ol>
<li>install the server (it should be added automatically as a windows/*nix service)</li>
<li>start the Jazz service</li>
<li>connect to the web-admin interface</li>
<li>create some users</li>
</ol>
<p>The developer:</p>
<ol>
<li> installs the Eclipse Jazz plugin</li>
<li>connects with his username/password</li>
<li>uploads a project or two in the repository</li>
</ol>
<p>The server:</p>
<ol>
<li>autodetects how to build and test the projects (eclipse/ant/maven)</li>
<li>starts doing this immediately with a predefined schedule (continuously)</li>
<li>if there are failures it notifies the responsible developer</li>
<li>build and test status are visible in the status bar of the IDE</li>
</ol>
<p>What happens in reality is not that simple. You need to create a project area, define the process, create a team area (A team area is just a team, the word &#8220;Area&#8221; was added so that you don&#8217;t confuse the representation of a team in Jazz with the people sitting around you), create a development line, create a workspace, create a stream from your workspace to the development line, create an iteration plan, an iteration, a build configuration, a build engine etc.</p>
<p><a href="http://jaksa.files.wordpress.com/2008/02/jazz.png" title="jazz.png"></a></p>
<div style="text-align:center;"><a href="http://jaksa.files.wordpress.com/2008/02/jazz.png" title="jazz.png"><img src="http://jaksa.files.wordpress.com/2008/02/jazz.thumbnail.png" alt="jazz.png" /></a></div>
<p>What I would like to see is a product where the novice user and even the administrator initially, don&#8217;t need to know about project areas, iteration plans, development lines, streams. All these are advanced features. The first impact should present a shared versioned storage where you place your projects and it tells you whether the projects are building and whether the tests are passing. Users should be able to add tasks without having to define an iteration or an iteration plan. And most of all, I don&#8217;t like the Team Artifacts view. It&#8217;s an heterogeneus collection of entities in the Jazz server unimmaninatively organized into a tree. Integration with Eclipse should be tighter. Eclipse already knows how to build and test my projects. Why do I need to specify those things in two different places?</p>
<p>Don&#8217;t get me wrong. I don&#8217;t want to say that Jazz is overengineered. Most of the entities involved are necessary for such a product. Even multiple project areas and streams. But the point here is that they are presented in the wrong way. Advanced features should be hidden from the user and the product should be usable out-of-the-box. Ok, it took me less than 2 hours to install the server, read the instructions and configure a project, and another hour to troubleshoot the automated build. But there is really no reason why it should take more than 5 minutes.</p>
<p>I really hope that Jazz developers will take this as a constructive critique and deal with these issues before the release of Jazz. Otherwise they risk to loose a multitude of potential customers who need only simple configurations with the most basic process. And it&#8217;s from projects like these that you get the most publicity, community involvement and knowledge sharing.</p>
<img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/jaksa.wordpress.com/4/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/jaksa.wordpress.com/4/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/jaksa.wordpress.com/4/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/jaksa.wordpress.com/4/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/jaksa.wordpress.com/4/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/jaksa.wordpress.com/4/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/jaksa.wordpress.com/4/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/jaksa.wordpress.com/4/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/jaksa.wordpress.com/4/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/jaksa.wordpress.com/4/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/jaksa.wordpress.com/4/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/jaksa.wordpress.com/4/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=jaksa.wordpress.com&blog=2662408&post=4&subd=jaksa&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://jaksa.wordpress.com/2008/02/26/playing-with-jazz/feed/</wfw:commentRss>
	
		<media:content url="http://jaksa.files.wordpress.com/2008/02/jazz.thumbnail.png" medium="image">
			<media:title type="html">jazz.png</media:title>
		</media:content>
	</item>
		<item>
		<title>A Case Against the GOTO Statement</title>
		<link>http://jaksa.wordpress.com/2008/01/29/a-case-against-the-goto-statement/</link>
		<comments>http://jaksa.wordpress.com/2008/01/29/a-case-against-the-goto-statement/#comments</comments>
		<pubDate>Tue, 29 Jan 2008 21:02:19 +0000</pubDate>
		<dc:creator>jaksa</dc:creator>
		
		<category><![CDATA[programming]]></category>

		<category><![CDATA[dijkstra]]></category>

		<category><![CDATA[goto]]></category>

		<guid isPermaLink="false">http://jaksa.wordpress.com/?p=3</guid>
		<description><![CDATA[In recent times I was thinking a lot about Dijkstra&#8217;s article against the GOTO statement published in Communications of the Association for Computing Machinery (CACM) in 1968. I had the feeling that a lot of people should take one more look at it and was planning to circulate it among some of my friends. This [...]]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>In recent times I was thinking a lot about Dijkstra&#8217;s article against the GOTO statement published in <i>Communications of the Association for Computing Machinery</i> (CACM) in 1968. I had the feeling that a lot of people should take one more look at it and was planning to circulate it among some of my friends. This morning I found a copy of the Communications of ACM under my door. It&#8217;s the 50th anniversary edition and it opens with the above cited article. Apparently the editor shared my feelings that it is time to look back at the history of programming languages in order to avoid repeating the same mistakes which had caused 20 years of debate.  So here it is:</p>
<blockquote>
<h1>Go To Statement Considered Harmful</h1>
<p>For a number of years I have been familiar with the observation that the quality of programmers is a decreasing function of the density of go to statements in the programs they produce. More recently I discovered why the use of the go to statement has such disastrous effects and I became convinced that the go to statement should be abolished from all &#8220;higher level&#8221; programming languages (i.e. everything except, perhaps, plain machine code). At that time I did not attach too much importance to this discovery; I now submit my considerations for publication because in very recent discussions in which the subject turned up, I have been urged to do so.</p>
<p>My first remark is that, although the programmer&#8217;s activity ends when he has constructed a correct program, the process taking place under control of his program is the true subject matter of his activity, for it is this process that has to effectuate the desired effect, it is this process that in its dynamic behaviour has to satisfy the desired specifications. Yet, once the program has been made, the &#8220;making&#8221; of the corresponding process is delegated to the machine.</p>
<p>My second remark is that our intellectual powers are rather geared to master static relations and that our powers to visualize processes evolving in time are relatively poorly developed. For that reason we should do (as wise programmers aware of our limitations) our utmost to shorten the conceptual gap between the static program and the dynamic process, to make the correspondence between the program (spread out in text space) and the process (spread out in time) as trivial as possible.</p>
<p>Let us now consider how we can characterize the progress of a process. (You may think about this question in a very concrete manner: suppose that a process, considered as a time succession of actions, is stopped after an arbitrary action, what data do we have to fix in order that we can redo the process until that very same point?) If the program text is a pure concatenation of, say, assignment statements (for the purpose of this discussion regarded as the descriptions of single actions) it is sufficient to point in the program text to a point between two successive action descriptions. (In the absence of go to statements I can permit myself the syntactic ambiguity in the last three words of the previous sentence: if we parse them as &#8220;successive (action descriptions)&#8221; we mean successive in text space, if we parse as &#8220;(successive action) descriptions&#8221; we mean successive in time.) Let us call such a pointer to a suitable place in the text a &#8220;textual index&#8221;.</p>
<p>When we include conditional clauses (<b>if</b> B <b>then </b>A), alternative clauses (<b>if </b>S <b>then </b>A1 <b>else </b>A2), choice clauses as introduced by A.R.Hoare (&#8221;<b>case</b>[i] <b>of</b> (A1, A2,&#8230;..,An)&#8221;) or conditional expressions as introduced by J.McCarthy (&#8221;B1 → E1, B2 → E2,&#8230;.., Bn → En&#8221;), the fact remains that the progress of the process remains characterized by a single textual index.</p>
<p>As soon as we include in our language procedures we must admit that a single textual index is no longer sufficient: in the case that a textual index points to the interior of a procedure body the dynamic progress is only characterized when we also give to which call of the procedure we refer. With the inclusion of procedures we can characterize the progress of the process via a sequence of textual indices, the length of this sequence being equal to the dynamic depth of procedure calling.</p>
<p>Let us now consider repetition clauses (like &#8220;<b>while </b>B <b>repeat </b>A&#8221; or &#8220;<b>repeat </b>A <b>until </b>B&#8221;). Logically speaking, such clauses are now superfluous, because we can express repetition with the aid of recursive procedures. For reasons of realism I don&#8217;t wish to exclude them: on the one hand repetition clauses can be implemented quite comfortable with present day finite equipment, on the other hand the reasoning pattern known as &#8220;induction&#8221; makes us well equipped to retain our intellectual grasp on the processes generated by repetition clauses. With the inclusion of the repetition clauses textual indices are no longer sufficient to describe the dynamic progress of the process. With each entry into a repetition clauses, however, we can associate a so-called &#8220;dynamic index&#8221;, inexorably counting the ordinal number of the corresponding current repetition. As repetition clauses (just as procedure calls) may be applied nestedly, we find that now the progress of the process can always be uniquely characterized by a (mixed) sequence of textual and/or dynamic indices.</p>
<p>The main point is that the values of these indices are outside programmer&#8217;s control: they are generated (either by the write up of his program or by the dynamic evolution of the process) whether he wishes or not. They provide independent coordinates in which to describe the progress of the process.</p>
<p>Why do we need such independent coordinates? The reason is –and this seems to be inherent to sequential processes- that we can interpret the value of a variable only with respect to the progress of the process. If we wish to count the number, &#8220;n&#8221; say, of people in an initially empty room, we can achieve this by increasing &#8220;n&#8221; by 1 whenever we see someone entering the room; in the in-between moment that we have observed someone entering the room but have not yet performed the subsequent increase of &#8220;n&#8221;, its value equals the number of people in the room minus one!</p>
<p>The unbridled use of the go to statement has as an immediate consequence that it becomes terribly hard to find a meaningful set of coordinates in which to describe the process progress. Usually, people take into account as well the values of some well chosen variables, but this is out of the question because it is relative to the progress that the meaning of these values is to be understood! With the go to statement one can, of course, still describe the progress uniquely by a counter counting the number of actions performed since program start (viz. a kind of normalized clock). The difficulty is that such a coordinate, although unique, is utterly unhelpful: in such a coordinate system it becomes an extremely complicated affair to define all those points of progress where, say, &#8220;n&#8221; equals the number of persons in the room minus one!</p>
<p>The go to statement as it stands is just too primitive, it is too much an invitation to make a mess of one&#8217;s program. One can regard and appreciate the clauses considered as bridling its use. I do not claim that the clauses mentioned are exhaustive in the sense that they will satisfy all needs; but whatever clauses are suggested (e.g. abortion clauses) they should satisfy the requirement that a programmer independent coordinate system can be maintained to describe the process in a helpful and manageable way.</p>
<p>It is hard to end this article with a fair acknowledgement: am I to judge by whom my thinking has been influenced? It is fairly obvious that I am not uninfluenced by Peter Landin and Christopher Strachey, and that I do not regret their influence upon me. Finally I should like to record (as I remember it quite distinctly) how Heinz Zemanek at the pre-ALGOL meeting in early 1959 in Copenhagen quite explicitly expressed his doubts whether the go to statement should be treated on equal syntactic footing with the assignment statement. To a modest extent I blame myself for not having then drawn the consequences of his remark.</p>
<p>The remark about the undesirability of the go to statement is far from new. I remember having read the explicit recommendation to restrict the use of the go to statement to alarm exits, but I have not been able to trace it; presumably, it has been made by C. A. R. Hoare. In [1, Sec. 3.2.1] Wirth and Hoare together make a remark in the same direction in motivating the case construction: &#8220;Like the conditional, it mirrors the dynamic structure of a program more  clearly than go to statements and switches, and it eliminates the  need for introducing a large number of labels in the program.&#8221;</p>
<p>In [2] Guiseppe Jacopini seems to have proved the (logical) superfluousness of the <b>go to</b> statement. The exercise to translate an arbitrary flow diagram more or less mechanically into a jump-less one, however, is not to be recommended. Then the resulting flow diagram cannot be expected to be more transparent than the original one.</p>
<p>References:</p>
<p>1. Wirth, Niklaus, and Hoare C. A. R.<br />
A contribution to the development of ALGOL.<br />
Comm. ACM 9 (June 1966), 413-432.</p>
<p>2. Böhm, Corrado, and Jacopini Guiseppe.<br />
Flow diagrams, Turing machines and languages with only two formation rules.<br />
Comm. ACM 9 (May 1966), 366-371.</p>
<p>by Edsger W.Dijkstra<br />
Technological University<br />
Eindhoven, The Netherlands</p></blockquote>
<img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/jaksa.wordpress.com/3/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/jaksa.wordpress.com/3/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/jaksa.wordpress.com/3/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/jaksa.wordpress.com/3/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/jaksa.wordpress.com/3/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/jaksa.wordpress.com/3/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/jaksa.wordpress.com/3/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/jaksa.wordpress.com/3/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/jaksa.wordpress.com/3/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/jaksa.wordpress.com/3/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/jaksa.wordpress.com/3/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/jaksa.wordpress.com/3/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=jaksa.wordpress.com&blog=2662408&post=3&subd=jaksa&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://jaksa.wordpress.com/2008/01/29/a-case-against-the-goto-statement/feed/</wfw:commentRss>
		</item>
	</channel>
</rss>