<?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:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Xebia Blog &#187; Peter Veentjer</title>
	<atom:link href="http://blog.xebia.com/author/pveentjer/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.xebia.com</link>
	<description>Software development done right!</description>
	<lastBuildDate>Wed, 01 Feb 2012 00:30:00 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>EJCP: #9 Stopping threads</title>
		<link>http://blog.xebia.com/2008/02/12/ejcp-9-stopping-threads/</link>
		<comments>http://blog.xebia.com/2008/02/12/ejcp-9-stopping-threads/#comments</comments>
		<pubDate>Tue, 12 Feb 2008 11:56:55 +0000</pubDate>
		<dc:creator>Peter Veentjer</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Concurrency Control]]></category>

	<!-- AutoMeta Start -->
	<category>jump</category>
	<category>victim</category>
	<category>stop</category>
	<category>stopping</category>
	<category>volatile</category>
	<category>loop</category>
	<category>lock</category>
	<category>reordering</category>
	<!-- AutoMeta End -->
	
		<guid isPermaLink="false">http://blog.xebia.com/2008/02/12/ejcp-9-stopping-threads/</guid>
		<description><![CDATA[Continuing the Enterprise Java Concurrency Problem Top 10 countdown, it&#8217;s time to talk about number 9 &#8216;Stopping threads&#8217;. Stopping a Thread is complicated. In the beginning the Thread.stop() method was added for this purpose, but is has been deprecated for a long time. The reason is when some thread calls stop() on a victim thread, [...]]]></description>
			<content:encoded><![CDATA[<p>
Continuing the <a href="http://blog.xebia.com/2008/01/22/ejcp-top-10-nested-monitor-lockout/">Enterprise Java Concurrency Problem Top 10 countdown</a>, it&#8217;s time to talk about number 9 &#8216;Stopping threads&#8217;.
</p>
<p>
Stopping a Thread is complicated. In the beginning the <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Thread.html#stop()">Thread.stop()<a> method was added for this purpose, but is has been<br />
<a href="http://java.sun.com/j2se/1.5.0/docs/guide/misc/threadPrimitiveDeprecation.html">deprecated</a> for a long time. The reason is when some thread calls stop() on a victim thread, a <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/ThreadDeath.html">ThreadDeath</a> error is thrown inside the victim thread. And while this error propagates up the stacktrace, all locks the victim thread owns, are released. This means that the victim-thread could leave objects (on which it held locks) in an inconsistent state. So stopping a thread should be a cooperative mechanism between threads: the victim thread and the initiating thread both need to agree upon a protocol being used.
</p>
<p><span id="more-403"></span></p>
<p>
Luckily I don&#8217;t see the usage of Thread.stop() (or even worse, the <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Thread.html#destroy()">Thread.destroy()</a>) often, but the idiom displayed in the example below, is something I do see regularly. Although the exception handling is sometimes <a href="http://pveentjer.wordpress.com/2008/01/31/runnables-and-logging-exceptions/">forgotten</a>. This Task is executed by some thread, and when a different thread wants to stop this Task, it calls the stop method on the Task and the stop variable is set to true. As soon as the victim thread starts the next iteration of the loop, it reads the stop variable, ends the loop and returns from the run method (returning from the run method eventually terminates the victim thread).
</p>
<pre>
public class Task implements Runnable{
	private boolean stop = false;

	public void stop(){
		stop = true;
	}

	public void run(){
		while(!stop){
			try{
				runSingleUnit();
			}catch(Exception ex){
				//log it, in most cases we
				//don't want to break the loop
			}
		}
	}

	public void runSingleUnit()throws Exception{
		System.out.println("executing some service");
	}
}
</pre>
<p>
The problem is that this example is faulty. There are 2 reasons and they are both linked to the Java Memory Model (JMM) that after a long period is completely defined in Java 5 and higher (see the <a href="http://jcp.org/aboutJava/communityprocess/review/jsr133/index.html">JSR 133</a> for more information):
</p>
<ol>
<li>visibility</li>
<li>reorderings</li>
</ol>
<h3>Visibility</h3>
<p>
Because the read and write of the stop variable are not special (so not volatile, not final, and not done inside a synchronized context) the JVM doesn&#8217;t provide any guarantee that the most recently written value is read (there are more ways to provide visibility guarantees but they are out of scope for this post). This means that the victim thread could see the initial written value till end of time. And this effectively transforms the loop to an infinitive one.
</p>
<p>
You might wonder why a thread is not able to see the most recently written value, because this most surely be some kind of error. Well&#8230; it isn&#8217;t because this desired behaviour, called sequential consistency, prevents a lot of optimizations from being used. There are different forms of local memory (multi level caches, cpu registers) where value&#8217;s can be stored instead of the main memory. This can result in the following scenario&#8217;s:</p>
<ol>
<li>
local memory doesn&#8217;t need to contain the most recently written value by another thread. So<br />
a thread that uses this local memory, doesn&#8217;t need to see writes made by other threads.
</li>
<li>
local memory contain the most recently written value made by the current thread without being visible in main memory, so a write doesn&#8217;t have to be visible to other reading threads.
</li>
</ol>
<p>
The chance of this happening with the strong cache coherence most cpu&#8217;s provide (realized by snooping and sniffing caches for example) isn&#8217;t that big, but it certainly is possible. And concurrency problems have the tendency to appear only once in a while and therefore are very hard to reproduce (they could also be hardware dependent).
</p>
<p>
Reasoning about caches, invalidation, memory fences and the like can complicate the platform independent view Java developers have. Therefore the JMM is defined in terms of happens before rules where each rule defines a relation between 2 actions (read/write/volatile-read/volatile-write/lock-acquire/lock-release), and this should shield us from reasoning about these low level issues. If a happens before relation between 2 actions (in this cases the normal write and normal read) can be found, all changes made in first action (the write) are visible in second action (the read). In this case there is no such relation, so no guarantee can be given about the write of the stop variable in the stop method (executed by the initiating thread) ever being visible at the read of the stop variable in the run method (executed by the victim thread).
</p>
<h3>Reorderings</h3>
<p>
The compiler could decide to hoist the read of the stop variable out of the loop, a performance increasing technique called <a href="http://jeremymanson.blogspot.com/2007/03/loop-invariant-code-motion-and-java.html">&#8216;Loop invariant code motion&#8217;</a></p>
<pre>
public void run(){
	if(stop)
		return;

	while(true){
		try{
			runSingleUnit();
		}catch(Exception ex){
			//log it
		}
	}
}
</pre>
<p>
This optimization is possible because inside the loop the stop value is not changed, so why do an expensive memory access every time. As you can imagine, the new run method never ends as soon as it passes the if(stop) check. This reordering is allowed because from the victim thread point of view, the transformed code is equivalent to the original one, so the within-thread as-if-serial semantics of the transformed code is the same as the original. </p>
<p/>
<h3>Solution</h3>
<p>
The simplest way to solve these problems is to make the stop variable volatile. Volatile variables prevent:
</p>
<ol>
<li>
 <b>visibility problems:</b> there is a happens before relation (called volatile variable rule) between the write to a volatile variable and the subsequent read of the same variable, so a read will always see the most recently written value.
</li>
<li>
<b>reordering problems:</b> the instructions prior to the volatile read of the stop variable, <a href="http://www.ibm.com/developerworks/library/j-jtp03304/#2.0">are not allowed to be moved over this read</a>. This prevents the movement (reordering) of the check outside the loop.
</li>
</ol>
<p>
But using a read and write under a lock (<a href="http://pveentjer.wordpress.com/2008/02/11/jmm-cache-invalidation-vs-happens-before-rules/">should be the same lock</a>) should also fix the problem:
</p>
<pre>
public synchronized void stop(){
	stop = true;
}

private synchronized boolean isStopped(){
	return stop;
}

public void run(){
	while(!isStopped()){
		...
	}
}
</pre>
<p>
The reason why the synchronized approach works:
</p>
<ol>
<li><b>visibility</b>: there is a happens before relation between the write of stop and the read of stop (called monitor lock rule) that makes sure that all changes made before releasing the lock in the stop method, are visible when the lock is acquired in the isStopped() method.
</li>
<li>
<b>reordering</b> the movement of instructions prior to the lock acquire is not allowed to jump over the release of the lock. This principle is called the <a href="http://jeremymanson.blogspot.com/2007/05/roach-motels-and-java-memory-model.html">&#8216;Roach Motel&#8217;</a>: instructions in front of the lock acquire are not allowed to jump over the lock release, but are allowed to jump over the lock.acquire. The same principle can be applied to instruction after the lock release: they are not allowed to jump over the lock acquire, but they are allowed to jump over the lock.release. Instruction that are between the lock acquire and the lock release are not permitted to jump over the lock.release or lock.acquire (a cockroach doesn&#8217;t want to leave his dark shelter).
</li>
</ol>
<p>
This stopping technique is quite useful if the execution of a single iteration doesn&#8217;t take too much time. If it takes a longer time, different techniques need to be considered like thread interruption. For more information about stopping threads I recommend chapter 7 &#8220;Cancelling and Shutdown&#8221; from <a href="http://www.amazon.com/Java-Concurrency-Practice-Brian-Goetz/dp/0321349601">&#8216;Java Concurrency in Practice&#8217;</a>. For more information about the JMM I recommend chapter 16 &#8220;The Java Memory Model&#8221; from the same book or check out the the <a href="http://www.cs.umd.edu/~pugh/java/memoryModel/">JMM website</a>.</p>
<div name="googleone_share_1" style="position:relative;z-index:5;float: right; margin-left: 10px;"><g:plusone size="small" count="1" href="http://blog.xebia.com/2008/02/12/ejcp-9-stopping-threads/"></g:plusone></div><p><a class="a2a_dd a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fblog.xebia.com%2F2008%2F02%2F12%2Fejcp-9-stopping-threads%2F&amp;title=EJCP%3A%20%239%20Stopping%20threads" id="wpa2a_2"><img src="http://blog.xebia.com/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://blog.xebia.com/2008/02/12/ejcp-9-stopping-threads/feed/</wfw:commentRss>
		<slash:comments>14</slash:comments>
		</item>
		<item>
		<title>EJCP Top 10: Nested monitor lockout</title>
		<link>http://blog.xebia.com/2008/01/22/ejcp-top-10-nested-monitor-lockout/</link>
		<comments>http://blog.xebia.com/2008/01/22/ejcp-top-10-nested-monitor-lockout/#comments</comments>
		<pubDate>Tue, 22 Jan 2008 16:38:49 +0000</pubDate>
		<dc:creator>Peter Veentjer</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Concurrency Control]]></category>

	<!-- AutoMeta Start -->
	<category>fridge</category>
	<category>kitchen</category>
	<category>beer</category>
	<category>door</category>
	<category>monitor</category>
	<category>itemlist</category>
	<category>structures</category>
	<category>deadlock</category>
	<!-- AutoMeta End -->
	
		<guid isPermaLink="false">http://blog.xebia.com/2008/01/22/ejcp-top-10-nested-monitor-lockout/</guid>
		<description><![CDATA[Concurrent programming is going to be even more important with the introduction of the multi-core cpu&#8217;s. Running the complete application on a single cpu&#8217;s (single threaded) is going to lead to less effective usage of hardware. Luckily in most cases, applications are inherently concurrent (like a standard request/response web-application) so a developer doesn&#8217;t need to [...]]]></description>
			<content:encoded><![CDATA[<p>
Concurrent programming is going to be even more important with the introduction of the multi-core cpu&#8217;s. Running the complete application on a single cpu&#8217;s (single threaded) is going to lead to less effective usage of hardware. Luckily in most cases, applications are inherently concurrent (like a standard request/response web-application) so a developer doesn&#8217;t need to deal often with explicit concurrency control. But it doesn&#8217;t mean that even such simple applications are free of concurrency problems. In this Enterprise Java Concurrency Problems (EJCP) Top 10, I&#8217;m going to list my 10 most important issues I look at, when I need to find concurrency problems within Enterprise Java applications.<span id="more-394"></span></p>
<p><p>
So, without further ado, let&#8217;s start at the bottom: number 10.
</p>
<h2>Nested Monitor Lockout</h2>
<p>
It is very easy to cause liveness problems with conditions (aka condition variables) but it is not just the direct usage that can cause problems, also techniques like object composition can be quite dangerous.
</p>
<p>
A condition is a very low level synchronization structure that makes it possible for threads to wait for an event to occur, e.g. the return of a license in a semaphore or the placement of an item on a queue. So a lot of higher order concurrency structures are build on top of conditions and this makes them one of the most fundamental concurrency abstractions. The big question is: how can the usage of a condition cause a deadlock? When a thread is going to wait for a notification, it blocks, it is added to a wait-set (a set of blocking threads that wait for that condition) and the associated lock is released. Releasing and reacquiring the lock is done behind the screens and luckily is not a task developers need to deal with. But if the waiting thread never receives the notification it is waiting for, the thread won&#8217;t wake-up and therefore is in a deadlock.
</p>
<p>
Imagine there is a fridge with room for beer. If someone wants to grab a beer from the fridge, he opens the door (other people are not able to access the fridge while it is opened) and checks if one is available. If there is, he takes it, closes the door and returns. If there isn&#8217;t, he closes the door and waits next to the fridge. When the delivery guy wants to put something in the fridge, he opens the door, places the item, shouts that a new item has been put and closes the door. The guy that is waiting heard the delivery guy, he opens the door, sees that a beer is available, takes it and closes the door.
</p>
<pre>
class Fridge{
	final Object monitor = new Object();
	final List&lt;Beer&gt; itemList = new LinkedList&lt;Beer&gt;();

	void put(Beer beer){
		synchronized(monitor){
			itemList.add(beer);
			monitor.notify();
		}
	}

	Beer take()throws InterruptedException{
		synchronized(monitor){
			while(itemList.isEmpty())
				monitor.wait();
			return itemList.remove(0);
		}
	}
}
</pre>
<p>
The Fridge class is an implementation of the example. It uses a Java monitor, a combination of a condition (wait-set) and its corresponding (intrinsic) lock:
</p>
<ol>
<li>the lock is used to synchronize between threads (providing exclusive access)</li>
<li>the condition is used to communicate between threads (the waiting and shouting part)</li>
</ol>
<p>
Lets enhance our example and place the fridge in a very small kitchen; a kitchen with room for just a single person. We can prevent multiple people from accessing the small room by adding a door to the kitchen.
</p>
<pre>
class Kitchen{
	final Object monitor = new Object();
	final Fridge fridge = new Fridge();

	void put(Beer beer){
		synchronized(monitor){
			fridge().put(beer);
		}
	}

	Beer take()throws InterruptedException{
		synchronized(monitor){
			return fridge.take();
		}
	}
}
</pre>
<p>
In this Kitchen class, the kitchen-door is implemented by a monitor (only the lock is used b.t.w.). When someone wants to access the fridge he sees that the kitchen-door is open and enters the kitchen, he closes the kitchen-door (he acquires the lock of the kitchen-monitor), he opens the fridge-door (he acquires the lock of the fridge-monitor) and looks inside. When he realizes that the fridge is empty, he waits in the kitchen. When this happens, the lock on the fridge-door is released, but because he stays in the kitchen the kitchen-door remains closed (locked). The consequence is that everybody who want to access the kitchen is going to deadlock:
</p>
<ol>
<li>someone that wants to take something from the fridge or wants to refill the fridge is going to deadlock because he can&#8217;t enter the kitchen (the kitchen-door is closed) and keeps waiting.</li>
<li>
the person that is waiting in the kitchen, is going to deadlock because nobody is able to refill the fridge because he has locked out everybody from the kitchen.
</li>
</ol>
<p>
This problem is called: &#8216;nested monitor lockout&#8217;. Composing larger structures (e.g. kitchens) from smaller structures (e.g. fridges) is a technique all object oriented developers use on a daily basis (dependency injection, object composition, decorators, template methods, proxies, strategies, etc). But as soon as these structures block and are wrapped within other concurrent structures, you can get in serious liveness problems. So one of the first things I look at is if synchronized structures are wrapped in other synchronized structures and possible do blocking calls (if you are lucky, the methods throw an InterruptedException). But this can be a very challenging task if the concurrent code isn&#8217;t localized but scattered all over the place or when the InterruptedExceptions aren&#8217;t handled correctly. Maybe in the future techniques like STM (Software Transactional Memory) can help us, but for the moment we need to keep paying extra attention to concurrency control.
</p>
<p>
For more information about this subject I recommend <a href="http://www.amazon.com/Concurrent-Programming-Java-TM-Principles/dp/0201310090">&#8220;Concurrent Programming in Java: Design Principles and Pattern (2nd Edition)&#8221;</a> from Doug Lea, Chapter 3.3.4 &#8220;Confinement and nested monitors&#8221;.</p>
<div name="googleone_share_1" style="position:relative;z-index:5;float: right; margin-left: 10px;"><g:plusone size="small" count="1" href="http://blog.xebia.com/2008/01/22/ejcp-top-10-nested-monitor-lockout/"></g:plusone></div><p><a class="a2a_dd a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fblog.xebia.com%2F2008%2F01%2F22%2Fejcp-top-10-nested-monitor-lockout%2F&amp;title=EJCP%20Top%2010%3A%20Nested%20monitor%20lockout" id="wpa2a_4"><img src="http://blog.xebia.com/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://blog.xebia.com/2008/01/22/ejcp-top-10-nested-monitor-lockout/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Oracle and ORA-08177</title>
		<link>http://blog.xebia.com/2007/11/28/oracle-and-ora-08177/</link>
		<comments>http://blog.xebia.com/2007/11/28/oracle-and-ora-08177/#comments</comments>
		<pubDate>Wed, 28 Nov 2007 10:26:38 +0000</pubDate>
		<dc:creator>Peter Veentjer</dc:creator>
				<category><![CDATA[General]]></category>
		<category><![CDATA[Concurrency Control]]></category>
		<category><![CDATA[Oracle]]></category>

	<!-- AutoMeta Start -->
	<category>serializable</category>
	<category>transaction</category>
	<category>transaction</category>
	<category>exclusive</category>
	<category>08177</category>
	<category>updates</category>
	<category>lock</category>
	<category>pessimistic</category>
	<!-- AutoMeta End -->
	
		<guid isPermaLink="false">http://blog.xebia.com/2007/11/28/oracle-and-ora-08177/</guid>
		<description><![CDATA[When using Oracle, or other MVCC (Multi Version Concurrency Control) databases like Postgresql or MySql in combination with InnoDb, a transaction with the SERIALIZABLE isolation level doesn&#8217;t always block (a pessimistic approach) when it conflicts with another transaction. Instead a more optimistic approach is used. This approach however can lead to an abort of the [...]]]></description>
			<content:encoded><![CDATA[<p>When using Oracle, or other MVCC (Multi Version Concurrency Control) databases like Postgresql or MySql in combination with InnoDb, a transaction with the SERIALIZABLE isolation level doesn&#8217;t always block (a pessimistic approach) when it conflicts with another transaction. Instead a more optimistic approach is used. This approach however can lead to an abort of the transaction with the feared: &#8220;ORA-08177: can&#8217;t serialize access for this transaction&#8221;, which in essence is just an optimistic locking failure.<span id="more-333"></span></p>
<p>A SERIALIZABLE transaction in classic lock based databases, is implemented by using pessimistic locking. The transaction needs to obtain the exclusive table lock prior to accessing the table. This prevents other SERIALIZABLE transactions and non SERIALIZABLE transactions (these need to obtain the shared table lock) from executing concurrently. The consequence is that a SERIALIZABLE transaction blocks until the exclusive table lock is obtained, or when it is rolled back (eg a timeout, detection of a deadlock, etc).</p>
<p>In Oracle no exclusive table lock is required to implement the SERIALIZABLE isolation level. Instead Oracle is able to take a snapshot of the database and use this snapshot for the duration of the transaction (transaction level read consistency). This is realized by reading the SCN (the System Change Number: a version number that is increased when a transaction commits) when the transaction begins and using this SCN and the data in the rollback segment, to reconstruct previous versions of records. The consequence of this approach is that different transactions could see different snapshots at the same moment (hence Multi Version Concurrency Control). Therefor a SERIALIZABLE transaction is not able to see other updates (so no worries about unrepeatable reads) but also not other inserts/deletes (so no phantom reads).</p>
<p>In short: instead of relying on pessimistic locks to prevent isolation problems, the transaction is able to see the state of the database as it was when the transaction began, even though other transactions could have changed the database in the meanwhile! This is one of the reasons why Oracle is able to perform well under heavy load.</p>
<p>There is one caveat: most transactions do more than just reading (else the READ_ONLY isolation level would have been a better solution). When a transaction modifies (inserts, updates, deletes) records, these records are exclusively locked for the remaining duration of the transaction (these changes are visible inside the transaction of course), independent of the isolation level. But once a transaction ends, these locks are released and without extra protection, it could happen that a SERIALIZABLE transaction updates an older version of the record (a reconstructed one) than the last committed version. This problem is called a lost update.</p>
<p>Luckily Oracle protects us from lost updates with SERIALIZABLE transactions by adding an optimistic lock: when the transaction tries to update a record that has been committed after the transaction began, it knows that a different transaction has modified it and the transaction aborts with the &#8220;ORA-08177: can&#8217;t serialize access for this transaction&#8221;. Just like optimistic locking failures in normal database communication, the standard policy of dealing with this situation is to retry the transaction and hope that the transaction isn&#8217;t interfered again.</p>
<div name="googleone_share_1" style="position:relative;z-index:5;float: right; margin-left: 10px;"><g:plusone size="small" count="1" href="http://blog.xebia.com/2007/11/28/oracle-and-ora-08177/"></g:plusone></div><p><a class="a2a_dd a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fblog.xebia.com%2F2007%2F11%2F28%2Foracle-and-ora-08177%2F&amp;title=Oracle%20and%20ORA-08177" id="wpa2a_6"><img src="http://blog.xebia.com/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://blog.xebia.com/2007/11/28/oracle-and-ora-08177/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Service layer woes</title>
		<link>http://blog.xebia.com/2007/07/18/service-layer-woes/</link>
		<comments>http://blog.xebia.com/2007/07/18/service-layer-woes/#comments</comments>
		<pubDate>Wed, 18 Jul 2007 18:01:52 +0000</pubDate>
		<dc:creator>Peter Veentjer</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Spring]]></category>

	<!-- AutoMeta Start -->
	<category>employee</category>
	<category>employeeservice</category>
	<category>employeedao</category>
	<category>givebonus</category>
	<category>bonus</category>
	<category>findbyid</category>
	<category>employeeid</category>
	<category>saveorupdate</category>
	<!-- AutoMeta End -->
	
		<guid isPermaLink="false">http://blog.xebia.com/2007/07/18/service-layer-woes/</guid>
		<description><![CDATA[Service layers are one of the most important parts of an enterprise system in my opinion, for a lot of reasons: defines what your system can and can&#8217;t do a good location for transaction demarcation a good location for security And although a lot has been written about the service layer (Patterns of Enterprise Applications [...]]]></description>
			<content:encoded><![CDATA[<p>Service layers are one of the most important parts of an enterprise system in my opinion, for a lot of reasons:</p>
<ol>
<li>defines what your system can and can&#8217;t do</li>
<li>a good location for transaction demarcation</li>
<li>a good location for security</li>
</ol>
<p>And although a lot has been written about the service layer (<a href="http://www.amazon.com/Patterns-Enterprise-Application-Architecture-Martin">Patterns of Enterprise Applications</a> from <a href="http://martinfowler.com">Martin Fowler</a> is one of the most famous books about this subject), there are a lot of ways to implement it. In this post I&#8217;ll walk through a few examples that are improved step by step.<br />
<span id="more-267"></span><br />
An example of some bad code I have seen too often:</p>
<pre class="brush: plain; title: ; notranslate">
class BonusController{
	EmployeeDao employeeDao;
	EmployeeService employeeService;

	void someAction(Request request){
		long id = new Long(request.get(&quot;id&quot;));
		Employee employee = employeeDao.findById(id);
		employee.setSalary(employee.getSalary()+100);
		employeeService.saveOrUpdate(employee);
	}
}
</pre>
<p>There is a lot wrong with this code. The most important issues are:</p>
<ol>
<li>the bonus logic is hard to reuse because it is integrated inside the controller, so duplication is not uncommon in such systems.
	</li>
<li>
	it is hard to maintain/extend because the bonus logic is overshadowed by all the plumbing.
	</li>
<li>it is very easy to bypass any form of validation because the database is exposed by the saveOrUpdate method. If the employeeService is used inside a remoting layer, and you have &#8216;deserialized&#8217; an employee, god knows what kind of properties are placed in the database when it is saved.
	</li>
</ol>
<p>A better, but still bad solution, is the following:</p>
<pre class="brush: plain; title: ; notranslate">
class BonusController{
	EmployeeDao employeeDao;
	EmployeeService employeeService;

	void someAction(Request request){
		long id = new Long(request.get(&quot;id&quot;));
		Employee employee = employeeDao.findById(id);
		employeeService.giveBonus(employee);
	}
}

class EmployeeService{
	EmployeeDao employeeDao;

	void giveBonus(Employee employee){
		...execute logic for bonus
		employeeDao.saveOrUpdate(employee);
	}
}
</pre>
<p>The horrific saveOrUpdate method has been removed and the bonus logic has been moved inside the service. But we are not out of the woods yet:</p>
<ol>
<li>
	I&#8217;m still able to inject an employee that bypasses all checks
</li>
<li>
	Transactional behavior is vague at best and erroneous at worst. If multiple transactions are working on the same employee, and if there is no form of offline locking, then one transaction is able to overwrite the changes of the other: this problem is called the lost update problem. The consequence of a lost update is that we could loose a bonus! Beside the lost update there are other problems: Imagine what happens when one transaction has deleted the employee and the second one commits. If all logic is executed inside a single transaction, you can make use of standard solutions to prevent these problems (optimistic/pessimistic-locks, isolation levels etc).
</li>
</ol>
<p>Another issue I find smelly, is that no explicit transaction is used to access the employeeDao inside the controller. Most databases are friendly enough to create a transaction if one is missing, and in the previous example it is quite clear that an employeeDao is used inside a controller, but I have seen my share of deeply tucked away dao&#8217;s inside presentationlayer support objects like Spring editors. I think this is a good example of misuse of technology.</p>
<p>The simplest solution to the problems above is the following:</p>
<pre class="brush: plain; title: ; notranslate">
class BonusController{
	void someAction(Request request){
		long id = new Long(request.get(&quot;id&quot;));
		employeeService.giveBonus(id);
	}
}

class EmployeeService{
	void giveBonus(long employeeId){
		Employee employee = employeeDao.findById(employeeId);
		....bonus logic
	}
}
</pre>
<p>All previous mentioned problems are solved, and even the controller has been simplified. This approach even is agnostic to the technique you use to realize the bonus logic. You could create a <a href="http://www.martinfowler.com/eaaCatalog/transactionScript.html">transaction script</a>:</p>
<pre class="brush: plain; title: ; notranslate">
class EmployeeService{
	void giveBonus(long employeeId){
		Employee employee = employeeDao.findById(employeeId);
		employee.setSalary(employee.getSalary()+100);
	}
}
</pre>
<p>You could place it inside the domain object of you have a richer domain model (something I&#8217;m for).</p>
<pre class="brush: plain; title: ; notranslate">
class EmployeeService{
	EmployeeDao employeeDao;

	void giveBonus(long employeeId){
		Employee employee = employeeDao.findById(employeeId);
		employee.giveBonus();
	}
}
</pre>
<p>And if your bonus logic is very complex, you could even decide to use a domain service (see <a href="http://www.amazon.com/Domain-Driven-Design-Tackling-Complexity-Software/dp/0321125215">Domain Driven Design</a> from <a href="http://domainlanguage.com/about/ericevans.html">Eric Evans</a>, chapter 5, subject: Services for more information) that contains the actual logic:</p>
<pre class="brush: plain; title: ; notranslate">
class EmployeeService{
	EmployeeDao employeeDao;
	BonusDomainService bonusDomainService;

	void giveBonus(long employeeId){
		Employee employee = employeeDao.findById(employeeId);
		bonusDomainService.giveBonus(employee);
	}
}
</pre>
<p>For those that have watched carefully, the EmployeeService provides another very important function: it provides a layer of abstraction. The outside world is not coupled to the implementation, and this means that changes in the implementation won&#8217;t effect the clients (presentationlayer, remoting layers). </p>
<div name="googleone_share_1" style="position:relative;z-index:5;float: right; margin-left: 10px;"><g:plusone size="small" count="1" href="http://blog.xebia.com/2007/07/18/service-layer-woes/"></g:plusone></div><p><a class="a2a_dd a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fblog.xebia.com%2F2007%2F07%2F18%2Fservice-layer-woes%2F&amp;title=Service%20layer%20woes" id="wpa2a_8"><img src="http://blog.xebia.com/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://blog.xebia.com/2007/07/18/service-layer-woes/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Spring and visibility problems</title>
		<link>http://blog.xebia.com/2007/03/01/spring-and-visibility-problems/</link>
		<comments>http://blog.xebia.com/2007/03/01/spring-and-visibility-problems/#comments</comments>
		<pubDate>Thu, 01 Mar 2007 12:08:51 +0000</pubDate>
		<dc:creator>Peter Veentjer</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Concurrency Control]]></category>
		<category><![CDATA[Spring]]></category>

	<!-- AutoMeta Start -->
	<category>employeedao</category>
	<!-- AutoMeta End -->
	
		<guid isPermaLink="false">http://blog.xebia.com/2007/03/01/spring-and-visibility-problems/</guid>
		<description><![CDATA[Spring is a great framework, but I expect that some Spring based applications are subject to visibility problems (a type of concurrency problem). This blog entry describes the cause and effects of this problem, and also how it can be solved. Visibility problems Most programmers don&#8217;t have much experience with multi threading and have a [...]]]></description>
			<content:encoded><![CDATA[<p>Spring is a great framework, but I expect that some Spring based applications are subject to visibility problems (a type of concurrency problem). This blog entry describes the cause and effects of this problem, and also how it can be solved.</p>
<h3>Visibility problems</h3>
<p>Most programmers don&#8217;t have much experience with multi threading and have a very simplistic view on reality: if a thread makes a change to a variable, this change is directly visible to all other threads that access the same variable. This view is called <a href="http://en.wikipedia.org/wiki/Sequential_consistency">sequential consistency</a>, but the problem is that no virtual machine automatically provides this view.</p>
<p><span id="more-168"></span></p>
<p>The reason for this apparently faulty behavior is performance. Most variables are not shared between threads, so no special instructions (memory barriers) have to be added to make the program sequentially consistent. If these instructions were automatically added to all variable accesses, it would greatly reduce performance because a lot of optimizations would be excluded from being used. To name a few:</p>
<ol>
<li>
        usage of super fast local-memory (like caches and cpu-registers). It also could reduce the performance benefits of multi-core systems because the increased access to main memory would become the bottleneck.
    </li>
<li>
        reordering of instructions to increase the chance of a cache hit.
    </li>
</ol>
<p>The consequence of a visibility problem, is that a value written to a variable by one thread, doesn&#8217;t have to be visible in other threads (maybe never). This could lead to an easy to detect NullPointerException, but it can also lead to much harder to detect problems like shown in the following example:</p>
<pre>
public class SomeRunnable implements Runnable{
    private boolean stop = false;

    public void stop(){
        stop = true;
    }

    public void run(){
        while(!stop){
                System.out.println("hello");
        }
    }
}
</pre>
<p>There are a few reasons why this runnable could fail to stop:</p>
<ol>
<li>
                stop is not safely published: the thread that executed the run method, doesn&#8217;t need to see a change in the stop value. A possible scenario would be: thread1 (the thread that executed run) is running on cpu1 (with cache1). Thread2 (the thread that calls stop) is running on cpu2 (with cache2). When thread1 runs, it needs the value of stop, sees the initial false value and places it in his cache. When thread2 executes stop, stop is set to true. But it might happen that this value remains in cache2 for an undetermined time and isn&#8217;t flushed to main memory, so thread1 never sees the new value when it happens to read from main memory. Even if the value is flushed to main memory, thread1 could still be reading the stale value from cache1.
        </li>
<li>
                because the access to the stop variable isn&#8217;t safely published, and the value doesn&#8217;t change in the loop, the &#8216;compiler&#8217; (JIT, cpu etc) could decide to replace the variable read by the constant &#8216;true&#8217; in that loop.
        </li>
</ol>
<p>Visibility problems can lead to hard to detect errors and unpredictable behavior, and you definitely want to keep them out of your system. And although most cpu&#8217;s are not subject to visibility problems (because of  strong <a href="http://en.wikipedia.org/wiki/Memory_coherence">Memory Coherence</a>), betting on this behavior is asking for problems (the application also wouldn&#8217;t be platform independent).</p>
<h3>Spring applications and visibility problems</h3>
<p>I expect that a lot of Spring applications are subject to visibility problems. If you look at singleton beans for example (dao&#8217;s, controllers, managers etc), these beans often are shared by many threads, to name a few:</p>
<ul>
<li>threads from the servlet container</li>
<li>threads from remoting middleware</li>
<li>threads from jmx</li>
<li>threads from triggers or other internal threads</li>
</ul>
<p>Take a look at the following example:</p>
<pre>
public class EmployeeManagerImpl implements EmployeeManager{

    private EmployeeDao employeeDao;

    public setEmployeeDao(EmployeeDao employeeDao){
        this.employeeDao = employeeDao;
    }

    public void fire(long employeeId){
        Employee employee = employeeDao.load(employeeId);
        employee.fire();
    }
}
</pre>
<p>And the bean configuration that belongs to it:</p>
<pre>
    &lt;bean id=&quot;employeeManager&quot; class=&quot;EmployeeManagerImpl&quot;&gt;
        &lt;property name=&quot;employeeDao&quot; ref=&quot;employeeDao&quot;/&gt;
    &lt;/bean&gt;
</pre>
<p>The visibility problem here, is that employeeDao, set by the thread that constructed the employeeManager, isn&#8217;t safely published and doesn&#8217;t have to be visible in other threads. If one of those threads calls the fire method on the EmployeeManagerImpl, it could lead to a NullPointerException because that thread still sees a null value for the employeeDao.</p>
<p>The problem can be solved in a few ways:</p>
<ol>
<li>
        make employeeDao volatile. Although it sounds quite strange, because the employeeDao is not going to change after it has been set, volatile variables are always safely published. Personally I don&#8217;t like this solution much because it is misleading (the value is never going to change after the object has been constructed) and it also reduces performance (the variable always has to be read from main memory instead of local memory).
    </li>
<li>
        make employeeDao final, because final variables also are safely published. The problem with final variables is that they only can be set by constructor based Dependency Injection (DI) and Spring promotes setter based DI. Personally I prefer constructor based DI, because it is a lot easier to guarantee class invariants. Although those setters only are visible in an implementing class, and not in the interface, I still don&#8217;t feel happy about because it also makes classes harder to understand. But constructor based DI isn&#8217;t perfect either; I guess most of us have struggled with large constructors.
    </li>
</ol>
<h3>Problem not that bad?</h3>
<p>Before going into detail why the problems maybe are not that bad, I need to explain the new Memory Model found in Java 5 and higher (<a href="http://jcp.org/aboutJava/communityprocess/review/jsr133/index.html">JSR-133</a>) (see footnote). The model describes under what kinds of conditions a variable will be visible in other threads and it also shields you from reasoning about caches (they are not mentioned in the Java Memory Model).</p>
<p/>
The model is expressed in terms of actions:</p>
<ol>
<li>
                read/writes to normal/volatile/final variables
        </li>
<li>
                lock acquire/release
        </li>
<li>
                thread start/join
        </li>
</ol>
<p/>
The model also contains a set of happens-before rules between actions. If a happens-before rule applies between action1 and action2, then all changes made by action1 are visible in action2. Examples of happens-before rules are:</p>
<ol>
<li>
                <b>Program Order rule:</b> each action in a thread happens-before every action in that thread that comes later in the program order. It is important to realize that normal variable reads/writes, can be reordered as long as they keep the &#8216;within-thread as-if-serial semantics&#8217;: the reordering should not be visible inside the thread.
        </li>
<li>
                <b>Volatile variable rule:</b> a write to a volatile variable happens-before every subsequent read of that same variable (that is why making the employeeDao volatile works).
        </li>
<li>
                <b>Monitor lock rule:</b> an unlock on a monitor lock happens-before every subsequent lock on that same monitor lock. (The same goes for the the new <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/locks/Lock.html">Lock</a> found in Java 5.
        </li>
<li>
                <b>Transitivity rule:</b> if action1 happens-before action2, and action2 happens-before action3, then action1 happens-before action3.
        </li>
</ol>
<p>If there is a happens before relation between the write and the read of a variable, then it is safely published.</p>
<h3>Safe handoff</h3>
<p>These happens-before rules can be used to check if there is a happens-before relation between two actions. Take a look at the following example:</p>
<pre>
int a=0;
volatile boolean b=0;

void initialize(){
        a=console.readInteger();
        b=console.readBoolean();
}

void print(){
        print(b);
        print(a);
}
</pre>
<p>A possible ordering of actions could be:</p>
<table border="1">
<tr>
<td>action</td>
<td>thread 1</td>
<td>thread 2</td>
</tr>
<tr>
<td>action1</td>
<td>normalwrite(a)</td>
<td></td>
</tr>
<tr>
<td>action2</td>
<td>volatilewrite(b)</td>
<td></td>
</tr>
<tr>
<td>action3</td>
<td></td>
<td>volatileread(b)</td>
</tr>
<tr>
<td>action4</td>
<td></td>
<td>normalread(a)</td>
</tr>
</table>
<p>Because action1 happens-before action2 (program order) and because action2 happens-before action3 (volatile variable rule) and because action3 happens before action4 (program order), action1 happens before action4 (remember that the happens before rules are transitive). This means that the change in action1, is visible in action4. This technique is called &#8216;safe handoff&#8217; (aka &#8216;piggybacking on synchronization&#8217;).<br />
Safe handoff uses the safe publication of a variable X (in this case b), to safely publish all unsafely-published-variables that are changed before X (in this case a).</p>
<h4>Safe handoff in Spring</h4>
<p>The Spring applicationcontext also provides safe handoff (only in Java 5 and higher): after a singleton bean is created, it is placed in a singletonmap. When it is needed, it is retrieved from that map. But instead of using the &#8216;volatile variable&#8217; rule, it uses the &#8216;monitor lock&#8217; rule (action4 and action5)</p>
<p>The following table shows a very simplified ordering of actions (variable mapentry.ref is the variable &#8216;X&#8217; from the &#8216;save handoff&#8217; technique):</p>
<table border="1">
<tr>
<td>action</td>
<td>thread 1</td>
<td>thread 2</td>
</tr>
<tr>
<td>action1</td>
<td>lock(singletonmap)</td>
<td></td>
</tr>
<tr>
<td></td>
<td><i>construction of the employeeManager</i></td>
<td></td>
</tr>
<tr>
<td>action2</td>
<td>normalwrite(employeeDao)</td>
<td></td>
</tr>
<tr>
<td></td>
<td><i>employeeManager is placed in the applicationcontext</i></td>
<td></td>
</tr>
<tr>
<td>action3</td>
<td>normalwrite(mapentry.ref)</td>
<td></td>
</tr>
<tr>
<td>action4</td>
<td>unlock(singletonmap)</td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td><i>employeeManager is read from the applicationcontext</i></td>
</tr>
<tr>
<td>action5</td>
<td></td>
<td>lock(singletonmap)</td>
</tr>
<tr>
<td>action6</td>
<td></td>
<td>normalread(mapentry.ref)</td>
</tr>
<tr>
<td>action7</td>
<td></td>
<td>unlock(singletonmap)</td>
</tr>
<tr>
<td></td>
<td></td>
<td><i>employeeManager fire method is called</i></td>
</tr>
<tr>
<td>action8</td>
<td></td>
<td>normalread(employeeDao)</td>
</tr>
</table>
<p>This means that there is a happens before relation between action2 and action8, so the value set in the employeeDao (action2), is visible when it is read by another thread (action8). That is why standard Spring singletons don&#8217;t have visibility problems. If you want to see it for yourself, check out the <a href="http://www.springframework.org/docs/api/org/springframework/beans/factory/support/DefaultSingletonBeanRegistry.html">DefaultSingletonBeanRegistry</a> and the &#8216;public Object getSingleton(String beanName, ObjectFactory singletonFactory)&#8217; method</p>
<h3>Conclusion</h3>
<p>I&#8217;m glad that standard singleton beans aren&#8217;t subject to visibility problems (under Java 5 and higher), but I don&#8217;t think it is the correct way to deal with concurrency control in Spring (or in general):</p>
<ol>
<li>
                objects can&#8217;t be safely used in a different environment. So your objects are tied to the (current version of the) Spring framework to make them work correct.
        </li>
<li>
                the save handoff behavior is not guaranteed by Spring, and it only works under Java 5 and higher. The behavior is undefined in older JVM&#8217;s.
        </li>
<li>
                are beans with different scopes than singletons free from visibility problems?
        </li>
</ol>
<p>I don&#8217;t want to depict Spring as a bad product: it really is amazing and I&#8217;m always happy when I can use it on a project. But I do think that developers should be more careful when writing code that is used in a multi threaded environment.</p>
<p/>
A part of this responsibility should be taken bij developers themselves, if you write threadsafe code, you need to know what you are doing. But I also think the guys behind Spring should take part of this responsibility: not all developers have a lot of experience with writing multi-threaded code and I guess most don&#8217;t know anything about the Java Memory Model. If these issues are not mentioned in the Spring documentation, a lot of developers will remain agnostic and this is going to lead to problems in the future.</p>
<p/>
Footnote:<br />
If you want a more in depth explanation of the new Java Memory Model, I suggest <a href="http://www.amazon.com/Java-Concurrency-Practice-Brian-Goetz/dp/0321349601">&#8216;Java Concurrency in Practice&#8217;</a> from Brian Goetz, Tim Peierls, Joshua Bloch, Joseph Bowbeer, David Holmes and Doug Lea, or check out the following website <a href="http://www.cs.umd.edu/~pugh/java/memoryModel">The Java Memory Model</a></p>
<p/>
I want to thank colleagues, acquaintances and the guys from the concurrency mailing list for proofreading this post.</p>
<p/>
<p/>
<div name="googleone_share_1" style="position:relative;z-index:5;float: right; margin-left: 10px;"><g:plusone size="small" count="1" href="http://blog.xebia.com/2007/03/01/spring-and-visibility-problems/"></g:plusone></div><p><a class="a2a_dd a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fblog.xebia.com%2F2007%2F03%2F01%2Fspring-and-visibility-problems%2F&amp;title=Spring%20and%20visibility%20problems" id="wpa2a_10"><img src="http://blog.xebia.com/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://blog.xebia.com/2007/03/01/spring-and-visibility-problems/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
	</channel>
</rss>
<!-- This Quick Cache file was built for (  blog.xebia.com/author/pveentjer/feed/ ) in 0.65941 seconds, on Feb 9th, 2012 at 4:32 pm UTC. -->
<!-- This Quick Cache file will automatically expire ( and be re-built automatically ) on Feb 9th, 2012 at 5:32 pm UTC -->
