<?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>Jayway Team Blog &#187; concurrency</title>
	<atom:link href="http://blog.jayway.com/tag/concurrency/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.jayway.com</link>
	<description>Sharing Experience</description>
	<lastBuildDate>Sat, 28 Jan 2012 15:53:55 +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>Invoke any Method on any Thread</title>
		<link>http://blog.jayway.com/2011/08/08/invoke-any-method-on-any-thread/</link>
		<comments>http://blog.jayway.com/2011/08/08/invoke-any-method-on-any-thread/#comments</comments>
		<pubDate>Mon, 08 Aug 2011 08:03:16 +0000</pubDate>
		<dc:creator>Fredrik Olsson</dc:creator>
				<category><![CDATA[Architecture]]></category>
		<category><![CDATA[Cocoa]]></category>
		<category><![CDATA[Dynamic languages]]></category>
		<category><![CDATA[Tips & Tricks]]></category>
		<category><![CDATA[concurrency]]></category>
		<category><![CDATA[design patterns]]></category>
		<category><![CDATA[iphone]]></category>
		<category><![CDATA[mac]]></category>
		<category><![CDATA[objective-c]]></category>
		<category><![CDATA[open source]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[tips]]></category>
		<category><![CDATA[tutorial]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=9143</guid>
		<description><![CDATA[I previously wrote a blog post titled Performing any Selector on the Main Thread detailing a convenience category on NSInvoication for easily creating invocation objects that could be invoked on any thread. This category has served me well, and even got traction in the iOS developer community, so I never bothered to stop and think [...]]]></description>
			<content:encoded><![CDATA[<p>I previously wrote a blog post titled <a href="http://blog.jayway.com/2010/03/30/performing-any-selector-on-the-main-thread/">Performing any Selector on the Main Thread</a> detailing a convenience category on <code>NSInvoication</code> for easily creating invocation objects that could be invoked on any thread.</p>
<p>This category has served me well, and even got traction in the <a href="http://iphonedevelopment.blogspot.com/2010/08/nsoperation-file-template-notes.html">iOS developer community</a>, so I never bothered to stop and think if there exist an even better solution.</p>
<p>Especially now that GDC exists, and doing an inline block to invoke on the main thread or a background queue is easier than ever before.</p>
<h3>Until Today</h3>
<p>Traveling home by bus as usual I got a flash of genius; <i>Why not use proxy objects?</i> Calling a method on the main thread should be no harder then this;</p>
<pre class="brush:objc">[[self.slider mainThreadProxy] setValue:0.5f animated:YES];</pre>
<p>The old <code>NSInvocation</code> solutions have a few drawbacks. First of all there is no code completion for the arguments, secondly there is not even basic type checking, and lastly the implementation is quite ABI specific.</p>
<p>The <code>NSObject</code> class already has support for method forwarding, and wrapping method calls up into <code>NSInvocation</code> instances. Why not use seriously battle proven code that Apple provides.</p>
<h3>The Skeleton</h3>
<p>The implementation for <code>-[NSObject mainThreadProxy]</code> will be childishly simple:</p>
<pre class="brush:objc">-(id)mainThreadProxy;
{
    // Return self directly if already on main thread.
    if ([NSThread isMainThread]) {
        return self;
    } else {
        return [CWMainProxy proxyWithTarget:self];
    }
}</pre>
<p>The <code>CWMainProxy</code> class is a simple private helper, that will perform all of the heavy lifting. The interface and life time code is very small:</p>
<pre class="brush:objc">@interface CWMainProxy : NSObject {
    id _target;
}
+(id)proxyWithTarget:(id)target;
@end

@implementation CWMainProxy

+(id)proxyWithTarget:(id)target;
{
    CWMainProxy* proxy = [[[self alloc] init] autorelease];
    proxy->_target = [target retain];
    return proxy;
}

-(void)dealloc;
{
    [_target release];
    [super dealloc];
}
@end
</pre>
<h3>The Meaty Parts</h3>
<p>Now comes the tricky parts; actually act like a proxy. The proxy is a simple <code>NSObject</code> subclass, first it needs to be able to fake to any caller that it can respond to everything that the proxies target responds to.</p>
<pre class="brush:objc">-(BOOL)respondsToSelector:(SEL)sel;
{
    return [super respondsToSelector:sel] ||
           [_target respondsToSelector:sel];
}</pre>
<p>Next up if the object claims it responds to a selector but do not have an actual implementation, then we must provide a <code>NSMethodSignature</code> so the run-time can create a proper <code>NSInvocation</code> for us.</p>
<pre class="brush:objc">-(NSMethodSignature*)methodSignatureForSelector:(SEL)sel;
{
    if ([_target respondsToSelector:self) {
        return [_target methodSignatureForSelector:sel];
    } else {
        return [super methodSignatureForSelector:sel];
    }
}</pre>
<p>And finally we need to actually forward the <code>NSInvocation</code> call to the main thread, as per the callers request:</p>
<pre class="brush:objc">-(void)forwardInvocation:(NSInvocation*)invocation;
{
    [invocation performSelectorOnMainThread:@selector(invokeWithTarget:)
                                 withObject:_target
                              waitUntilDone:YES];
}</pre>
<h3>Conclusions</h3>
<p>Given some thought I regard this solution to be much more elegant than my old solution. And it even yields less and more readable code than using GCD on iOS 4 and later:</p>
<pre class="brush:objc">[[self.slider mainThreadProxy] setValue:0.5f animated:YES];
    // vs
dispatch_async(dispatch_get_main_queue(),
               ^{
                   [self.slider setValue:0.5f animated:YES];
               });</pre>
<ul>
<li>The implementation is much smaller, and relies on the Foundation framework functionality, not my own Objective-C ABI hacks.</li>
<li>It is less code to write to use the functionality.</li>
<li>Xcode can do proper code completion and basic type checking.</li>
<li>It is compatible all the way back to iPhone OS 2, or Mac OS X 10.0, <a href="http://www.cocoanetics.com/2011/08/ios-versions-in-the-wild/">if you should care</a>.
 </ul>
<p>The <a href="https://github.com/Jayway/CWFoundation">CWFoundation project on Github</a> has a more complete implementation. With more support for optional blocking, delays, and more proxies not only for the main thread but also for background threads and operations queue.</p>
<p>You are seldom alone with great ideas, so a nod to <a href="http://twitter.com/#!/nevyn">Joachim Bengtsson</a> who has written about an <a href="http://overooped.com/post/913725384/nsinvocation">invocation grabber</a> before.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2011/08/08/invoke-any-method-on-any-thread/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Sync-Async Pair Pattern &#8211; Easy concurrency on iOS</title>
		<link>http://blog.jayway.com/2011/04/28/sync-asyn-pair-pattern-easy-concurrency-on-ios/</link>
		<comments>http://blog.jayway.com/2011/04/28/sync-asyn-pair-pattern-easy-concurrency-on-ios/#comments</comments>
		<pubDate>Thu, 28 Apr 2011 09:10:19 +0000</pubDate>
		<dc:creator>Fredrik Olsson</dc:creator>
				<category><![CDATA[Architecture]]></category>
		<category><![CDATA[Cocoa]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[Tips & Tricks]]></category>
		<category><![CDATA[automated testing]]></category>
		<category><![CDATA[concurrency]]></category>
		<category><![CDATA[design patterns]]></category>
		<category><![CDATA[iphone]]></category>
		<category><![CDATA[objective-c]]></category>
		<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=8208</guid>
		<description><![CDATA[Apple provides many tools for implementing concurrency in your application. NSOperationQueue, GCD, or simply using performSelectorInBackground:withObject: that is available on each and every object, are just some examples. The tools are there, yet implementing good concurrency is hard. The solution I have found is not yet another tool, or framework, but a simple pattern. I [...]]]></description>
			<content:encoded><![CDATA[<p>Apple provides many tools for implementing concurrency in your application. <code>NSOperationQueue</code>, GCD, or simply using <code>performSelectorInBackground:withObject:</code> that is available on each and every object, are just some examples. The tools are there, yet implementing good concurrency is hard.</p>
<p>The solution I have found is not yet another tool, or framework, but a simple pattern. I have not found an existing name for the pattern so I call it Sync-Async Pair. The idea is to hide the complexity of asynchronous calls and call-back behind a facade, and have a straightforward synchronous implementation. An implementation that is easy to write, test and extend.</p>
<h3>Sync-Async Pair Pattern</h3>
<p>As the name suggests the pattern consist of a method pair, one is synchronous, and the other is asynchronous. The asynchronous method is backed by the synchronous implementation, and is only responsible for erecting a simplified facade in front of the sometimes complex concurrent implementation. </p>
<p>The first priority is to expose a clean API, the second priority is an implementation that is simple, testable and maintainable. Turns out that beginning with a clean API design (how to use the code), steers you towards a clean implementation (how to write the code). Most developers do the mistake to first write the code, and then struggle to try to use their own code.</p>
<p>Sync-Asyn Pair begins by defining a public API that then steers towards a clean implementation. Let's assume we are implementing some kind of a book reader. We need two model objects; <code>CWBook</code> and <code>CWChapter</code>. Both books and chapters are fetched from the network, so we need concurrency in order to not block the UI thread.</p>
<p>For this example let's focus only on fetching the chapters associated with a book. All other operations would be implemented in a similar fashion. First we need a public API, two methods for the sync-async pair on <code>CWBook</code>, and a delegate protocol.</p>
<pre class="brush:objc">@protocol CWBookFetchChaptersDelegate &lt;NSObject&gt;
-(void)bookDidFetchChapters:(CWBook*)book;
-(void)book:(CWBook*)book failedFetchChaptersWithError:(NSError*)error;
@end
// ...
-(BOOL)fetchChaptersWithError:(NSError**)error;
-(void)fetchChaptersWithAsyncDelegate:(id&lt;CWBookFetchChaptersDelegate&gt;)delegate;
</pre>
<p>The synchronous method <code>fetchChaptersWithError:</code> is very straightforward to implement.</p>
<pre class="brush:objc">-(BOOL)fetchChaptersWithError:(NSError**)error;
{
    NSURL* url = [self URLForFetchingChapters];
    NSData* data = [NSData dataWithContentsOfURL:url
                                         options:0
                                           error:error];
    if (data) {
        return [self parseChaptersFromData:data
                                     error:error];
    }
    return NO;
}</pre>
<p>How to construct the <code>NSURL</code>, or possibly <code>NSURLRequest</code> is not important. Nor is it important how you actually parse the resulting data sent from the server, that is totally left to our problem domain. Just make it synchronous and super easy to write automatic unit checks for!</p>
<h3>Adding Concurrency</h3>
<p>Now to the hard part, that is actually quite manageable; adding the concurrency. For this example I will use <code>performSelectorInBackground:withObject:</code>. Your specific implementation might need <code>NSOperationQueue</code>, or GCD if you have special needs such as queues or cancelable operations. The idea will remain the same.</p>
<p>The most basic, and common, implementation for the public async method simply fires off the concurrent operation:</p>
<pre class="brush:objc">-(void)fetchChaptersWithAsyncDelegate:(id&lt;CWBookFetchChaptersDelegate&gt;)delegate;
{
    [self performSelectorInBackground:@selector(fetchChaptersWithDelegate:)
                           withObject:delegate];
}</pre>
<p>In most cases all it does is request a private method to be performed on a background thread at some point in time. This is also the perfect place to abort operations early, for example a no-op if a request such as fetching a thumbnail is already in progress.</p>
<p>The private method previously launched is where most of the work is done. This is where a <code>NSAutoreleasePool</code> is setup, the synchronous method is called, and the delegate is properly called on the proper thread. The basic implementation for fetching books would be:</p>
<pre class="brush:objc">-(void)fetchChaptersWithDelegate:(id&lt;CWBookFetchChaptersDelegate&gt;)delegate;
{
    NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
    NSError* error = nil;
    BOOL success = [self fetchChaptersWithError:&error];
    if (success) {
        [[NSInvocation invocationWithTarget:delegate
                                   selector:@selector(bookDidFetchChapters:)
                            retainArguments:YES, self] invokeOnMainThreadWaitUntilDone:NO];
    } else {
        [[NSInvocation invocationWithTarget:delegate
                                   selector:@selector(book:failedFetchChaptersWithError:)
                            retainArguments:YES, self, error] invokeOnMainThreadWaitUntilDone:NO];
    }
    [pool release];
}</pre>
<p>For this example I am using my <code>NSInvocation</code> additions to perform the delegate callbacks to the main thread, but it could just as easily been done using GCD. The additions are described in detail and available for download in <a href="http://blog.jayway.com/2010/03/30/performing-any-selector-on-the-main-thread/">this blog post</a>, or from in the <a href="https://github.com/jayway/CWFoundation">CWFoundation repo on github</a>.</p>
<p>As you can see the boiler plate code for managing concurrency is actually very minimal, much less than 10 statements in total. The boilerplate code is almost reduced to only calling other methods, leaving very very few opportunities for bugs to sneak in.</p>
<h3>Core Data in the Mix</h3>
<p>The Sync-Async Pair pattern also lend itself beautifully for writing multi-threaded Core Data. The hassle of juggling <code>NSManagedObjectID</code> and <code>NSManagedObject</code> instances from different contexts can be completely left up to the private implementation that calls the synchronous method.</p>
<p>The private method responsible for calling the synchronous method and handling callbacks could be implemented as such:</p>
<pre class="brush:objc">-(void)notifyDelegate:(id)delegate ofSuccess:(BOOL)success withError:(NSError*)error;
{
    self = [[NSManagedObjectContext threadLocalContext] objectWithID:[self objectID]];
    if (success) {
        [delegate bookDidFetchChapters:self];
    } else {
        [delegate book:self failedFetchChaptersWithError:error];
    }
}

-(void)fetchChaptersWithDelegate:(id&lt;CWBookFetchChaptersDelegate&gt;)delegate;
{
    NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
    self = [[NSManagedObjectContext threadLocalContext] objectWithID:[self objectID]];
    NSError* error = nil;
    BOOL success = [self fetchChaptersWithError:&error];
    [[NSInvocation invocationWithTarget:self
                               selector:@selector(notifyDelegate:ofSuccess:withError:)
                        retainArguments:YES, delegate, success, error] invokeOnMainThreadWaitUntilDone:NO];
    [pool release];
}</pre>
<p>Not much extra code, and the ugliness of handling Core Data's managed contexts is neatly hidden for clients at a single point in the code, that is much easier to test, debug, and maintain than most conventional Core Data code.</p>
<h3>Conclusions</h3>
<p>The simple Sync-Async Pair pattern makes it easy to write robust concurrent code. It is even a pattern that by design yields an elegant public API. It is also very easy to test, extend and even change the internal implementation completely without affecting any clients.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2011/04/28/sync-asyn-pair-pattern-easy-concurrency-on-ios/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Future Cocoa Operation</title>
		<link>http://blog.jayway.com/2010/08/19/future-cocoa-operation/</link>
		<comments>http://blog.jayway.com/2010/08/19/future-cocoa-operation/#comments</comments>
		<pubDate>Thu, 19 Aug 2010 17:51:30 +0000</pubDate>
		<dc:creator>Fredrik Olsson</dc:creator>
				<category><![CDATA[Architecture]]></category>
		<category><![CDATA[Cocoa]]></category>
		<category><![CDATA[Tips & Tricks]]></category>
		<category><![CDATA[concurrency]]></category>
		<category><![CDATA[design patterns]]></category>
		<category><![CDATA[iphone]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[mobile]]></category>
		<category><![CDATA[network]]></category>
		<category><![CDATA[objective-c]]></category>
		<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=6051</guid>
		<description><![CDATA[In Java you have for quite some time had the Future interface for encapsulating an asynchronous calculation. Cocoa has had the abstract NSOperation class to encapsulate asynchronous operations. NSOperation do not have any facilities for returning a result when done as the Future do, you are left to implement this on your own. Which I [...]]]></description>
			<content:encoded><![CDATA[<p>In Java you have for quite some time had the <code><a href="http://download.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/Future.html">Future</a></code> interface for encapsulating an asynchronous calculation. Cocoa has had the abstract <code><a href="http://developer.apple.com/iphone/library/documentation/Cocoa/Reference/NSOperation_class/Reference/Reference.html">NSOperation</a></code> class to encapsulate asynchronous operations.</p>
<p><code>NSOperation</code> do not have any facilities for returning a result when done as the <code>Future</code> do, you are left to implement this on your own. Which I have done a few times, and as a rule of thumb, make the solution generic when needed for the third time.</p>
<p>Operations works perfectly for background network activities. One common network activity is search-as-you-type, in this case you need to also cancel the previous operation if it has not yet been completed, so lets built this behavior into the generic solution as well.</p>
<h3>API Design</h3>
<p>What we want is an subclass of <code>NSOperation</code> that provides a future result, lets call this class <code>CWFutureOperation</code>. It is abstract, so users are supposed to subclass and implement <code>main</code> method just as for <code>NSOperation</code>, only difference is that the main method implementation must call <code>setResult:</code> before exiting.</p>
<p>The result that is set in the main method implementation can then be fetched using the blocking method <code>result</code>, equivalent to <code>get()</code> from the Java <code>Future</code>. As an alternative we would also like to be handed the method upon completion via a target-action pair. If the target-action pair is only called for finished operations that are not cancelled, then we get the search-as-you-type behavior for free.</p>
<p>It is also nice to be able to wrap up any method returning an object in a future operation as a convenience, so lets add that as well to our class interface:</p>
<pre class="brush:objc">@interface CWFutureOperation : NSOperation {
@private
    id _result;
    BOOL _isResultSet;
    id _completionTarget;
    SEL _completionSelector;
}

-(id)result;
-(void)setCompletionTarget:(id)target selector:(SEL)selector;
-(void)setResult:(id)result;

+(CWFutureOperation*)operationWithTarget:(id)target
                                selector:(SEL)selector
                                  object:(id)object;

+(CWFutureOperation*)operationWithInvocation:(NSInvocation*)invocation;

@end</pre>
<h3>Implementation</h3>
<p>The client of the code must be able to fetch the result and the <code>CWFutureOperation</code> subclass must be able to set the result. The <code>result</code> method should block until the operation is finished if needed, and must properly return a result that can survive the operation that might be in a release pool. The implementation for this is straight forward, only minor complexity added in order to allow the result to be set multiple times:</p>
<pre class="brush:objc">-(id)result;
{
    if (![self isFinished]) {
        [self waitUntilFinished];
    }
    if ([self isCancelled]) {
        return nil;
    }
    return [[_result retain] autorelease];
}

-(void)setResult:(id)result;
{
    _isResultSet = YES;
    if (_result != result) {
        [_result autorelease];
        _result = [result retain];
    }
}</pre>
<p>The reason that we flag if the result has been set is because we want to throw an exception if the subclass implementation of the main method failes to set the result before exiting, we add this behavior by overriding the start method in <code>CWFutureOperation</code>.</p>
<p>The <code>start</code> method will also call the target-action pair upon completion if the operation has not been cancelled. The target selector is always called on the main thread, this is so that we safely can update any UI using the calculated result without adding even more threading code.</p>
<pre class="brush:objc">-(void)start;
{
    [super start];
    if (![self isCancelled]) {
        if (!_isResultSet) {
            [NSException raise:NSInternalInconsistencyException
                        format:@"%@ did not set result.", self];
        }
        [_completionTarget performSelectorOnMainThread:_completionSelector
                                            withObject:self
                                         waitUntilDone:NO];
    }
}</pre>
<h3>Conclusion</h3>
<p>The total amount of code is not mu<a href='http://blog.jayway.com/wordpress/wp-content/uploads/2010/08/Futures.zip'>Futures</a>ch, but this generic class adds a pattern to follow making design decisions for new application easy and consistent.</p>
<p>Solving the age old search-as-you-type problem can be as simple as this (Many assumptions, but you get the idea):</p>
<pre class="brush:objc">-(NSArray*)performSearchWithString:(NSString*)str;
{
    NSMutableArray* searchResults = nil;
    // Do actual search over the interwebz.
    return searchResults;
}

-(void)searchOperationDidComplete:(CWFutureOperation*)op;
{
    self.currentSearchOperation = nil;
    self.currentSearchResult = [op result];
    [self.searchDisplayController.searchResultsTableView reloadData];
}

-(BOOL)searchDisplayController:(UISearchDisplayController*)controller
  shouldReloadTableForSearchString:(NSString*)searchString;
{
	CWFutureOperation* op = [CWFutureOperation operationWithTarget:self
                                                          selector:@selector(performSearchWithString:) object:searchString];
    [op setCompletionTarget:self
                   selector:@selector(searchOperationDidComplete:)];
    [[NSOperationQueue defaultQueue]
    		replaceOperation:self.currentSearchOperation
               withOperation:op];
    self.currentSearchOperation = op;
    return NO;
}</pre>
<p>The full source code including unit tests, and some additional categories for making operation queue life easier, can be <a href="http://blog.jayway.com/wordpress/wp-content/uploads/2010/08/Futures.zip">downloaded here</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2010/08/19/future-cocoa-operation/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Awaitility &#8211; Java DSL for easy testing of asynchronous systems</title>
		<link>http://blog.jayway.com/2010/07/20/awaitility-java-dsl-for-easy-testing-of-asynchronous-systems/</link>
		<comments>http://blog.jayway.com/2010/07/20/awaitility-java-dsl-for-easy-testing-of-asynchronous-systems/#comments</comments>
		<pubDate>Tue, 20 Jul 2010 08:26:15 +0000</pubDate>
		<dc:creator>Johan Haleby</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[automated testing]]></category>
		<category><![CDATA[concurrency]]></category>
		<category><![CDATA[open source]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=5844</guid>
		<description><![CDATA[Introduction Testing asynchronous systems is hard. Not only does it require handling threads, timeouts and concurrency issues, but the intent of the test code can be obscured by all these details. Awaility is a DSL that allows you to express expectations of a asynchronous system in a concise and easy to read manner. Simple example [...]]]></description>
			<content:encoded><![CDATA[<h2>Introduction</h2>
<p>Testing asynchronous systems is hard. Not only does it require handling threads, timeouts and concurrency issues, but the intent of the test code can be obscured by all these details. Awaility is a DSL that allows you to express expectations of a asynchronous system in a concise and easy to read manner.</p>
<h2>Simple example</h2>
<p>So let's assume that we send an "add user" message to our asynchronous system like this:</p>
<pre class="java">&nbsp;
publish<span style="color: #66cc66;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> AddUserMessage<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;John Doe&quot;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;</pre>
<p>In your test case Awaitility can help you to easily verify that the database has been updated. In its simplest form it may look something like this:</p>
<pre class="java">&nbsp;
await<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">until</span><span style="color: #66cc66;">&#40;</span>newUserIsAdded<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;</pre>
<p>Awaitility will now block the test execution and wait until the new user is added to the database. <code>newUserIsAdded</code> is a method that you implement yourself in your test case. It specifies the condition that must be fulfilled in order for Awaitility to stop waiting.</p>
<pre class="java">&nbsp;
<span style="color: #000000; font-weight: bold;">private</span> Callable&lt;Boolean&gt; newUserIsAdded<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
	<span style="color: #000000; font-weight: bold;">return</span> <span style="color: #000000; font-weight: bold;">new</span> Callable&lt;Boolean&gt;<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
		<span style="color: #000000; font-weight: bold;">public</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3ABoolean+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Boolean</span></a> call<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #000000; font-weight: bold;">throws</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AException+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Exception</span></a> <span style="color: #66cc66;">&#123;</span>
			<span style="color: #000000; font-weight: bold;">return</span> userRepository.<span style="color: #006600;">size</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> == <span style="color: #cc66cc;">1</span>; <span style="color: #808080; font-style: italic;">// The condition that must be fulfilled</span>
		<span style="color: #66cc66;">&#125;</span>
	<span style="color: #66cc66;">&#125;</span>;
<span style="color: #66cc66;">&#125;</span>
&nbsp;</pre>
<p>By default Awaitility will wait for 10 seconds and if the size of the user respository is not equal to 1 during this time it'll throw a <code>TimeoutException</code> failing the test. If you want a different timeout you can define it like this:</p>
<pre class="java">&nbsp;
await<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">atMost</span><span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">5</span>, SECONDS<span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">until</span><span style="color: #66cc66;">&#40;</span>newUserWasAdded<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;</pre>
<h2>Better reuse</h2>
<p>Awaitility also supports splitting up the condition into a supplying and a matching part for better reuse. The example above can also be written as:</p>
<pre class="java">&nbsp;
await<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">until</span><span style="color: #66cc66;">&#40;</span> userRepositorySize<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>, equalTo<span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">1</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#41;</span>;
&nbsp;</pre>
<p>The <code>userRepositorySize</code> method is now a Callable of type Integer:</p>
<pre class="java">&nbsp;
<span style="color: #000000; font-weight: bold;">private</span> Callable&lt;Integer&gt; userRepositorySize<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
	<span style="color: #000000; font-weight: bold;">return</span> <span style="color: #000000; font-weight: bold;">new</span> Callable&lt;Integer&gt;<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
		<span style="color: #000000; font-weight: bold;">public</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AInteger+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Integer</span></a> call<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #000000; font-weight: bold;">throws</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AException+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Exception</span></a> <span style="color: #66cc66;">&#123;</span>
			<span style="color: #000000; font-weight: bold;">return</span> userRepository.<span style="color: #006600;">size</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>; <span style="color: #808080; font-style: italic;">// The condition supplier part</span>
		<span style="color: #66cc66;">&#125;</span>
	<span style="color: #66cc66;">&#125;</span>;
<span style="color: #66cc66;">&#125;</span>
&nbsp;</pre>
<p><code>equalTo</code> is a standard <a href="http://code.google.com/p/hamcrest/">Hamcrest</a> matcher specifiying the matching part of the condition for Awaitility.</p>
<p>Now we could reuse the <code>userRepositorySize</code> in a different test. E.g. let's say we have a test that adds three users at the same time:</p>
<pre class="java">&nbsp;
publish<span style="color: #66cc66;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> AddUserMessage<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;User 1&quot;</span><span style="color: #66cc66;">&#41;</span>, <span style="color: #000000; font-weight: bold;">new</span> AddUserMessage<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;User 2&quot;</span><span style="color: #66cc66;">&#41;</span>, <span style="color: #000000; font-weight: bold;">new</span> AddUserMessage<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;User 3&quot;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;</pre>
<p>We now reuse the <code>userRepositorySize</code> supplier and simply update the Hamcrest matcher:</p>
<pre class="java">&nbsp;
await<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">until</span><span style="color: #66cc66;">&#40;</span> userRepositorySize<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>, equalTo<span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">3</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#41;</span>;
&nbsp;</pre>
<h2>Reduce verboseness</h2>
<p>Since Java is so verbose Awaitility also provides a way achieve the same result by building up the supplier part without defining a Callable:</p>
<pre class="java">&nbsp;
await<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">untilCall</span><span style="color: #66cc66;">&#40;</span> to<span style="color: #66cc66;">&#40;</span>userRepository<span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">size</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>, equalTo<span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">3</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#41;</span>;
&nbsp;</pre>
<p><code>to</code> is method in Awaitility which you can use to define the suppling part inline in the await statement. Which option you like best depends on the use case and readability.</p>
<h2>More features</h2>
<p>Awaitility uses polling to check if a condition is fulfilled. You can easily specify a polling interval and poll delay (the delay before the first poll commits):</p>
<pre class="java">&nbsp;
with<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">pollInterval</span><span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">400</span>, MILLISECONDS<span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">and</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">pollDelay</span><span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">2</span>, SECONDS<span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">await</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">forever</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">until</span><span style="color: #66cc66;">&#40;</span>somethingHappens<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;</pre>
<p>In some cases it's also useful to create named awaits for example if you need multiple awaits in one test. A naive example:</p>
<pre class="java">&nbsp;
publish<span style="color: #66cc66;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> AddUserMessage<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;User 1&quot;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
await<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;user 1&quot;</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">until</span><span style="color: #66cc66;">&#40;</span>userRepositorySize<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>, is<span style="color: #66cc66;">&#40;</span>equalTo<span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">1</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
publish<span style="color: #66cc66;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> AddUserMessage<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;User 2&quot;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
await<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;user 2&quot;</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">until</span><span style="color: #66cc66;">&#40;</span>userRepositorySize<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>, is<span style="color: #66cc66;">&#40;</span>equalTo<span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">2</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;</pre>
<p>So if the first await statement fails the <code>TimeoutException</code> will indicate that it was the "user 1" statement that failed and so on.</p>
<h2>Conclusion</h2>
<p>We hope that you find Awaitility easy to use when you need to synchronize asynchronous behaviour in Java. However be aware that since it uses polling to verify that the condition is fulfilled it's not recommended to use it for precise performance testing. In these cases it could be better to use an AOP framework such as AspectJ and leverage on its compile-time weaving. </p>
<p>Please visit our <a href="http://code.google.com/p/awaitility/">homepage</a> for more info and downloads.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2010/07/20/awaitility-java-dsl-for-easy-testing-of-asynchronous-systems/feed/</wfw:commentRss>
		<slash:comments>11</slash:comments>
		</item>
		<item>
		<title>Performing any Selector on the Main Thread</title>
		<link>http://blog.jayway.com/2010/03/30/performing-any-selector-on-the-main-thread/</link>
		<comments>http://blog.jayway.com/2010/03/30/performing-any-selector-on-the-main-thread/#comments</comments>
		<pubDate>Tue, 30 Mar 2010 14:57:48 +0000</pubDate>
		<dc:creator>Fredrik Olsson</dc:creator>
				<category><![CDATA[Cocoa]]></category>
		<category><![CDATA[Embedded]]></category>
		<category><![CDATA[Tips & Tricks]]></category>
		<category><![CDATA[cocoa touch]]></category>
		<category><![CDATA[concurrency]]></category>
		<category><![CDATA[iphone]]></category>
		<category><![CDATA[mac]]></category>
		<category><![CDATA[mobile]]></category>
		<category><![CDATA[objective-c]]></category>
		<category><![CDATA[open source]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[tips]]></category>
		<category><![CDATA[tutorial]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=5209</guid>
		<description><![CDATA[Many UI frameworks, including AppKit for Mac OS X and UIKit for iPhone OS, require that all methods to UI components are sent on the main UI thread. Cocoa and Cocoa Touch make this quite easy by providing for example -[NSObject performSelectorOnMainThread:withObject:waitUntilDone:] in Foundation. Making updating the text for a text field a snap: [someTextField [...]]]></description>
			<content:encoded><![CDATA[<p>Many UI frameworks, including AppKit for Mac OS X and UIKit for iPhone OS, require that all methods to UI components are sent on the main UI thread. Cocoa and Cocoa Touch make this quite easy by providing for example <code>-[NSObject performSelectorOnMainThread:withObject:waitUntilDone:]</code> in Foundation. Making updating the text for a text field a snap:</p>
<pre class="brush:objc">[someTextField performSelectorOnMainThread:@selector(setText:)
                              	withObject:@"A new text"
                             waitUntilDone:YES];</pre>
<h3>But not everything is an object</h3>
<p>Since Objective-C is a superset of C, there are still all the types from C available. Such as all the primitives, including enums, and more complex struct types. Cocoa Touch is pragmatic and will use the most proper type for the use-case, not forcing everything into a square OOP hole.</p>
<p>This makes it quite hard to call for example <code>-[UIView setHidden:]</code>, that takes a single <code>BOOL</code> argument. Same for <code>-[UIView setFrame:]</code>, that takes a single <code>CGRect</code> struct argument, that in turn consists of one <code>CGPoint</code> and one <code>CGSize</code> struct.</p>
<p>Every type imaginable in C can be bundled in an <code>NSValue</code> instance. So we could bundle up the <code>BOOL</code> primitive, or the <code>CGRect</code> struct in a <code>NSValue</code> object. Then pass that object to the main thread, where it is unbundled and passed to the desired method. Quite cumbersome as it requires us to bundle, and unbundle types manually, and implement at least one extra method.</p>
<h3>There must be an easier way</h3>
<p>It turns out that <code>NSInvocation</code> can also handle any imaginable C type, or else it would not be able to invoke any imaginable Objective-C method. Making a <code>NSInvocation</code> invoke its method on the main thread is easy enough. Just add a category to the <code>NSInvocation</code> class, with a new method like this:</p>
<pre class="brush:objc">-(void)invokeOnMainThreadWaitUntilDone:(BOOL)wait;
{
  [self performSelectorOnMainThread:@selector(invoke)
                         withObject:nil
                      waitUntilDone:wait];
}</pre>
<p>So now all you need to do is to create a <code>NSInvocation</code> object, fill it in with the primitive or struct types, and invoke it on the main thread. But creating and setting up a <code>NSInvocation</code> object is also a bit on the boring side...</p>
<h3>There must be an even easier way!</h3>
<p>We could use variable argument lists from plain old C. Too bad that they are untyped?<br />
No despair, we know the target object for our invocation, and we know what method to call. So we have what we need to fetch the <code>NSMethodSignature</code> object for the call, that contains all the type information we need to safely process the <code>va_list</code>.</p>
<p>Our target machine is a Mac running 32- or 64-bit Intel CPU, or an iPhone OS device with a 32 bit ARM CPU. Turns out that on both platforms <code>va_list</code> is simply a <code>void*</code> pointer, to the stack frame. Even better <code>va_start()</code> will always flush any argument passed into the register on the stack frame. So we can skip most of the boring argument handling, by treating the arguments like a byte buffer, only advancing and aligning the buffer according to the information in the <code>NSMethodSignature</code> object.</p>
<p>A convenience method for creating a <code>NSInvocation</code> object for a particular target, selector, and list of variable arguments, would turn out like this:</p>
<pre class="brush:objc">+(NSInvocation*)invocationWithTarget:(id)target
                            selector:(SEL)aSelector
                     retainArguments:(BOOL)retainArguments, ...;
{
  va_list ap;
  va_start(ap, retainArguments);
  char* args = (char*)ap;
  NSMethodSignature* signature = [target methodSignatureForSelector:aSelector];
  NSInvocation* invocation = [NSInvocation invocationWithMethodSignature:signature];
  if (retainArguments) {
    [invocation retainArguments];
  }
  [invocation setTarget:target];
  [invocation setSelector:aSelector];
  for (int index = 2; index < [signature numberOfArguments]; index++) {
    const char *type = [signature getArgumentTypeAtIndex:index];
    NSUInteger size, align;
    NSGetSizeAndAlignment(type, &size, &align);
    NSUInteger mod = (NSUInteger)args % align;
    if (mod != 0) {
      args += (align - mod);
    }
    [invocation setArgument:args atIndex:index];
    args += size;
  }
  va_end(ap);
  return invocation;
}
</pre>
<h3>Conclusion</h3>
<p>And now we can easily call any method on the main UI thread. </p>
<p>An example where a <code>CGRect</code> struct is used to update the UI components frame;</p>
<pre class="brush:objc">// Set new frame of a label.
[[NSInvocation invocationWithTarget:someLabel
                           selector:@selector(setFrame:)
                    retainArguments:NO, CGRectMake(40, 40, 200, 100)]
 invokeOnMainThreadWaitUntilDone:NO];</pre>
<p>A slightly more complex example, where we send a primitive int, and also waits for and fetches the result from the main thread:</p>
<pre class="brush:objc">// Query a UITableView for the number of rows in section 2.
NSInvocation* i = [NSInvocation invocationWithTarget:tableView
                                            selector:@selector(numberOfRowsInSection:)
                                     retainArguments:NO, (NSUInteger)2];
// Block this thread until method has been invoked and result is available.
[i invokeOnMainThreadWaitUntilDone:YES];
NSInteger numberOfRows;
[i getReturnValue:&numberOfRows];</pre>
<p>Download full source code here: <a href='http://blog.jayway.com/wordpress/wp-content/uploads/2010/03/NSInvocation+CWVariableArguments.zip'>NSInvocation+CWVariableArguments.zip</a></p>
<p><em>Update: Example 2 was not 64-bit compatible as <a href="http://twitter.com/chmod007">David Remahl</a> pointed out to me. Added type cast to fix the error.</em></p>
<p><em>Update 2: A new version with some more features and small bug-fixes to BOOL, float and uint16_t types, plus proper unit tests can be downloaded here: <a href='http://blog.jayway.com/wordpress/wp-content/uploads/2010/03/CWFoundationAsyncAdditions.zip'>CWFoundationAsyncAdditions.zip</a></em></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2010/03/30/performing-any-selector-on-the-main-thread/feed/</wfw:commentRss>
		<slash:comments>20</slash:comments>
		</item>
		<item>
		<title>Queued Background Tasks for Cocoa</title>
		<link>http://blog.jayway.com/2009/05/09/queued-background-tasks-for-cocoa/</link>
		<comments>http://blog.jayway.com/2009/05/09/queued-background-tasks-for-cocoa/#comments</comments>
		<pubDate>Sat, 09 May 2009 12:42:04 +0000</pubDate>
		<dc:creator>Fredrik Olsson</dc:creator>
				<category><![CDATA[Architecture]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[concurrency]]></category>
		<category><![CDATA[design patterns]]></category>
		<category><![CDATA[frameworks]]></category>
		<category><![CDATA[iphone]]></category>
		<category><![CDATA[mac]]></category>
		<category><![CDATA[mobile]]></category>
		<category><![CDATA[network]]></category>
		<category><![CDATA[objective-c]]></category>
		<category><![CDATA[open source]]></category>
		<category><![CDATA[performance]]></category>
		<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=1665</guid>
		<description><![CDATA[The megahertz race is over, and instead we get more execution cores. This means that we as developers must make our applications parallel, in order to take advantage of the new performance. The easiest way to be parallel is to execute tasks in new threads, something that is useful also for lengthy but not resource [...]]]></description>
			<content:encoded><![CDATA[<p>The megahertz race is over, and instead we get more execution cores. This means that we as developers must make our applications parallel, in order to take advantage of the new performance. The easiest way to be parallel is to execute tasks in new threads, something that is useful also for lengthy but not resource intensive tasks such as network access.</p>
<p>Any sane developer avoids premature optimization, so the task we later want to execute in a separate thread is almost always available in our current context. I am sure all Java-developers has seen something like this:</p>
<pre class="java"> <span style="color: #000000; font-weight: bold;">new</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AThread+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Thread</span></a><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #993333;">void</span> run<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
        OuterClass.<span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006600;">someMethod</span><span style="color: #66cc66;">&#40;</span>arg<span style="color: #66cc66;">&#41;</span>;
    <span style="color: #66cc66;">&#125;</span>
<span style="color: #66cc66;">&#125;</span>.<span style="color: #006600;">start</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;</pre>
<p>And often an anonymous <code>Runnable</code> is involved as well. Executing a task in a separate thread with Cocoa and Cocoa Touch is ridiculously easy given the dynamic nature of Objective-C. This is done with Cocoa with this one-liner:</p>
<pre class="objc"><span style="color: #002200;">&#91;</span>self performSelectorInBackground:<span style="color: #0000ff;">@selector</span><span style="color: #002200;">&#40;</span>someMethod:<span style="color: #002200;">&#41;</span> withObject:arg<span style="color: #002200;">&#93;</span>;</pre>
<p>The <code>performSelectorInBackground:withObject:</code> is a companion method for <code>performSelector:withObject:</code>, and will create a new <code>NSThread</code> instance, and execute the specified method there. There are more companions such as <code>performSelectorOnMainThread:withObject:</code> that is used to execute a method on the main UI thread.</p>
<p>This easy access to executing in new threads often can result in code that spawns too many threads. In Cocoa on Mac OS X this is seldom a problem, not for Cocoa Touch applications under development when running in the iPhone simulator either. But on the more resource constrained iPhone and iPod Touch devices this will be a problem. Spawning a dozen background threads to download images will bring the iPhone OS to a staggering mess.</p>
<p><em><strong>Update: </strong>I have removed <code>CWSelectorOperation</code> from this post, since using <code>NSInvocationOperation</code> is preferred.</em></p>
<h3>Operation Queues</h3>
<p>The solution is to use a <code>NSOperationQueue</code>, that as the name implies handles a queue of operations. The max number of concurrent operations can be set, as well as dependencies and priority. The downside is that <code>NSOperationQueue</code> can only handle instances of <code>NSOperation</code>.</p>
<p><code>NSOperation</code> is an abstract class, where you as a developer override the <code>main</code> method to execute your task. In short <code>NSOperation</code> is programatically the equivalent of the Java <code>Runnable</code> interface. It is even worse as Objective-C do not support anonymous classes, so we will be required to actually implement our queued tasks as separate classes.</p>
<p>Not as neat as one would like, and definitely not even very Cocoa-like.</p>
<h3>What is Missing</h3>
<p>As a Cocoa developer I expect that executing a task on background queue, would be just as easy as executing a task on a background thread. The expected needed code is something like this:</p>
<pre class="objc"><span style="color: #002200;">&#91;</span>self performSelectorOnBackgroundQueue:<span style="color: #0000ff;">@selector</span><span style="color: #002200;">&#40;</span>someMethod:<span style="color: #002200;">&#41;</span> withObject:arg<span style="color: #002200;">&#93;</span>;</pre>
<p>To make this work we need:</p>
<ol>
<li>A category on <code>NSObject</code> to add <code>performSelectorOnBackgroundQueue:withObject:</code>.</li>
<li><del datetime="2009-05-13T10:47:35+00:00">Implement a concrete subclass of <code>NSOperation</code> to support execution of a selector on any target.</del>Use <code>NSInvocationOperation</code> to perform selector.</li>
<li>A category on <code>NSOperationQueue</code> to add a shared operation queue.</li>
</ol>
<p>This is in the order of how a client developer would see it (most developers will only care for the <code>NSObject</code> category). For us this is the reverse order when implement this functionality.</p>
<h3>A Shared Operation Queue</h3>
<p>Cocoa and Cocoa Touch used many shared instances, for example a shared <code>UIAccelerometer</code> instance, and a shared <code>NSURLCache</code> instance. So this pattern of single point dependency injection is common in Cocoa and works very well. So let us follow suit by introducing an interface like this:</p>
<pre class="objc"><span style="color: #0000ff;">@interface</span> NSOperationQueue <span style="color: #002200;">&#40;</span>CWSharedQueue<span style="color: #002200;">&#41;</span>
+<span style="color: #002200;">&#40;</span>NSOperationQueue*<span style="color: #002200;">&#41;</span>sharedOperationQueue;
+<span style="color: #002200;">&#40;</span><span style="color: #0000ff;">void</span><span style="color: #002200;">&#41;</span>setSharedOperationQueue:<span style="color: #002200;">&#40;</span>NSOperationQueue*<span style="color: #002200;">&#41;</span>operationQueue;
<span style="color: #0000ff;">@end</span></pre>
<p>The shared operation queue will be created lazily if it do not exist, and the client can easily swap it out at startup if needed. The implementation is very small, and a good example of how we should implement class variables with proper memory handling.</p>
<pre class="objc"><span style="color: #0000ff;">@implementation</span> NSOperationQueue <span style="color: #002200;">&#40;</span>CWSharedQueue<span style="color: #002200;">&#41;</span>
&nbsp;
<span style="color: #0000ff;">static</span> NSOperationQueue* cw_sharedOperationQueue = <span style="color: #0000ff;">nil</span>;
&nbsp;
+<span style="color: #002200;">&#40;</span>NSOperationQueue*<span style="color: #002200;">&#41;</span>sharedOperationQueue;
<span style="color: #002200;">&#123;</span>
  <span style="color: #0000ff;">if</span> <span style="color: #002200;">&#40;</span>cw_sharedOperationQueue == <span style="color: #0000ff;">nil</span><span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
    cw_sharedOperationQueue = <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>NSOperationQueue alloc<span style="color: #002200;">&#93;</span> init<span style="color: #002200;">&#93;</span>;
    <span style="color: #002200;">&#91;</span>cw_sharedOperationQueue setMaxConcurrentOperationCount:<span style="color: #0000dd;">3</span><span style="color: #002200;">&#93;</span>;
  <span style="color: #002200;">&#125;</span>
  <span style="color: #0000ff;">return</span> cw_sharedOperationQueue;
<span style="color: #002200;">&#125;</span>
&nbsp;
+<span style="color: #002200;">&#40;</span><span style="color: #0000ff;">void</span><span style="color: #002200;">&#41;</span>setSharedOperationQueue:<span style="color: #002200;">&#40;</span>NSOperationQueue*<span style="color: #002200;">&#41;</span>operationQueue;
<span style="color: #002200;">&#123;</span>
  <span style="color: #0000ff;">if</span> <span style="color: #002200;">&#40;</span>operationQueue != cw_sharedOperationQueue<span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
    <span style="color: #002200;">&#91;</span>cw_sharedOperationQueue release<span style="color: #002200;">&#93;</span>;
    cw_sharedOperationQueue = <span style="color: #002200;">&#91;</span>operationQueue retain<span style="color: #002200;">&#93;</span>;
  <span style="color: #002200;">&#125;</span>
<span style="color: #002200;">&#125;</span>
&nbsp;
<span style="color: #0000ff;">@end</span></pre>
<h3><del datetime="2009-05-13T10:47:35+00:00">Enter <code>CWSelectorOperation</code></del></h3>
<p><em><strong>Update: </strong><code>CWSelectorOperation</code> is no longer needed, our implementation instead uses <code>NSInvocationOperation</code>.</em></p>
<h3>Wrapping up <code>NSObject</code></h3>
<p>And at last we reach the category on <code>NSObject</code>, that is what we initially wanted, and what 95% of all use cases will be limited to.</p>
<pre class="objc"><span style="color: #0000ff;">@interface</span> <a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/ObjC_classic/Classes/NSObject.html"><span style="color: #0000ff;">NSObject</span></a> <span style="color: #002200;">&#40;</span>CWSharedQueue<span style="color: #002200;">&#41;</span>
&nbsp;
-<span style="color: #002200;">&#40;</span>NSInvocationOperation*<span style="color: #002200;">&#41;</span>performSelectorInBackgroundQueue:<span style="color: #002200;">&#40;</span><span style="color: #0000ff;">SEL</span><span style="color: #002200;">&#41;</span>aSelector
    withObject:<span style="color: #002200;">&#40;</span><span style="color: #0000ff;">id</span><span style="color: #002200;">&#41;</span>arg;
-<span style="color: #002200;">&#40;</span>NSInvocationOperation*<span style="color: #002200;">&#41;</span>performSelectorInBackgroundQueue:<span style="color: #002200;">&#40;</span><span style="color: #0000ff;">SEL</span><span style="color: #002200;">&#41;</span>aSelector
    withObject:<span style="color: #002200;">&#40;</span><span style="color: #0000ff;">id</span><span style="color: #002200;">&#41;</span>arg dependencies:<span style="color: #002200;">&#40;</span><a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/ObjC_classic/Classes/NSArray.html"><span style="color: #0000ff;">NSArray</span></a>*<span style="color: #002200;">&#41;</span>dependencies
    priority:<span style="color: #002200;">&#40;</span>NSOperationQueuePriority<span style="color: #002200;">&#41;</span>priority;
&nbsp;
<span style="color: #0000ff;">@end</span></pre>
<p>Most <code>performSelector*</code> methods do not have a return value, I have chosen to return the resulting <code> NSInvocationOperation </code> so that it can be used to setup dependencies for future queued operations. I have also added a second method <code>performSelectorInBackgroundQueue:withObject:dependencies:priority:</code> so that such dependencies can easily be setup, as well as prioritisation of operations.</p>
<p>The actual implementation is a simple wrapper around the <code> NSInvocationOperation </code> class, and category on <code>NSOperationQueue</code> that we implemented above:</p>
<pre class="objc"><span style="color: #0000ff;">@implementation</span> <a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/ObjC_classic/Classes/NSObject.html"><span style="color: #0000ff;">NSObject</span></a> <span style="color: #002200;">&#40;</span>CWSharedQueue<span style="color: #002200;">&#41;</span>
&nbsp;
-<span style="color: #002200;">&#40;</span>NSInvocationOperation*<span style="color: #002200;">&#41;</span>performSelectorInBackgroundQueue:<span style="color: #002200;">&#40;</span><span style="color: #0000ff;">SEL</span><span style="color: #002200;">&#41;</span>aSelector
    withObject:<span style="color: #002200;">&#40;</span><span style="color: #0000ff;">id</span><span style="color: #002200;">&#41;</span>arg;
<span style="color: #002200;">&#123;</span>
  NSInvocationOperation* operation = <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>NSInvocationOperation alloc<span style="color: #002200;">&#93;</span>
      initWithTarget:self selector:aSelector object:arg<span style="color: #002200;">&#93;</span>;
  <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>NSOperationQueue sharedOperationQueue<span style="color: #002200;">&#93;</span> addOperation:operation<span style="color: #002200;">&#93;</span>;
  <span style="color: #0000ff;">return</span> <span style="color: #002200;">&#91;</span>operation autorelease<span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#125;</span>
&nbsp;
-<span style="color: #002200;">&#40;</span>NSInvocationOperation*<span style="color: #002200;">&#41;</span>performSelectorInBackgroundQueue:<span style="color: #002200;">&#40;</span><span style="color: #0000ff;">SEL</span><span style="color: #002200;">&#41;</span>aSelector
    withObject:<span style="color: #002200;">&#40;</span><span style="color: #0000ff;">id</span><span style="color: #002200;">&#41;</span>arg dependencies:<span style="color: #002200;">&#40;</span><a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/ObjC_classic/Classes/NSArray.html"><span style="color: #0000ff;">NSArray</span></a>*<span style="color: #002200;">&#41;</span>dependencies
    priority:<span style="color: #002200;">&#40;</span>NSOperationQueuePriority<span style="color: #002200;">&#41;</span>priority;
<span style="color: #002200;">&#123;</span>
  NSInvocationOperation* operation = <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>NSInvocationOperation alloc<span style="color: #002200;">&#93;</span>
      initWithTarget:self selector:aSelector object:arg<span style="color: #002200;">&#93;</span>;
  <span style="color: #002200;">&#91;</span>operation setQueuePriority:priority<span style="color: #002200;">&#93;</span>;
  <span style="color: #0000ff;">for</span> <span style="color: #002200;">&#40;</span>NSOperation* dependency in dependencies<span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
    <span style="color: #002200;">&#91;</span>operation addDependency:dependency<span style="color: #002200;">&#93;</span>;
  <span style="color: #002200;">&#125;</span>
  <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>NSOperationQueue sharedOperationQueue<span style="color: #002200;">&#93;</span> addOperation:operation<span style="color: #002200;">&#93;</span>;
  <span style="color: #0000ff;">return</span> <span style="color: #002200;">&#91;</span>operation autorelease<span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#125;</span>
&nbsp;
<span style="color: #0000ff;">@end</span></pre>
<p>And that is it, if you want to avoid cut and paste of all this code to your own project just <a href='http://blog.jayway.com/wordpress/wp-content/uploads/2009/05/nsoperationqueuecwsharedqueue.zip'>download the source code here</a>. And happy concurrent hacking.</p>
<p>Download the <a href='http://blog.jayway.com/wordpress/wp-content/uploads/2009/05/cwselectoroperation.zip'>older source code here</a>, with a concrete subclass of <code>NSOperation</code> called <code>CWSelectorOperation</code>. </p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2009/05/09/queued-background-tasks-for-cocoa/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Devoxx highlights</title>
		<link>http://blog.jayway.com/2008/12/23/devoxx-highlights/</link>
		<comments>http://blog.jayway.com/2008/12/23/devoxx-highlights/#comments</comments>
		<pubDate>Tue, 23 Dec 2008 22:29:31 +0000</pubDate>
		<dc:creator>Jacob Mattsson</dc:creator>
				<category><![CDATA[Agile]]></category>
		<category><![CDATA[Events]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[bdd]]></category>
		<category><![CDATA[concurrency]]></category>
		<category><![CDATA[conference]]></category>
		<category><![CDATA[frameworks]]></category>
		<category><![CDATA[spring]]></category>
		<category><![CDATA[spring dm]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=699</guid>
		<description><![CDATA[In order to embrace the true Christmas spirit, I thought I'd share a few goodies from the Devoxx conference that took place in Antwerp, Belgium in mid December. Devoxx is the former JavaPolis that has changed name due to trademarking issues with Sun. Nonetheless, it's still the worlds largest independent Java conference, where the 3200 [...]]]></description>
			<content:encoded><![CDATA[<p>In order to embrace the true Christmas spirit, I thought I'd share a few goodies from the <a href="http://devoxx.com">Devoxx conference</a> that took place in Antwerp, Belgium in mid December. Devoxx is the former JavaPolis that has changed name due to trademarking issues with Sun. Nonetheless, it's still the worlds largest <em>independent</em> Java conference, where the 3200 attendees find themselves being literally showered with news from the broad Java community. Below follow summaries from some of the, IMHO, best sessions from this years conference. Enjoy!</p>
<h3>BDD in Java with easyb (John Ferguson Smart)</h3>
<p>John started out by arguing that TDD is not about testing, it's about writing better code. That is, it's about making your code more maintainable, flexible, reliable and simple. TDD is forces the programmer to think about how to test the class before actually writing the class. BDD, on the other hand, helps to determine what to test and to write more focused code, by starting with the behavior. Instead of thinking that you're testing your class, you should think that you're validating your requirements! </p>
<p>easyb is a BDD testing framework for Java, written in Groovy (hence providing full access to all Java API's). It ensures that tests become clearer and easier to both write and read!  It helps the developer to focus on the requirements only. A competitor to easyb is JBehave, which is an extension to JUnit. However, according to John, JBehave is more cumbersome than easyb.</p>
<p>easyb makes use of stories, much like the story cards in the Agile world. In a story, a narrative approach is used to describe a precise requirement. In easyb, a story could look like this:</p>
<pre class="groovy">&nbsp;
scenario â€œMake initial deposit onto a <a href="http://www.google.de/search?q=site%3Adocs.codehaus.org/%20new"><span style="color: #000000; font-weight: bold;">new</span></a> accountâ€, <span style="color: #66cc66;">&#123;</span>
	given â€œa <a href="http://www.google.de/search?q=site%3Adocs.codehaus.org/%20new"><span style="color: #000000; font-weight: bold;">new</span></a> accountâ€
	when â€œan initial deposit is madeâ€
	then â€œthe balance should be equal to the amount depositedâ€
<span style="color: #66cc66;">&#125;</span>
&nbsp;</pre>
<p>This scenario is quite clear and readable, isn't it!? Furthermore, it's self-documenting - a very appreciated feature =) And the syntax is so trivial that even a non-technical stakeholder would have no problem understanding it. The developer can then reuse the given scenario (pseudo) code and implement the test case, like this:</p>
<pre class="groovy">&nbsp;
<span style="color: #a1a100;">import com.mycompany.bankonline.domain.Account</span>
&nbsp;
scenario â€œMake initial deposit onto a <a href="http://www.google.de/search?q=site%3Adocs.codehaus.org/%20new"><span style="color: #000000; font-weight: bold;">new</span></a> accountâ€, <span style="color: #66cc66;">&#123;</span>
	given â€œa <a href="http://www.google.de/search?q=site%3Adocs.codehaus.org/%20new"><span style="color: #000000; font-weight: bold;">new</span></a> accountâ€, <span style="color: #66cc66;">&#123;</span>
		account = <a href="http://www.google.de/search?q=site%3Adocs.codehaus.org/%20new"><span style="color: #000000; font-weight: bold;">new</span></a> Account<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>
	<span style="color: #66cc66;">&#125;</span>
	when â€œan initial deposit is madeâ€, <span style="color: #66cc66;">&#123;</span>
		initialAmount = <span style="color: #cc66cc;">100</span>
		account.<span style="color: #006600;">makeDeposit</span><span style="color: #66cc66;">&#40;</span>initialAmount<span style="color: #66cc66;">&#41;</span>
	<span style="color: #66cc66;">&#125;</span>
	then â€œthe balance should be equal to the amount depositedâ€, <span style="color: #66cc66;">&#123;</span>
		account.<span style="color: #006600;">balance</span>.<span style="color: #006600;">shouldBe</span> initialAmount
	<span style="color: #66cc66;">&#125;</span>
<span style="color: #66cc66;">&#125;</span>
&nbsp;</pre>
<p>The <code>shouldBe</code> call is an intuitive and readable way to verify that the requirement holds. Another way to verify the outcomes is to use the <code>ensure</code> syntax. Example:</p>
<pre class="groovy">&nbsp;
ensure<span style="color: #66cc66;">&#40;</span>account.<span style="color: #006600;">balance</span> &gt; <span style="color: #cc66cc;">0</span><span style="color: #66cc66;">&#41;</span>
&nbsp;</pre>
<p>or</p>
<pre class="groovy">&nbsp;
ensure<span style="color: #66cc66;">&#40;</span>account<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
	has<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#91;</span>balance:<span style="color: #cc66cc;">100</span><span style="color: #66cc66;">&#93;</span><span style="color: #66cc66;">&#41;</span>
<span style="color: #66cc66;">&#125;</span>
&nbsp;</pre>
<p>easyb could be extended to use DBUnit (and further plugins for Grails and Excel are on the way). On the IDE support, the only good option is IntelliJ IDEA. It really comes down to the Groovy support, and Eclipse and NetBeans doesn't shine here. In those cases, you're better off running the tests in Maven or Ant, which both are well supported. In the upcoming version, easyb will have full support for Continuous Integration (CI), enabling automatic test execution in a CI-server such as Hudson.</p>
<p>Furthermore, easyb comes with a web application - Easiness (cmp. Fitnesse) - where stakeholders can create stories in plain text. The developers can then go ahead and implement the stories defined by the stakeholders. This is an important features, that further improves the cooperation between the customer and the provider. It really seems like a quite nice little framework! If you agree, have a look at it at <a href="http://easyb.org/">http://easyb.org/</a>.</p>
<h3>From Concurrent to Parallel â€“ Library-based parallelism in JDK 7 (Brian Goetz)</h3>
<p>Brian is an expert in the concurrency area, but he's not a good presenter! He speaks faster than I can read, and his slides are so packed with info that he doesn't have time to say the half of it. That put aside, in this very interesting session Brian presented some really cool concurrency features to be included in JDK 7.</p>
<p>As you probably know, JDK 5 introduced a set of very useful classes for course-grained parallelism. JDK 7 will introduce a framework for fine-grained parallelism - the "fork-join" framework.</p>
<p>We have now reach a point in time when Moore's laws isn't valid anymore. The new reality is not faster CPUs but more CPUs. To adapt to these changes, programmers have to change the way they think about parallelism. The unit of work (UoW) that represents a task to be solved must be split into even smaller parts to be able to keep all hardware busy. Nowadays, it isn't enough to for ex. spawn a new thread for each service call in a server, the UoW must be split up even further.</p>
<p>Examples of finer-grained parallelism is searching, sorting and filtering a data set. Such a task is preferably solved by dividing it into sub-problems and combining the sub-results at the end. We could use the course-grained concurrency tools (for ex. <code>Executor</code> + <code>Future</code>) introduced in JDK 5 to solve this problem. However, with multiple CPUs available, these tools doesn't perform optimally. For ex., the shared work queue in the <code>Executor</code> becomes a bottle neck when the number of threads/CPUs increases. Furthermore, these tools provide no form of load balancing, i.e. if one thread finishes before the others, it is never reused.</p>
<p>The divide-and-conquer algorithm could also be applied to solve the problem. This great advantage of this approach is that it's independent of the number of CPUs used! Using plain threads for this approach is too expensive though, since thread creation costs way too much. However, the fork-join-operation in JDK 7 solves problems like these using the divide-and-conquer algorithm in a much more effective way! Internally, it uses an slim thread pool to overcome the cost of thread creation. Furthermore, no data-copying penalty exist since the data set (for ex. an array) is not divided/copied during the solution. Instead, the indexes within the data structure is used to define each data subset. Another advantage is that the code doesn't know how many CPUs it executes on, hence it's portable! </p>
<p>While the <code>Executor</code> (JDK 5) should be used for tasks consisting of both IO and computing, the fork-join-operation (JDK 7) should be used for highly compute-intensive tasks. Examples of such tasks are matrix operations, numerical integrations and game playing. The JDK 7 class to be used for these kind of problems is <code>ParallelArray</code>. It's a utility class that greatly simplifies the work of solving a task in parallel. You can think of it as an in-memory database for data sets. Typical usage is:</p>
<pre class="java">&nbsp;
ParallelLongArray pa = ParallelLongArray.<span style="color: #006600;">createUsingHandoff</span><span style="color: #66cc66;">&#40;</span>array, forkJoinPool<span style="color: #66cc66;">&#41;</span>;
<span style="color: #993333;">long</span> max = pa.<span style="color: #006600;">max</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;</pre>
<p>The <code>ParallelArray</code> class provides operations for:</p>
<ul>
<li>Filtering (nestable)</li>
<li>Mapping</li>
<li>Replacement</li>
<li>Aggregation (max, count, sum, ...)</li>
<li>Application (one action performed for each selected element)</li>
</ul>
<p>To compare, the <code>ParallelArray</code> class acts much like the Map-Produce concept introduced by Google but it works in a different domain (local system instead of in a distributed system).</p>
<p>The only downside really is that JDK 7 isn't scheduled until mid 2010, meaning we'll have to wait quite some time before we can actually use these new concurrency features. But from the looks of it ... it may be worth the wait!</p>
<h3>The SpringSource DM Server (Joris Kuipers)</h3>
<p>The reasons why SpringSource decided to develop a new application server were many. Today, modularity is important and developers spend much time on achieving it in their applications (layering, separation of concerns, etc.). However, when the application is deployed, all modularity is lost - the deployable unit is one huge, monolithic WAR file. That means that sharing code (let alone services) between applications become hard if not impossible. In order to perform the smallest update on the application, whole WAR file have to be redeployed. Furthermore, the servers themselves lack modularity; they come prepackaged with a lot of modules but there's no way to configure that your application only make use of a couple of them. Hence, they are all left in there, consuming unnecessary CPU cycles and memory.</p>
<p>The DM (Dynamic Modules) server was developed to tackle these issues of non-modularity. In order to achieve true modularity, is has been built on top of OSGi (namely the Equinox container). Since OSGi can be quite hard sometimes, the DM server conceal the complexity of OSGi in the same way as the Spring framework does with for ex. Remoting or JMX. </p>
<p>In order to be able to use a third-party library from within the DM server (and from any other OSGi containers), the standard JAR library needs to be extended with OSGi-specific meta data - the OSGi manifest. SpringSource has therefore created the Enterprise Bundle Repository, where they have started to upload and publish OSGi-ified Java EE libraries. If you're using Maven or Ivy, the bundle repository can easily be configured as a remote (or local) repository.</p>
<p>The DM server also introduces a couple of new OSGi import constructs, enabling ease of development. One example is the "Import-library" that can be useful if you want to make use of a framework (for ex. Spring) but don't want to waste your time having to specify every single Import-package (for example Spring-Remoting) within the framework (as you normally would have had to do). This doesn't affect performance improvement since (thanks to OSGi) none of the pre-installed bundles are loaded before they are actually used! Furthermore, with the DM server it's now possible to remove the library bloat of monolithic Java EE WARs. Instead of building the external libraries into your WAR, you can instead declare them as dependencies in the OSGi manifest headers. The server will then convert these into plain "Import-package" constructs during deployment. That way, the size of the built/deployed WAR can be reduced significantly!</p>
<p>In the DM server, one can of course deploy plain OSGi bundles but also WARs, EARs etc. Typical scenarios for deploying a plain OSGi bundle are stand-alone libraries, global services and small stand-alone applications. However, being able to deploy a bundle is not enough in most cases ... A normal application normally consist of multiple bundles, which becomes hard to un/deploy since there is no single deployable unit. Furthermore, with multiple bundles you don't get a common log file or a notion of an application scope. To tackle this issue, the DM server adds the notion of an application by introducing the PAR (Platform Archive) format. It's basically a JAR with a number of 'Application-*' manifest headers. You can think of it as an EAR in Java EE. PARs are versioned and the versions apply to all of their bundles. This mean that one can deploy a PAR twice with different versions but with the same bundles, without conflicts.</p>
<p>The DM server comes in several versions. Of course there's the community version, using a GPL and SpringSource license. Then there's the commercial license where full support from SpringSource is included. On the extension side, better Maven support will soon be released so that the dependencies can be specified in a single place (not like now when you have to duplicate them in the pom and in the manifest). There's a Eclipse-plugin available that enables re/deployments from within the IDE.</p>
<p>These are some of the features in the DM server. There are plenty or more cool ones, read all about them <a href="http://www.springsource.com/products/suite/dmserver">here</a>. There, you'll also find a lot of sample applications that can get you going! With the DM server, SpringSource feel that they are filling the (up until now) empty space of server side OSGi and states that "The DM server is the healthy new way to run your apps!". I must say it looks very promising! Why don't you go ahead and try it out!? I know I will!</p>
<p><em>If you appreciated these posts, you will definitely enjoy next years conference! Pick up your calendar and reserve December 2009 for a great week at Devoxx!</em></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2008/12/23/devoxx-highlights/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Azul</title>
		<link>http://blog.jayway.com/2008/10/20/azul/</link>
		<comments>http://blog.jayway.com/2008/10/20/azul/#comments</comments>
		<pubDate>Mon, 20 Oct 2008 19:58:46 +0000</pubDate>
		<dc:creator>Jan Kronquist</dc:creator>
				<category><![CDATA[Architecture]]></category>
		<category><![CDATA[concurrency]]></category>
		<category><![CDATA[hardware]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[scala]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=363</guid>
		<description><![CDATA[We have got the privilege to borrow an Azul Vega 1 which is the smallest of <a href="http://www.azulsystems.com/">Azul</a>'s monster machines. This evening a bunch of us Jaywayers gathered to try it out. Installing the Azul JVM was painless and all of us were up and running very quickly. Read more...]]></description>
			<content:encoded><![CDATA[<p>We have got the privilege to borrow an Azul Vega 1 which is the smallest of <a href="http://www.azulsystems.com/">Azul</a>'s monster machines. This evening a bunch of us Jaywayers gathered to try it out. Installing the Azul JVM was painless and all of us were up and running very quickly.</p>
<p>Here is screenshot from the management console showing 81 active CPUs and 23 GB free memory:</p>
<p><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2008/10/azul.png" rel="lightbox"><img src="http://blog.jayway.com/wordpress/wp-content/uploads/2008/10/azul.png" alt="" title="azul" width="600" height="250" class="alignnone size-medium wp-image-364" /></a></p>
<p>I tried some <a href="http://www.scala-lang.org/node/242">Scala actors</a> which worked very well. By running some CPU intensive calculations I concluded that it scaled linearly up to the number of CPUs. No surprise, but very cool when you are running 80 threads at full speed! Also cool to see that Scala runs smoothly which means that neither Scala nor Azul does anything strange. Just pure bytecode.</p>
<p>Somebody tried to configure the Azul JVM in Eclipse and was able to run JUnit tests on Azul. We were also able to run maven without any problems.</p>
<p>We tried to allocate lots of memory. No problem there either, although we had to specify -Xmx10G or something. By default you only get 1.6 GB....</p>
<p>A colleague started tomcat, produced lots of garbage and tried garbage collection at 8 GB of heap. No pause! However, there was some synchronization problem with Log4j since all 16 CPUs had to coordinate their work.</p>
<p>We encountered two problems:</p>
<ul>
<li>xstream apparently had a dependency to Unsafe which is not supported on Azul</li>
<li>the program must be headless, so no Swing</li>
</ul>
<p>A quick rewrite later and we had generated a 64 megapixel mandelbrot calculated in parallel on 40 CPUs. The only problem was saving the PNG file which was a single threaded operation...</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2008/10/20/azul/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>News On Concurrency</title>
		<link>http://blog.jayway.com/2007/05/01/news-on-concurrency/</link>
		<comments>http://blog.jayway.com/2007/05/01/news-on-concurrency/#comments</comments>
		<pubDate>Tue, 01 May 2007 14:18:18 +0000</pubDate>
		<dc:creator>Jacob Mattsson</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[concurrency]]></category>
		<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=3495</guid>
		<description><![CDATA[Prior to Java 5, most people associated concurrency in Java with the Thread and Runnable concepts. That has all changed now! We now have a compelling high-level API at our hands, including a lot of new concurrent data structures in the Collections Framework and a brand new task Executor framework. In this article, you’ll get [...]]]></description>
			<content:encoded><![CDATA[<p><strong>Prior to Java 5, most people associated concurrency in Java with the Thread and Runnable concepts. That has all changed now! We now have a compelling high-level API at our hands, including a lot of new concurrent data structures in the Collections Framework and a brand new task Executor framework. In this article, you’ll get an introduction to the most important features in the new java.util.concurrent package.</strong> </p>
<h2>Low level constructs</h2>
<p>In the new API, there are representations of the classical concurrency constructs of<br />
locks, semaphores, latches and barriers. The Lock interface, for example, behave very<br />
much like the intrinsic lock (used in synchronized blocks). However, the biggest<br />
advantage of Lock objects is their ability to back out if the lock isn’t available, either<br />
immediately or within a specified timeout, allowing the implementer to take an al-<br />
ternate	action.	Furthermore,	the	new	Lock	interface	also	allows	locks	to	be	acquired<br />
and released in different code blocks. The drawback of the new Lock class is that<br />
it’s more complex, above all it requires the programmer to remember to release the<br />
lock. In a similar manner, there are useful implementations of semaphores, latches<br />
and barriers.<br />
The concept of atomicity is central in concurrency. An atomic operation is one<br />
that cannot be interrupted by a concurrently running process. The Java increment<br />
operator, i++, is not an atomic operation (internally it’s three operations) but a sim-<br />
ple assign (i = 5;) is. The java.util.concurrent.atomic package defines classes that<br />
support	atomic	operations	on	single	variables.	For	example,	in	order	to	protect	a<br />
variable incrementation (i++) from thread interference without resorting to syn-<br />
chronization, the variable can be kept in an AtomicInteger and the increment can be<br />
performed using the incrementAndGet() method, thus ensuring atomicity. </p>
<h2>New Collection types</h2>
<p>The java.util.concurrent package includes a number of additions to the Java Collec-<br />
tions	Framework.	The	new	concurrent	collections	are	improvements	over	synchro-<br />
nized collections in terms of throughput and efficiency. Synchronized collections<br />
achieve their thread safety by protecting the collection’s state by a collection-wide<br />
lock. When accessed by multiple threads, throughput suffers. Concurrent collec-<br />
tions, on the other hand, are designed for concurrent access from multiple threads<br />
and instead lock on the individual elements.<br />
Two important new Collection types are BlockingQueue and ConcurrentMap.<br />
BlockingQueue implements the (non-concurrent) Queue interface, which holds<br />
elements prior to processing. The thread-safe BlockingQueue is primarily designed<br />
for producer-consumer queues and allows clients to wait for an element to appear<br />
(possibly within a specified timeout). Waiting occurs if you either try to insert an<br />
element into a full queue or if you try to retrieve from an empty queue. Concur-<br />
rentMap defines a couple of very useful atomic map operations: </p>
<ul>
<li>	A	key/value	pair	is	removed/replaced	only	if	the	key	is	present	in	the	map.
<li>	A	key/value	pair	is	added	only	if	the	key	is	absent.
</ul>
<p>Hence, there’s no need to synchronize when accessing the ConcurrentMap.</p>
<h2>High level constructs </h2>
<p>The new Callable interface is responsible for encapsulating a task. It’s similar to the<br />
Runnable interface; both are designed for classes whose instances are potentially<br />
executed by another thread. However, Callable returns a result and may throw an<br />
exception. The utility class Executors has methods for converting from other com-<br />
mon	task	forms	(such	as	Runnable)	to	a	Callable.	Furthermore,	a	Callable	can	be<br />
executed by the ExecutorService class in the submit() method.<br />
The	Future	interface	is	an	important	entity	in	the	new	Executor	framework	and<br />
represents the result of an asynchronous computation. The result can be retrieved<br />
using one of the get() methods when the computation has completed, blocking if<br />
necessary until it’s ready. The interface provides a possibility to cancel the computa-<br />
tion and it’s also possible to determine if the task completed normally or if it was<br />
canceled.	A	Future	is	normally	used	in	the	following	manner: </p>
<pre>Future<String> futureResult = executor.submit(
   new Callable<String>() {
      public String call() {
         // perform heavy op and return result
      }
   }
);
doOtherThings();
try {
   useResult(futureResult.get());
} catch (ExecutionException ee) { cleanup(); }
</pre>
<p>Notice how the result is retrieved - get() might be blocking (depending on if the<br />
computation is ready or not by the time of the invocation).<br />
Executor is a simple interface for launching new tasks. It provides a way of decou-<br />
pling task submission from the mechanics of how each task will be run, including<br />
details of thread use, scheduling, etc. The single method in the interface, execute(),<br />
has been designed to replace the way we normally use threads. That is, instead of<br />
explicitly creating a new thread for each task to execute, all tasks are executed by a<br />
single Executor. How the Executor actually executes the tasks internally is imple-<br />
mentation-dependent. </p>
<p><img src="http://blog.jayway.com/wordpress/wp-content/uploads/2009/12/Picture-86.png" alt="Figure 1" title="Figure 1" width="419" height="248" class="alignnone size-full wp-image-3496" /></p>
<p>The ExecutorService interface extends the Executor interface and adds fea-<br />
tures for managing the life cycle of both individual tasks and the executor itself. It’s<br />
submit() methods accept both Runnable and Callable objects and returns a<br />
Future.	An	unused	ExecutorService	should	be	shutdown()	to	reclaim	its	resources.<br />
The ExecutorService interface also provide methods for submitting large collections<br />
of Callable objects.<br />
It’s time for an example. An implementation of a simple web server might look<br />
something like this: </p>
<pre>public class WebServer {
   /**
    * Creates a server socket, accepts connections,
    * and handles each incoming request in a new thread.
    */
   public void run() throws IOException {
      ServerSocket socket = new ServerSocket(8080);
      while (true) {
         final Socket connection = socket.accept();
         Runnable task = new Runnable() {
            public void run() {
               handleRequest(connection);
            }
         };
         new Thread(task).start();
      }
   } 

   public static void main(String[] args)
         throws IOException {
      WebServer webServer = new WebServer();
      webServer.run();
   } 

   private void handleRequest(Socket connection) {
      // Impl. details not important here!
   }
}
</pre>
<p>In order to achieve high responsiveness, each new request is handled in a new<br />
thread.	Under	light	to	moderate	load	with	sufficient	CPU	resources	available,	this<br />
implementation offers relatively good throughput too. However, it would be nice to<br />
have a more flexible solution supporting a wide variety of task execution policies, i.e.<br />
for ex. to be able to specify in what thread and in what order tasks will be executed,<br />
and how many tasks may execute concurrently. Let’s introduce an Executor: </p>
<pre>public class ThreadPerTaskExecutor implements Executor {
   public void execute(Runnable r) {
      new Thread(r).start();
   };
}
</pre>
<p>, which leaves us with the following run() method: </p>
<pre>public void run() throws IOException {
   Executor exec = new ThreadPerTaskExecutor();
   ServerSocket socket = new ServerSocket(8080);
   while (true) {
      final Socket connection = socket.accept();
      Runnable task = new Runnable() {
         public void run() {
            handleRequest(connection);
         }
      };
      exec.execute(task);
   }
} </pre>
<p>The great advantage of this approach is of course that the execution policy could<br />
very easily be substituted (even configured at deployment-time) without altering<br />
the rest of the code base. However, one big problem still exists with this solution!<br />
Under	heavy	load	a	lot	of	threads	will	be	created,	and	thread	creation	and	teardown<br />
takes	time	and	active	threads	consume	a	lot	of	memory.	Furthermore,	each	platform<br />
has an upper limit on how many threads that can be created, and when this limit is<br />
hit an OutOfMemoryError is probably thrown. Hence, up to a certain point, more<br />
threads can improve throughput but beyond that point, creating more threads just<br />
slows down the application and may even lead to a crash. The way to stay out of<br />
danger is to place some bound on how many active threads your application utilizes<br />
concurrently.<br />
Most of the executor implementations internally make use of thread pools,<br />
which consists of worker threads. Worker threads are often used to execute mul-<br />
tiple tasks and minimize the overhead caused by thread creation. One common<br />
thread pool type is the fixed thread pool, which always has a specified number of<br />
threads running. The Executors class contains factory methods for retrieving Execu-<br />
torServices	that	in	turn	use	different	kind	of	thread	pools	internally.	For	example,<br />
newCachedThreadPool() creates a thread pool that creates new threads as needed<br />
but will try to reuse previously created threads when available.<br />
To be on the safe side with regards to both throughput and responsiveness in the<br />
web server example, an executor that uses a thread pool internally should be used: </p>
<pre>public void run() throws IOException {
   Executor exec = Executors.newFixedThreadPool(100);
   ServerSocket socket = new ServerSocket(8080);
   while (true) {
      ... // same as above
   }
}
</pre>
<h2>Conclusion </h2>
<p>As you can imagine, Java 5 has given us a lot of great high level features in the<br />
new concurrency package. However, they extend (not replace) the traditional low<br />
level concurrency constructs, such as the synchronized keyword and the wait/notify<br />
mechanism, who still have a vital role to play. Your concurrency toolbox has just<br />
become bigger and more flexible. </p>
<h2>References </h2>
<p>1  <a href="http://java.sun.com/j2se/1.5.0/docs/api/ )">The JavaDoc</a><br />
2  <a href="http://java.sun.com/j2se/1.5.0/docs/guide/collections/changes5.html">Java 5 Collection Framework changes</a><br />
3  “Java Concurrency in Practice” (Brian Goetz et. al.), ISBN 9780321349606<br />
4  <a href="http://java.sun.com/docs/books/tutorial/essential/concurrency ) ">Concurrency Tutorial</a> </p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2007/05/01/news-on-concurrency/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

