<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/atom10full.xsl"?><?xml-stylesheet type="text/css" media="screen" href="http://feeds.feedburner.com/~d/styles/itemcontent.css"?><feed xmlns="http://www.w3.org/2005/Atom" xmlns:openSearch="http://a9.com/-/spec/opensearch/1.1/" xmlns:blogger="http://schemas.google.com/blogger/2008" xmlns:georss="http://www.georss.org/georss" xmlns:gd="http://schemas.google.com/g/2005" xmlns:thr="http://purl.org/syndication/thread/1.0" xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" gd:etag="W/&quot;AkIGSX84fyp7ImA9WhFSEE8.&quot;"><id>tag:blogger.com,1999:blog-5701415790759755571</id><updated>2013-06-12T11:15:28.137+02:00</updated><category term="5' on IT-Architecture" /><category term="NIO.2" /><category term="Threading stories" /><category term="dip-framework" /><category term="Spring-CDI modules" /><category term="Spring" /><category term="Methodology" /><category term="Git" /><category term="Java EE" /><category term="Agile" /><category term="Java" /><category term="Tutorials" /><title>Niklas' Blog</title><subtitle type="html" /><link rel="http://schemas.google.com/g/2005#feed" type="application/atom+xml" href="http://niklasschlimm.blogspot.com/feeds/posts/default" /><link rel="alternate" type="text/html" href="http://niklasschlimm.blogspot.com/" /><link rel="next" type="application/atom+xml" href="http://www.blogger.com/feeds/5701415790759755571/posts/default?start-index=26&amp;max-results=25&amp;redirect=false&amp;v=2" /><author><name>Niklas Schlimm</name><uri>http://www.blogger.com/profile/12402045792243894660</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="24" height="32" src="http://1.bp.blogspot.com/-T7F8yoGErpc/TjlFwjgDvTI/AAAAAAAAAPo/Uqt54kYww9E/s220/Niki.JPG" /></author><generator version="7.00" uri="http://www.blogger.com">Blogger</generator><openSearch:totalResults>37</openSearch:totalResults><openSearch:startIndex>1</openSearch:startIndex><openSearch:itemsPerPage>25</openSearch:itemsPerPage><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" type="application/atom+xml" href="http://feeds.feedburner.com/blogspot/BufQX" /><feedburner:info uri="blogspot/bufqx" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com/" /><feedburner:emailServiceId>blogspot/BufQX</feedburner:emailServiceId><feedburner:feedburnerHostname>http://feedburner.google.com</feedburner:feedburnerHostname><feedburner:feedFlare href="http://add.my.yahoo.com/rss?url=http%3A%2F%2Ffeeds.feedburner.com%2Fblogspot%2FBufQX" src="http://us.i1.yimg.com/us.yimg.com/i/us/my/addtomyyahoo4.gif">Subscribe with My Yahoo!</feedburner:feedFlare><feedburner:feedFlare href="http://www.newsgator.com/ngs/subscriber/subext.aspx?url=http%3A%2F%2Ffeeds.feedburner.com%2Fblogspot%2FBufQX" src="http://www.newsgator.com/images/ngsub1.gif">Subscribe with NewsGator</feedburner:feedFlare><feedburner:feedFlare href="http://feeds.my.aol.com/add.jsp?url=http%3A%2F%2Ffeeds.feedburner.com%2Fblogspot%2FBufQX" src="http://o.aolcdn.com/favorites.my.aol.com/webmaster/ffclient/webroot/locale/en-US/images/myAOLButtonSmall.gif">Subscribe with My AOL</feedburner:feedFlare><feedburner:feedFlare href="http://www.bloglines.com/sub/http://feeds.feedburner.com/blogspot/BufQX" src="http://www.bloglines.com/images/sub_modern11.gif">Subscribe with Bloglines</feedburner:feedFlare><feedburner:feedFlare href="http://www.netvibes.com/subscribe.php?url=http%3A%2F%2Ffeeds.feedburner.com%2Fblogspot%2FBufQX" src="http://www.netvibes.com/img/add2netvibes.gif">Subscribe with Netvibes</feedburner:feedFlare><feedburner:feedFlare href="http://fusion.google.com/add?feedurl=http%3A%2F%2Ffeeds.feedburner.com%2Fblogspot%2FBufQX" src="http://buttons.googlesyndication.com/fusion/add.gif">Subscribe with Google</feedburner:feedFlare><feedburner:feedFlare href="http://www.pageflakes.com/subscribe.aspx?url=http%3A%2F%2Ffeeds.feedburner.com%2Fblogspot%2FBufQX" src="http://www.pageflakes.com/ImageFile.ashx?instanceId=Static_4&amp;fileName=ATP_blu_91x17.gif">Subscribe with Pageflakes</feedburner:feedFlare><feedburner:feedFlare href="http://www.plusmo.com/add?url=http%3A%2F%2Ffeeds.feedburner.com%2Fblogspot%2FBufQX" src="http://plusmo.com/res/graphics/fbplusmo.gif">Subscribe with Plusmo</feedburner:feedFlare><feedburner:feedFlare href="http://www.thefreedictionary.com/_/hp/AddRSS.aspx?http%3A%2F%2Ffeeds.feedburner.com%2Fblogspot%2FBufQX" src="http://img.tfd.com/hp/addToTheFreeDictionary.gif">Subscribe with The Free Dictionary</feedburner:feedFlare><feedburner:feedFlare href="http://www.bitty.com/manual/?contenttype=rssfeed&amp;contentvalue=http%3A%2F%2Ffeeds.feedburner.com%2Fblogspot%2FBufQX" src="http://www.bitty.com/img/bittychicklet_91x17.gif">Subscribe with Bitty Browser</feedburner:feedFlare><feedburner:feedFlare href="http://www.live.com/?add=http%3A%2F%2Ffeeds.feedburner.com%2Fblogspot%2FBufQX" src="http://tkfiles.storage.msn.com/x1piYkpqHC_35nIp1gLE68-wvzLZO8iXl_JMledmJQXP-XTBOLfmQv4zhj4MhcWEJh_GtoBIiAl1Mjh-ndp9k47If7hTaFno0mxW9_i3p_5qQw">Subscribe with Live.com</feedburner:feedFlare><feedburner:feedFlare href="http://mix.excite.eu/add?feedurl=http%3A%2F%2Ffeeds.feedburner.com%2Fblogspot%2FBufQX" src="http://image.excite.co.uk/mix/addtomix.gif">Subscribe with Excite MIX</feedburner:feedFlare><feedburner:feedFlare href="http://www.webwag.com/wwgthis.php?url=http%3A%2F%2Ffeeds.feedburner.com%2Fblogspot%2FBufQX" src="http://www.webwag.com/images/wwgthis.gif">Subscribe with Webwag</feedburner:feedFlare><feedburner:feedFlare href="http://www.podcastready.com/oneclick_bookmark.php?url=http%3A%2F%2Ffeeds.feedburner.com%2Fblogspot%2FBufQX" src="http://www.podcastready.com/images/podcastready_button.gif">Subscribe with Podcast Ready</feedburner:feedFlare><feedburner:feedFlare href="http://www.wikio.com/subscribe?url=http%3A%2F%2Ffeeds.feedburner.com%2Fblogspot%2FBufQX" src="http://www.wikio.com/shared/img/add2wikio.gif">Subscribe with Wikio</feedburner:feedFlare><feedburner:feedFlare href="http://www.dailyrotation.com/index.php?feed=http%3A%2F%2Ffeeds.feedburner.com%2Fblogspot%2FBufQX" src="http://www.dailyrotation.com/rss-dr2.gif">Subscribe with Daily Rotation</feedburner:feedFlare><entry gd:etag="W/&quot;CkUDRHY8fip7ImA9WhJWFUk.&quot;"><id>tag:blogger.com,1999:blog-5701415790759755571.post-2769844306014298414</id><published>2012-08-17T13:16:00.006+02:00</published><updated>2012-08-21T11:11:15.876+02:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2012-08-21T11:11:15.876+02:00</app:edited><category scheme="http://www.blogger.com/atom/ns#" term="5' on IT-Architecture" /><title>5' on IT-Architecture: the modern software architect</title><content type="html">Before I start writing about this let me adjust something right at the beginning:&lt;br /&gt;
&lt;blockquote style="background-color: #cfe2f3;"&gt;Yes of course, there is the role of a "software architect" in any non-trivial software development project. Even in times of agile projects, dynamic markets and vague terms like "emergence". The simple reason for that is that emergence and democracy in teams only work within constraints. Though, it's not always clever to assign somebody the role explicitly. In an ideal world one developer in that team evolves into the architecture role. &lt;/blockquote&gt;When I started working as an IT professional at a *big* american software &amp;amp; IT consulting company I spent around five years with programming. After that time I got my first architecture job on a big project at a german automotive manufacturer. My main responsibility was to design the solution, advice developers, project managers and clients in doing things and to organize the development process. I wrote many documents, but I didn't code anymore. The result was that I lost expertise in my &lt;i&gt;core business&lt;/i&gt;: programming. So after a while my assessments and gut instinct got worse, which results in worse decisions. As a sideeffect of generic (vague) talking it got harder to gain acceptance by the developers, project managers or clients. When I realized all that I decided to do more development again. Today, I am doing architecture for 10 years. I am developing code in the IDE of my choice at least 20-30% of my time. &lt;br /&gt;
&lt;br /&gt;
&lt;a name='more'&gt;&lt;/a&gt;&lt;b&gt;Avtivity profile&lt;/b&gt;&lt;br /&gt;
&lt;br /&gt;
Whilst programming is a &lt;i&gt;necessary activity&lt;/i&gt;, there is a whole bunch of activities that are &lt;i&gt;sufficient&lt;/i&gt; to be successful as an architect. Doing architecture is a lot about collaboration, evaluating alternatives objectively (neutral and fair-minded) and about decision making. It's a lot about communication, dealing with other individuals that almost always have their own opinions. Further more it's a lot about forming teams and designing the ideal development process around those teams to solve the concrete problem. Last not least it's about designing (structuring) the solution in a way that all functional and non-functional requirements are well covered. You can do all that more or less without super actual technical knowledge. But I believe an architect can do better if he/she has technical expertise gathered by day-to-day coding business. In the long run you cannot be a technical architect without sufficient coding practice.&lt;br /&gt;
&lt;br /&gt;
&lt;table align="center" cellpadding="0" cellspacing="0" class="tr-caption-container" style="margin-left: auto; margin-right: auto; text-align: center;"&gt;&lt;tbody&gt;
&lt;tr&gt;&lt;td style="text-align: center;"&gt;&lt;a href="http://1.bp.blogspot.com/-qgf0fEmS-jk/UC4S4WU35ZI/AAAAAAAAAVY/OQxjQrTXg4c/s1600/Foto.JPG" imageanchor="1" style="margin-left: auto; margin-right: auto;"&gt;&lt;img border="0" height="240" src="http://1.bp.blogspot.com/-qgf0fEmS-jk/UC4S4WU35ZI/AAAAAAAAAVY/OQxjQrTXg4c/s320/Foto.JPG" width="320" /&gt;&lt;/a&gt;&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td class="tr-caption" style="text-align: center;"&gt;Figure 1: Activities of the software architect&lt;/td&gt;&lt;/tr&gt;
&lt;/tbody&gt;&lt;/table&gt;&lt;br /&gt;
&lt;b&gt;Solving tradeoffs&lt;/b&gt;&lt;br /&gt;
&lt;br /&gt;
When I worked as an architect I often found myself in difficult &lt;i&gt;tradeoff situations&lt;/i&gt;. That is, I wanted to improve one quality attribute, but to achieve that I needed to downgrade another. Here is a simple but very common example: its often desireable to have a highly changeable system with best possible performance. However, these two attributes - performance and changeability - typically correlate negatively, when you want to increase changeability you often loose efficiency. Doing architecture often means to find the golden mean between competing system qualities - it means choosing the right alternative that represents the best compromise. It's about finding the balance between system qualities and the environmental factors of that system (e.g. steakholders, requirements). The operations manager will focus on the efficiency of a new system, while the development manager will argue that it's important to have a changeable system that generates little maintenance costs. The client wants to have a new system with the highest degree of business process automation as possible. These situations consume a reasonalbe amount of time and energy. &lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Sharing knowledge and communication&lt;/b&gt;&lt;br /&gt;
&lt;br /&gt;
Another superior important activity: &lt;i&gt;sharing knowledge&lt;/i&gt; in a team of technical experts and other steakholders. The core problem of software development is to transform fuzzy knowledge of domain experts into merciless logical machine code of silly computers that only understand two digits: 0 and 1. This is a long way through the venturesome and endless jungle of human misunderstandings! Therefore, architects communicate a lot. They use models to do that. Models serve as a mapping mechanism between human brains and computers. The set of problems that can arise during the knowledge-to-binary transformation is very diverse. It's impossible that every team member knows all of them. That's another reason why sharing knowledge in a team is so superior important.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Nobody is perfect!&lt;/b&gt;&lt;br /&gt;
&lt;br /&gt;
Needless to say that &lt;i&gt;nobody is perfect&lt;/i&gt;. Every team is different and so is every concrete situation. So in one situation one may be the right architect for the team while in other team set-ups that person doesn't fit. An architect can also have different strengths. I know architects that communicate and socialize very well but don't do so good in designing solutions or organizing the development process. Although they don't master each individual skill, they're all good architects. The common ground is that they were all down-to-earth developers.&lt;br /&gt;
&lt;br /&gt;
That's all I wanted to express today. &lt;br /&gt;
So long, Niklas&lt;img src="http://feeds.feedburner.com/~r/blogspot/BufQX/~4/IuRvJ9MhFkE" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://niklasschlimm.blogspot.com/feeds/2769844306014298414/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://niklasschlimm.blogspot.com/2012/08/5-on-it-architecture-modern-software.html#comment-form" title="0 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/5701415790759755571/posts/default/2769844306014298414?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/5701415790759755571/posts/default/2769844306014298414?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/blogspot/BufQX/~3/IuRvJ9MhFkE/5-on-it-architecture-modern-software.html" title="5' on IT-Architecture: the modern software architect" /><author><name>Niklas Schlimm</name><uri>http://www.blogger.com/profile/12402045792243894660</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="24" height="32" src="http://1.bp.blogspot.com/-T7F8yoGErpc/TjlFwjgDvTI/AAAAAAAAAPo/Uqt54kYww9E/s220/Niki.JPG" /></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="http://1.bp.blogspot.com/-qgf0fEmS-jk/UC4S4WU35ZI/AAAAAAAAAVY/OQxjQrTXg4c/s72-c/Foto.JPG" height="72" width="72" /><thr:total>0</thr:total><feedburner:origLink>http://niklasschlimm.blogspot.com/2012/08/5-on-it-architecture-modern-software.html</feedburner:origLink></entry><entry gd:etag="W/&quot;C0IFQX88cSp7ImA9WhJRGUo.&quot;"><id>tag:blogger.com,1999:blog-5701415790759755571.post-8865697116824712397</id><published>2012-07-18T16:59:00.003+02:00</published><updated>2012-07-22T17:38:30.179+02:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2012-07-22T17:38:30.179+02:00</app:edited><category scheme="http://www.blogger.com/atom/ns#" term="5' on IT-Architecture" /><title>5' on IT-Architecture: root concepts explained by the pioneers of software architecture</title><content type="html">The last couple of weeks I am working on a new software architecture course specifically for the insurance and financial sector. During the preparations I was reading many of the most cited articles on software architecture. The concepts described in these articles are so fundamental (and still up-to-date) that every architect really should know about them. I have enjoyed reading such "old" stuff. I first read most of the cited articles during my studies at university in the mid 90s. It is surprising to realize that, the longer you're in this business, the more you agree to the ideas explained - in articles that were written 40 years ago! I've decided to qoute the original text passages - may be I thought it would be overbearing to explain it in my own words ;-) I hope you enjoy reading these text passages from the pioneers of software architecture.&lt;br /&gt;
&lt;br /&gt;
&lt;a name='more'&gt;&lt;/a&gt;&lt;b&gt;On the criteria for system decomposition&lt;/b&gt;&lt;br /&gt;
&lt;br /&gt;
"Many readers will now see what criteria were used in each decomposition. In the first decomposition the criterion used was to make each major step in the processing a module. One might say that to get the first decomposition one makes a flowchart. This is the most common approach to decomposition or modularization. It is an outgrowth of all programmer training which teaches us that we should begin with a rough flowchart and move from there to a detailed implementation. The flowchart was a useful abstraction for systems with on the order of 5,000-10,000 instructions, but as we move beyond that it does not appear to be sufficient; something additional is needed.&lt;br /&gt;
&lt;br /&gt;
The second decomposition was made using "information hiding" as a criterion. The modules no longer correspond to steps in the processing. [...] Every module in the second decomposition is characterized by its knowledge of a design decision which it hides from all others. Its interface or definition was chosen to reveal as little as possible about its inner workings."&lt;br /&gt;
&lt;br /&gt;
in: On the Criteria To Be Used in Decomposing Systems into Modules, D.L. Parnas, 1972&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;On the information hiding design principle&lt;/b&gt;&lt;br /&gt;
&lt;br /&gt;
"Our module structure is based on the decomposition criterion known as information hiding [IH]. According to this principle, system details that are likely to change independently should be the secrets of separate modules; the only assumptions that should appear in the interfaces between modules are those that are considered unlikely to change. Each data structure is used in only one module; it may be directly accessed by one or more programs within the module but not by programs outside the module. Any other program that requires information stored in a module’s data structures must obtain it by calling access programs belonging to that module.&lt;br /&gt;
&lt;br /&gt;
Applying this principle is not always easy. It is an attempt to minimize the expected cost of software and requires that the designer estimate the likelihood of changes. Such estimates are based on past experience, and may require knowledge of the application area, as well as an understanding of hardware and software technology."&lt;br /&gt;
&lt;br /&gt;
in: The Modular Structure of Complex Systems, D.L. Parnas, 1985&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;On module hierarchies&lt;/b&gt;&lt;br /&gt;
&lt;br /&gt;
"In discussions of system structure it is easy to confuse the benefits of a good decomposition with those of a hierarchical structure. We have a hierarchical structure if a certain relation may be defined between the modules or programs and that relation is a partial ordering. The relation we are concerned with is "uses" or "depends upon". [...] The partial ordering gives us two additional benefits. First, parts of the system are benefited (simplified) because they use the services of lower levels. Second, we are able to cut off the upper levels and still have a usable and useful product. [...] The existence of the hierarchical structure assures us that we can "prune" off the upper levels of the tree and start a new tree on the old trunk. If we had designed a system in which the "low level" modules made some use of the "high level" modules, we would not have the hierarchy, we would find it much harder to remove portions of the system, and "level" would not have much meaning in the system."&lt;br /&gt;
&lt;br /&gt;
in: On the Criteria To Be Used in Decomposing Systems into Modules, D.L. Parnas, 1972&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;On the separation of concerns&lt;/b&gt;&lt;br /&gt;
&lt;br /&gt;
"Let me try to explain to you, what to my taste is characteristic for all intelligent thinking. It is, that one is willing to study in depth an aspect of one's subject matter in isolation for the sake of its own consistency, all the time knowing that one is occupying oneself only with one of the aspects. We know that a program must be correct and we can study it from that viewpoint only; we also know that it should be efficient and we can study its efficiency on another day, so to speak. In another mood we may ask ourselves whether, and if so: why, the program is desirable. But nothing is gained —on the contrary!— by tackling these various aspects simultaneously. It is what I sometimes have called "the separation of concerns", which, even if not perfectly possible, is yet the only available technique for effective ordering of one's thoughts, that I know of. This is what I mean by "focussing one's attention upon some aspect": it does not mean ignoring the other aspects, it is just doing justice to the fact that from this aspect's point of view, the other is irrelevant. It is being one- and multiple-track minded simultaneously."&lt;br /&gt;
&lt;br /&gt;
in: On the role of scientific thought, Edsger W. Dijkstra, 1974&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;On conceptual integrity&lt;/b&gt;&lt;br /&gt;
&lt;br /&gt;
"Such design coherence in a tool not only delights, it also yields ease of learning and ease of use. The tool does what one expects it to do. I argued [...] that conceptual integrity is the most important consideration in system design. Sometimes the virtue is called coherence, sometimes consistency, sometimes uniformity of style [...] The solo designer or artist usually produces works with this integrity subconsciously; he tends to make each microsdecision the same way each time he encounters it (barring strong reasons). If he fails to produce such integrity, we consider the work flawed, not great."&lt;br /&gt;
&lt;br /&gt;
in: The Design of Design, Frederick P. Brooks, 2010 (originally introduced in: The Mythical Man Month, 1975)&lt;img src="http://feeds.feedburner.com/~r/blogspot/BufQX/~4/yWipKBIlOzY" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://niklasschlimm.blogspot.com/feeds/8865697116824712397/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://niklasschlimm.blogspot.com/2012/07/5-on-it-architecture-root-concepts.html#comment-form" title="0 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/5701415790759755571/posts/default/8865697116824712397?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/5701415790759755571/posts/default/8865697116824712397?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/blogspot/BufQX/~3/yWipKBIlOzY/5-on-it-architecture-root-concepts.html" title="5' on IT-Architecture: root concepts explained by the pioneers of software architecture" /><author><name>Niklas Schlimm</name><uri>http://www.blogger.com/profile/12402045792243894660</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="24" height="32" src="http://1.bp.blogspot.com/-T7F8yoGErpc/TjlFwjgDvTI/AAAAAAAAAPo/Uqt54kYww9E/s220/Niki.JPG" /></author><thr:total>0</thr:total><feedburner:origLink>http://niklasschlimm.blogspot.com/2012/07/5-on-it-architecture-root-concepts.html</feedburner:origLink></entry><entry gd:etag="W/&quot;AkAAQX0yeCp7ImA9WhJRFko.&quot;"><id>tag:blogger.com,1999:blog-5701415790759755571.post-6414534101780330277</id><published>2012-06-25T15:39:00.003+02:00</published><updated>2012-07-19T08:19:00.390+02:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2012-07-19T08:19:00.390+02:00</app:edited><category scheme="http://www.blogger.com/atom/ns#" term="5' on IT-Architecture" /><category scheme="http://www.blogger.com/atom/ns#" term="Methodology" /><title>5' on IT-Architecture: four laws of robust software systems</title><content type="html">&lt;a href="http://www.murphys-laws.com/murphy/murphy-true.html"&gt;Murphy's Law&lt;/a&gt; ("If anything can go wrong, it will") was born at Edwards Air Force Base in 1949 at North Base. It was named after Capt. Edward A. Murphy, an engineer working on Air Force Project MX981, (a project) designed to see how much sudden deceleration a person can stand in a crash. One day, after finding that a transducer was wired wrong, he cursed the technician responsible and said, "If there is any way to do it wrong, he'll find it." &lt;br /&gt;
&lt;br /&gt;
&lt;a name='more'&gt;&lt;/a&gt;For that described reason it may be good to put some quality assurance process in place. I could also call this blog "the four laws of steady software quality". It's about some fundamental techniques that can help to achieve superior quality over a longer distance. This is particularly important if you're developing some central component that will cause serious damage if it fails in production. OK, here is my (never final and not holistic) list of practical quality assurance tipps.&lt;br /&gt;
&lt;br /&gt;
Law 1: facilitate change&lt;br /&gt;
&lt;br /&gt;
There is nothing permanent except change. If a system isn't designed in accordance to this superior important reality, then the probability of failure may increase above average. A widely used technique to facilitate change is the development of a sufficient set of &lt;a href="http://en.m.wikipedia.org/wiki/Unit_testing"&gt;unit tests&lt;/a&gt;. Unit testing enables to uncover regressions in existing functionality after changes have been made to a system. It also encourages to really think about the desired functionality and required design of the component under development.&lt;br /&gt;
&lt;br /&gt;
Law 2: don't rush through the functional testing phase&lt;br /&gt;
&lt;br /&gt;
In economics, the marginal utility of a good is the gain (or loss) from an increase (or decrease) in the consumption of that good. The law of diminishing marginal utility says, that the marginal utility of each (homogenous) unit decreases as the supply of units increases (and vice versa). The first &lt;a href="http://en.wikipedia.org/wiki/Functional_testing"&gt;functional test&lt;/a&gt; cases often walk through the main scenarios covering the main paths of the considered software. All the code tested wasn't executed before. These test cases have a very high marginal utility. Subsequent test cases may walk through the same code ranges except specific sidepaths at specific validation conditions for instance. These test cases may cover three or four additional lines of code in your application. As a result, they will have a smaller marginal utility then the first test cases. &lt;br /&gt;
&lt;br /&gt;
My law about functional testing suggests: as long the execution of the next test case yields a significant utility the following applies: the more time you invest into testing the better the outcome! So don't rush through a functional testing phase and miss out some useful test case (this assumes the special case in which usefulness can be quantified). Try to find the useful test cases that promise a significant gain in perceptible quality. On the other hand, if you're executing test cases with a negative marginal utility you're actually investing more effort then you gain in terms of perceptible quality. There is this special (but not uncommon) situation where the client does not run functional tests on systematic bases. This law will then suggest: the longer the application is in the test environment, the better the outcome. &lt;br /&gt;
&lt;br /&gt;
Law 3: run (non-functional) benchmark tests&lt;br /&gt;
&lt;br /&gt;
Another peace of good permanent software quality is a regular &lt;a href="http://en.wikipedia.org/wiki/Load_testing"&gt;load test&lt;/a&gt;. To make results usable load tests need a defined steady environment and a baseline of measured values (a benchmark). These values are at least: CPU, response time, memory footprint. Load tests of new releases can be compared to those load tests of older releases. That way we can also bypass the often stated requirement that the load test environment needs to have the same capacity parameters then the production environment. In many cases it is possible to see the real big issues with a relatively small set of parallel users (e.g. 50 users). &lt;br /&gt;
&lt;br /&gt;
It makes limited sense to do load testing if single user &lt;a href="http://en.wikipedia.org/wiki/Profiling_%28computer_programming%29"&gt;profiling&lt;/a&gt; results are bad. Therefore it's a good idea to perform repeatable profiling test cases with every release. This way profiling results can be compared to each other (again: the benchmark idea). We do CPU and elapsed time profiling as well as memory profiling. Profiling is an activity that runs in parallel to actual development. It makes sence to focus on the main scenarios used regularly in production. &lt;br /&gt;
&lt;br /&gt;
Law 4: avoid dependency lock-in&lt;br /&gt;
&lt;br /&gt;
The difference between trouble and severe crisis is the time it takes to fix the problem that causes the trouble. For this reason you may always need a way back to your previous release, you need a fallback scenario to avoid a production crisis with severe business impact. You enable rollback by avoiding dependency lock-in. Runtime-dependencies of your application may exist to neighbouring systems by joint interface or contract changes during development. If you implemented requirements that resulted in changed interfaces and contracts, then you cannot simply roll back, that's obvious. Therefore you need to avoid too many interface and contract changes. Small release cycles help to reduce dependencies between application versions in one release 'cause less changes are rolled to production. Another counteraction against dependency lock-in is to let neighbouring systems be downwoards compatible for one version. &lt;br /&gt;
&lt;br /&gt;
That's it in terms of robust systems.&lt;br /&gt;
Cheers, Niklas&lt;img src="http://feeds.feedburner.com/~r/blogspot/BufQX/~4/W0EZ1-fnnI8" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://niklasschlimm.blogspot.com/feeds/6414534101780330277/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://niklasschlimm.blogspot.com/2012/06/5-on-it-architecture-four-laws-of.html#comment-form" title="2 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/5701415790759755571/posts/default/6414534101780330277?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/5701415790759755571/posts/default/6414534101780330277?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/blogspot/BufQX/~3/W0EZ1-fnnI8/5-on-it-architecture-four-laws-of.html" title="5' on IT-Architecture: four laws of robust software systems" /><author><name>Niklas Schlimm</name><uri>http://www.blogger.com/profile/12402045792243894660</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="24" height="32" src="http://1.bp.blogspot.com/-T7F8yoGErpc/TjlFwjgDvTI/AAAAAAAAAPo/Uqt54kYww9E/s220/Niki.JPG" /></author><thr:total>2</thr:total><feedburner:origLink>http://niklasschlimm.blogspot.com/2012/06/5-on-it-architecture-four-laws-of.html</feedburner:origLink></entry><entry gd:etag="W/&quot;CEAFRXY7fip7ImA9WhVUEEQ.&quot;"><id>tag:blogger.com,1999:blog-5701415790759755571.post-231758518382201269</id><published>2012-05-15T16:38:00.000+02:00</published><updated>2012-05-15T16:38:34.806+02:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2012-05-15T16:38:34.806+02:00</app:edited><category scheme="http://www.blogger.com/atom/ns#" term="5' on IT-Architecture" /><title>5' on IT-Architecture: three laws of good software architecture</title><content type="html">The issue with architectural decisions is that they effect the whole system and/or you often need to make them early in the development process. It means a lot effort if you change that decision a couple of months later. From an economic standpoint architectural decisions are often irrevocable. Good architecture is one that allows an architect to make late decisions without superior effect on efforts and costs. Let's put that on record.&lt;a name='more'&gt;&lt;/a&gt;&lt;br /&gt;
&lt;br /&gt;
Law 1: Good architecture is one that enables architects to have a minimum of irrevocable decisions.&lt;br /&gt;
&lt;br /&gt;
To minimize the set of irrevocable decisions the system needs to be responsive to change. There is a major lesson I have learned about software development projects: Nothing is permanent except change. The client changes his opinion about requirements. The stakeholders change their viewpoint of what's important. People join and leave the project team. The fact that change alone is unchanging leads me to the second rule of good architecture, that is:&lt;br /&gt;
&lt;br /&gt;
Law 2: To make decisions revocable you need to design for flexibility.&lt;br /&gt;
&lt;br /&gt;
This is the most provocative statement and I am having controversial discussions here. The reason is that flexibility introduces the need for abstraction. Abstraction uses a strategy of simplification, wherein formerly concrete details are left ambiguous, vague, or undefined (from &lt;a href="http://en.wikipedia.org/wiki/Abstraction"&gt;Wikipedia&lt;/a&gt;). This simplification process isn't always simple to do and to follow for others in particular. "Making something easy to change makes the overall system a little more complex, and making everything easy to change makes the entire system very complex. Complexity is what makes software hard to change." &lt;a href="http://martinfowler.com/ieeeSoftware/whoNeedsArchitect.pdf"&gt;from M. Fowler&lt;/a&gt;) This is one core problem of building good software architecture: Developing software that is easy to change but at the same time understandable. There are several concepts that try to tackle this paradox problem: &lt;a href="http://en.wikipedia.org/wiki/Design_Patterns"&gt;design patterns&lt;/a&gt; and &lt;a href="http://www.objectmentor.com/resources/articles/Principles_and_Patterns.pdf"&gt;object oriented design principles&lt;/a&gt;. Polymorphism, loose coupling and high cohesion are flexibility enablers to me.&lt;br /&gt;
&lt;br /&gt;
Law 3: To make use of flexibility one needs to refactor mercilessly.&lt;br /&gt;
&lt;br /&gt;
Flexibility is not an end in itself. You need to actively make use of flexible design. If something is changing and it makes a previous design or architectural decision obsolete you need to go into the code and change the software. Otherwise the effort of building flexible software is useless and technical debt may cause late delays and a maintenance nightmare. The fact that you take rigorous action on your code base requires continuous feedback about the qualities of your software. To be able to refactor it is therefore essential that the code base is covered by a sufficient amount of automated tests. In an ideal scenario everything is integrated into a continuous integration environment to receive permanent feedback about the health of your code base.&lt;img src="http://feeds.feedburner.com/~r/blogspot/BufQX/~4/UNIuofkfY2I" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://niklasschlimm.blogspot.com/feeds/231758518382201269/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://niklasschlimm.blogspot.com/2012/05/5-on-it-architecture-three-laws-of-good.html#comment-form" title="10 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/5701415790759755571/posts/default/231758518382201269?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/5701415790759755571/posts/default/231758518382201269?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/blogspot/BufQX/~3/UNIuofkfY2I/5-on-it-architecture-three-laws-of-good.html" title="5' on IT-Architecture: three laws of good software architecture" /><author><name>Niklas Schlimm</name><uri>http://www.blogger.com/profile/12402045792243894660</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="24" height="32" src="http://1.bp.blogspot.com/-T7F8yoGErpc/TjlFwjgDvTI/AAAAAAAAAPo/Uqt54kYww9E/s220/Niki.JPG" /></author><thr:total>10</thr:total><feedburner:origLink>http://niklasschlimm.blogspot.com/2012/05/5-on-it-architecture-three-laws-of-good.html</feedburner:origLink></entry><entry gd:etag="W/&quot;D0IHQnw6fip7ImA9WhVVFEo.&quot;"><id>tag:blogger.com,1999:blog-5701415790759755571.post-2124693091611043010</id><published>2012-05-04T15:09:00.004+02:00</published><updated>2012-05-08T13:12:13.216+02:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2012-05-08T13:12:13.216+02:00</app:edited><category scheme="http://www.blogger.com/atom/ns#" term="Java" /><category scheme="http://www.blogger.com/atom/ns#" term="NIO.2" /><title>Java 7: NIO.2 I/O operations on asynchronous channels are not atomic</title><content type="html">This part of my NIO.2 series wasn't on schedule when I started writing about NIO.2 aasynchronous file channels. It deals with an important detail: read and write operations are not atomic. What that means is that &lt;code&gt;AsynchronousFileChannel -&amp;gt; write()&lt;/code&gt; does not garantee to write all bytes passed as parameter to the destination file. Instead it returns the number of bytes written as return parameters of the corresponding I/O operations and the client needs to deal with situations where the bytes written isn't equal to the remaining bytes in the passed &lt;code&gt;ByteBuffer&lt;/code&gt;. &lt;br /&gt;
&lt;br /&gt;
&lt;a name='more'&gt;&lt;/a&gt;Let's recall the method signatures of the &lt;code&gt;read()&lt;/code&gt; and &lt;code&gt;write()&lt;/code&gt; operations in the &lt;code&gt;AsynchronousFileChannel&lt;/code&gt; interface for a moment.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="java" name="code"&gt;public abstract &amp;lt;A&amp;gt; void write(ByteBuffer src,
                                   long position,
                                   A attachment,
                                   CompletionHandler&amp;lt;Integer,? super A&amp;gt; handler);

    public abstract &amp;lt;A&amp;gt; void read(ByteBuffer dst,
                                  long position,
                                  A attachment,
                                  CompletionHandler&amp;lt;Integer,? super A&amp;gt; handler);
&lt;/pre&gt;&lt;br /&gt;
As you can see these signatures offer to pass a completion handler. I've already intruduced the completion handler in my last blog about closing file channels safely. You could also use the completion handler to enforce that all bytes are written or read when you perform I/O operations on an asynchronous channel. Here is the code snippet that does the Job.&lt;br /&gt;
&lt;br /&gt;
&lt;script src="https://gist.github.com/2506857.js"&gt;
 
&lt;/script&gt;&lt;br /&gt;
The &lt;code&gt;readAll&lt;/code&gt; (line 14) and the &lt;code&gt;writeFully&lt;/code&gt; methods (line 35) both call the corresponding &lt;code&gt;read&lt;/code&gt; or &lt;code&gt;write&lt;/code&gt; operations on asynchronous file channels recursively. This recursion ends, when the bytes of the source &lt;code&gt;ByteBuffer&lt;/code&gt; are transferred completely. Notice that the main thread has to wait for these recursions to finnish. Therefore a &lt;code&gt;CountDownLatch&lt;/code&gt; stops the main thread until all bytes are processed by the I/O thread that executes the &lt;code&gt;CompletionHandler&lt;/code&gt;.&lt;br /&gt;
&lt;br /&gt;
The explained procedure works because the position of the source or destination &lt;code&gt;ByteBuffer&lt;/code&gt; is always in sync with the actual bytes transferred. Another important fact is that the &lt;code&gt;write()&lt;/code&gt; and &lt;code&gt;read()&lt;/code&gt; operations in the &lt;code&gt;CompletionHandler&lt;/code&gt; are chained. That is when the write task completes one new one is issued and when this completes one new one is issued and so forth. Allthough different JVM threads will participate, there won't be an issue in sharing that same (non thread safe) &lt;code&gt;ByteBuffer&lt;/code&gt; instance.&lt;br /&gt;
&lt;br /&gt;
The NIO.2 file channels series:&lt;br /&gt;
- &lt;a href="http://niklasschlimm.blogspot.de/2012/04/java-7-asynchronous-file-channels-part.html"&gt;Introduction&lt;/a&gt;&lt;br /&gt;
- &lt;a href="http://niklasschlimm.blogspot.de/2012/04/java-7-asynchronous-file-channels-part_05.html"&gt;Applying custom thread pools&lt;/a&gt;&lt;br /&gt;
- &lt;a href="http://niklasschlimm.blogspot.de/2012/05/java-7-9-nio2-file-channels-on-test.html"&gt;Closing file channels without loosing data&lt;/a&gt;&lt;br /&gt;
- &lt;a href="http://niklasschlimm.blogspot.de/2012/05/java-7-10-nio2-file-channels-on-test.html"&gt;I/O operations are not atomic&lt;br /&gt;
&lt;/a&gt;&lt;br /&gt;
&lt;script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"&gt;
&lt;/script&gt;&lt;br /&gt;
&lt;script src="http://gist.github.com/raw/454771/gist-line-number-hack.js"&gt;
&lt;/script&gt;&lt;br /&gt;
&lt;script type="text/javascript"&gt;
addLineNumbersToAllGists()
&lt;/script&gt;&lt;img src="http://feeds.feedburner.com/~r/blogspot/BufQX/~4/38gWTsyzQ_0" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://niklasschlimm.blogspot.com/feeds/2124693091611043010/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://niklasschlimm.blogspot.com/2012/05/java-7-10-nio2-file-channels-on-test.html#comment-form" title="0 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/5701415790759755571/posts/default/2124693091611043010?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/5701415790759755571/posts/default/2124693091611043010?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/blogspot/BufQX/~3/38gWTsyzQ_0/java-7-10-nio2-file-channels-on-test.html" title="Java 7: NIO.2 I/O operations on asynchronous channels are not atomic" /><author><name>Niklas Schlimm</name><uri>http://www.blogger.com/profile/12402045792243894660</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="24" height="32" src="http://1.bp.blogspot.com/-T7F8yoGErpc/TjlFwjgDvTI/AAAAAAAAAPo/Uqt54kYww9E/s220/Niki.JPG" /></author><thr:total>0</thr:total><feedburner:origLink>http://niklasschlimm.blogspot.com/2012/05/java-7-10-nio2-file-channels-on-test.html</feedburner:origLink></entry><entry gd:etag="W/&quot;D0IFRXg6fSp7ImA9WhVVFEo.&quot;"><id>tag:blogger.com,1999:blog-5701415790759755571.post-8550660866779937371</id><published>2012-05-04T15:08:00.002+02:00</published><updated>2012-05-08T13:11:54.615+02:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2012-05-08T13:11:54.615+02:00</app:edited><category scheme="http://www.blogger.com/atom/ns#" term="Java" /><category scheme="http://www.blogger.com/atom/ns#" term="NIO.2" /><title>Java 7: Closing NIO.2 file channels without loosing data</title><content type="html">Closing an asynchronous file channel can be very difficult. If you submitted I/O tasks to the asynchronous channel you want to be sure that the tasks are executed properly. This can actually be a tricky requirement on asynchronous channels for several reasons. The default channel group uses deamon threads as worker threads, which isn't a good choice, cause these threads just abandon if the JVM exits. If you use a custom thread pool executor with non-deamon threads (see &lt;a href="http://niklasschlimm.blogspot.de/2012/04/java-7-asynchronous-file-channels-part_05.html"&gt;last part of this series&lt;/a&gt;) you need to manage the lifecycle of your thread pool yourself. If you don't the threads just stay alive when the main thread exits. Hence, the JVM actually does not exit at all, what you can do is kill the JVM. &lt;br /&gt;
&lt;br /&gt;
&lt;a name='more'&gt;&lt;/a&gt;Another issue when closing asynchronous channels is mentioned in the javadoc of &lt;code&gt;AsynchronousFileChannel&lt;/code&gt;: "Shutting down the executor service while the channel is open results in unspecified behavior." This is because the &lt;code&gt;close()&lt;/code&gt; operation on &lt;code&gt;AsynchronousFileChannel&lt;/code&gt; issues tasks to the associated executor service that simulate the failure of pending I/O operations (in that same thread pool) with an &lt;code&gt;AsynchronousCloseException&lt;/code&gt;. Hence, you'll get &lt;code&gt;RejectedExecutionException&lt;/code&gt; if you perform &lt;code&gt;close()&lt;/code&gt; on an asynchronous file channel instance when you previously closed the associated executor service. &lt;br /&gt;
&lt;br /&gt;
That all being said, the proposed way to safely configure the file channel and shutdown that channel goes like this:&lt;br /&gt;
&lt;br /&gt;
&lt;script src="https://gist.github.com/2137930.js"&gt;
 
&lt;/script&gt;&lt;br /&gt;
The custom thread pool executor service is defined in lines 6 and 7. The file channel is defined in lines 10 to 13. In the lines 18 to 20 the asynchronous channel is closed in an orderly manner. First the channel itself is closed, then the executor service is shutdown and last not least the thread awaits termination of the thread pool executor. &lt;br /&gt;
&lt;br /&gt;
Although this is a safe way to close a channel with a custom executor service, there's a new issue introduced. The clients submitted asynchronous write tasks (line 16) and may want be sure that, once they've been submitted successfully, those tasks will definitely be executed. Always waiting for &lt;code&gt;Future.get()&lt;/code&gt; to return (line 23), isn't an option, cause in many cases this would lead *asynchronous* file channels ad adsurdum. The snippet above will return lot's of "Task wasn't executed!" messages cause the channel is closed immediately after the write operations were submitted to the channel (line 18). To avoid such 'data loss' you can implement your own &lt;code&gt;CompletionHandler&lt;/code&gt; and pass that to the requested write operation.&lt;br /&gt;
&lt;br /&gt;
&lt;script src="https://gist.github.com/2146334.js"&gt;
 
&lt;/script&gt;&lt;br /&gt;
The &lt;code&gt;CompletionHandler.failed()&lt;/code&gt; method (line 16) catches any runtime exception during task processing. You can implement any compensation code here to avoid data loss. When you work on mission critical data, then it may be a good idea to use &lt;code&gt;CompletionHandler&lt;/code&gt;s. But *still* there's another issue. The clients can submit tasks but they don't know if the pool will successfully process these tasks. Successful in this context means that the bytes submitted actually reach their destination (the file on the hard disk). If you want to be sure that all submitted tasks are actually processed before closing, it gets a little trickier. You need a 'graceful' closing mechanism, that waits until the work queue is empty *before* it actually closes the channel and the associated executor service (this isn't possible using standard lifecycle methods). &lt;br /&gt;
&lt;b&gt;&lt;br /&gt;
Introducing GracefulAsynchronousChannel&lt;/b&gt;&lt;br /&gt;
&lt;br /&gt;
My last snippets introduce the &lt;code&gt;GracefulAsynchronousFileChannel&lt;/code&gt;. You can get the complete code &lt;a href="https://github.com/nschlimm/playground/blob/master/java7-playground/src/main/java/com/schlimm/java7/nio/investigation/closing/graceful/GracefulAsynchronousFileChannel.java"&gt;here in my Git repository&lt;/a&gt;. The behaviour of that channel is like this: guarantee to process all successfully submitted write operations and throw an &lt;code&gt;NonWritableChannelException&lt;/code&gt; if the channel prepares shutdown. It takes two things to implement that behaviour. Firstly, you'll need to implement the &lt;code&gt;afterExecute()&lt;/code&gt; in an extension of &lt;code&gt;ThreadPoolExecutor&lt;/code&gt; that sends a signal when the queue is empty. This is what &lt;code&gt;DefensiveThreadPoolExecutor&lt;/code&gt; does. &lt;br /&gt;
&lt;br /&gt;
&lt;script src="https://gist.github.com/2301734.js"&gt;
 
&lt;/script&gt;&lt;br /&gt;
The &lt;code&gt;afterExecute()&lt;/code&gt; method (line 12) is executed after each processed task by the thread that processed that given task. The implementation sends the &lt;code&gt;isEmpty&lt;/code&gt; signal in line 18. The second part you need two gracefully close a channel is a custom implementation of the &lt;code&gt;close()&lt;/code&gt; method of &lt;code&gt;AsynchronousFileChannel&lt;/code&gt;.&lt;br /&gt;
&lt;br /&gt;
&lt;script src="https://gist.github.com/2301874.js"&gt;
 
&lt;/script&gt;&lt;br /&gt;
Study that code for a while. The interesting bits are in line 11 where the &lt;code&gt;innerChannel&lt;/code&gt; gets replaced by a read-only channel. That causes any subsequent asynchronous write requests to fail with an &lt;code&gt;NonWritableChannelException&lt;/code&gt;. In line 16 the &lt;code&gt;close()&lt;/code&gt; method waits for the &lt;code&gt;isEmpty&lt;/code&gt; signal to happen. When this signal is send after the last write task the &lt;code&gt;close()&lt;/code&gt; method continues with an orderly shutdown procedure (line 27 ff.). Basically, the code adds a shared lifecycle state across the file channel and the associated thread pool. That way both objects can communicate during the shutdown procedure and avoid data loss.&lt;br /&gt;
&lt;br /&gt;
Here is a logging client that uses the &lt;code&gt;GracefulAsynchronousFileChannel&lt;/code&gt;.&lt;br /&gt;
&lt;br /&gt;
&lt;script src="https://gist.github.com/2308688.js"&gt;
 
&lt;/script&gt;&lt;br /&gt;
The client starts two threads, one thread issues write operations in an infinite loop (line 6 ff.). The other thread closes the file channel asynchronously after one second of processing (line 25 ff.). If you run that client, then the following output is produced:&lt;br /&gt;
&lt;pre class="java" name="code"&gt;Starting graceful shutdown ...
Deal with the fact that the channel was closed asynchronously ... java.nio.channels.NonWritableChannelException
Channel blocked for write access ...
Waiting for signal that queue is empty ...
Issueing signal that queue is empty ...
Received signal that queue is empty ... closing
File closed ...
Pool closed ...
Expected file size (bytes): 400020
Actual file size (bytes): 400020
No write operation was lost!
&lt;/pre&gt;The output shows the orderly shutdown procedure of participating threads. The logging thread needs to deal with the fact that the channel was closed asynchronously. After the queued tasks are processed the channel resources are closed. No data was lost, everything that the client issued was really written to the file destination. No &lt;code&gt;AsynchronousClosedException&lt;/code&gt;s or &lt;code&gt;RejectedExecutionException&lt;/code&gt;s in such a graceful closing procedure.&lt;br /&gt;
&lt;br /&gt;
That's all in terms of safely closing asynchronous file channels. The complete code &lt;a href="https://github.com/nschlimm/playground/tree/master/java7-playground/src/main/java/com/schlimm/java7/nio/investigation/closing/graceful"&gt;is here in my Git repository&lt;/a&gt;. I hope you've enjoyed it a little. Looking forward to your comments.&lt;br /&gt;
Cheers, Niklas&lt;br /&gt;
&lt;br /&gt;
The NIO.2 file channels series:&lt;br /&gt;
- &lt;a href="http://niklasschlimm.blogspot.de/2012/04/java-7-asynchronous-file-channels-part.html"&gt;Introduction&lt;/a&gt;&lt;br /&gt;
- &lt;a href="http://niklasschlimm.blogspot.de/2012/04/java-7-asynchronous-file-channels-part_05.html"&gt;Applying custom thread pools&lt;/a&gt;&lt;br /&gt;
- &lt;a href="http://niklasschlimm.blogspot.de/2012/05/java-7-9-nio2-file-channels-on-test.html"&gt;Closing file channels without loosing data&lt;/a&gt;&lt;br /&gt;
- &lt;a href="http://niklasschlimm.blogspot.de/2012/05/java-7-10-nio2-file-channels-on-test.html"&gt;I/O operations are not atomic&lt;br /&gt;
&lt;/a&gt;&lt;br /&gt;
&lt;script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"&gt;
&lt;/script&gt;&lt;br /&gt;
&lt;script src="http://gist.github.com/raw/454771/gist-line-number-hack.js"&gt;
&lt;/script&gt;&lt;br /&gt;
&lt;script type="text/javascript"&gt;
addLineNumbersToAllGists()
&lt;/script&gt;&lt;img src="http://feeds.feedburner.com/~r/blogspot/BufQX/~4/j6J5eR3lls8" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://niklasschlimm.blogspot.com/feeds/8550660866779937371/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://niklasschlimm.blogspot.com/2012/05/java-7-9-nio2-file-channels-on-test.html#comment-form" title="0 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/5701415790759755571/posts/default/8550660866779937371?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/5701415790759755571/posts/default/8550660866779937371?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/blogspot/BufQX/~3/j6J5eR3lls8/java-7-9-nio2-file-channels-on-test.html" title="Java 7: Closing NIO.2 file channels without loosing data" /><author><name>Niklas Schlimm</name><uri>http://www.blogger.com/profile/12402045792243894660</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="24" height="32" src="http://1.bp.blogspot.com/-T7F8yoGErpc/TjlFwjgDvTI/AAAAAAAAAPo/Uqt54kYww9E/s220/Niki.JPG" /></author><thr:total>0</thr:total><feedburner:origLink>http://niklasschlimm.blogspot.com/2012/05/java-7-9-nio2-file-channels-on-test.html</feedburner:origLink></entry><entry gd:etag="W/&quot;D08NQnw_eCp7ImA9WhVXGU4.&quot;"><id>tag:blogger.com,1999:blog-5701415790759755571.post-9186153424289661487</id><published>2012-04-19T14:22:00.001+02:00</published><updated>2012-04-20T17:31:33.240+02:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2012-04-20T17:31:33.240+02:00</app:edited><category scheme="http://www.blogger.com/atom/ns#" term="Java" /><category scheme="http://www.blogger.com/atom/ns#" term="Threading stories" /><title>Threading stories: ThreadLocal in web applications</title><content type="html">This week I spend reasonable time to eliminate all our &lt;code&gt;ThreadLocal&lt;/code&gt; variables in our web applications. The reason was that they created classloader leaks and we coudn't undeploy our applications properly anymore. Classloader leaks happen when a GC root keeps referencing an application object after the application was undeployed. If an application object is still referenced after undeploy, then the whole class loader can't be garbage collected cause the considered object references your applications class file which in turn references the classloader. This will cause an &lt;code&gt;OutOfMemoryError&lt;/code&gt; after you've undeployed and redeployed a couple of times.&lt;br /&gt;
&lt;br /&gt;
&lt;a name='more'&gt;&lt;/a&gt;&lt;code&gt;ThreadLocal&lt;/code&gt; is one classic candidate that can easily create classloader leaks in web applications. The server is managing its threads in a pool. These threads live longer then your web application. In fact they don't die at all until the underlying JVM dies. Now, if you put a &lt;code&gt;ThreadLocal&lt;/code&gt; in a pooled thread that references an object of your class you *must* be careful. You need to make sure that this variable is removed again using &lt;code&gt;ThreadLocal.remove()&lt;/code&gt;. The issue in web applications is: where is the right place to safely remove &lt;code&gt;ThreadLocal&lt;/code&gt; variables? Also, you may not want to modify that "removing code" every time a colleague decided to add another &lt;code&gt;ThreadLocal&lt;/code&gt; to the managed threads. &lt;br /&gt;
&lt;br /&gt;
We've developed a wrapper class around thread local that keeps all the thread local variables in one single &lt;code&gt;ThreadLocal&lt;/code&gt; variable. Here is the code.&lt;br /&gt;
&lt;br /&gt;
&lt;script src="https://gist.github.com/2234464.js"&gt;
 
&lt;/script&gt;&lt;br /&gt;
The advantage of the utility class is that no developer needs to manage the thread local variable lifecycle individually. The class puts all the thread locals in one map of variables. The &lt;code&gt;destroy()&lt;/code&gt; method can be invoked where you can safely remove all thread locals in your web application. In our case thats a &lt;code&gt;ServletRequestListener -&amp;gt; requestDestroyed()&lt;/code&gt; method. You will also need to place finally blocks elsewhere. Typical places are near the &lt;code&gt;HttpServlet&lt;/code&gt;, in the &lt;code&gt;init()&lt;/code&gt;, &lt;code&gt;doPost()&lt;/code&gt;, &lt;code&gt;doGet()&lt;/code&gt; methods. This may remove all thread locals in the pooled worker threads after the request is done or an exception is thrown unexpectedly. Sometimes it happens that the &lt;code&gt;main&lt;/code&gt; thread of the server leaks thread local variables. If that is the case you need to find the right places where to call the &lt;code&gt;ThreadLocalUtil -&amp;gt; destroy()&lt;/code&gt; method. To do that figure out where the main thread actually *creates* the thread variables. You could use your debugger to do that.&lt;br /&gt;
&lt;br /&gt;
Many guys out there suggest to ommit &lt;code&gt;ThreadLocal&lt;/code&gt; in web applications for several reasons. It can be very difficult to remove them in a pooled thread environment so that you can undeploy the applications safely. &lt;code&gt;ThreadLocal&lt;/code&gt; variables can be useful, but it's fair to consider other techniques before applying them. An alternative for web applications to carry request scope parameters is the &lt;code&gt;HttpServletRequest&lt;/code&gt;. Many web frameworks allow for generic request parameter access as well as request/session attribute access, without ties to the native Servlet/Portlet API. Also many framework support request scoped beans to be injected into an object tree using dependency injection. All these options fulfill most requirements and should be considered prior to using &lt;code&gt;ThreadLocal&lt;/code&gt;.&lt;br /&gt;
&lt;script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"&gt;
&lt;/script&gt;&lt;br /&gt;
&lt;script src="http://gist.github.com/raw/454771/gist-line-number-hack.js"&gt;
&lt;/script&gt;&lt;br /&gt;
&lt;script type="text/javascript"&gt;
addLineNumbersToAllGists()
&lt;/script&gt;&lt;img src="http://feeds.feedburner.com/~r/blogspot/BufQX/~4/iU1ZJyUr6Sk" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://niklasschlimm.blogspot.com/feeds/9186153424289661487/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://niklasschlimm.blogspot.com/2012/04/threading-stories-threadlocal-in-web.html#comment-form" title="3 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/5701415790759755571/posts/default/9186153424289661487?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/5701415790759755571/posts/default/9186153424289661487?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/blogspot/BufQX/~3/iU1ZJyUr6Sk/threading-stories-threadlocal-in-web.html" title="Threading stories: ThreadLocal in web applications" /><author><name>Niklas Schlimm</name><uri>http://www.blogger.com/profile/12402045792243894660</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="24" height="32" src="http://1.bp.blogspot.com/-T7F8yoGErpc/TjlFwjgDvTI/AAAAAAAAAPo/Uqt54kYww9E/s220/Niki.JPG" /></author><thr:total>3</thr:total><feedburner:origLink>http://niklasschlimm.blogspot.com/2012/04/threading-stories-threadlocal-in-web.html</feedburner:origLink></entry><entry gd:etag="W/&quot;D0MNRX87fCp7ImA9WhVVFEo.&quot;"><id>tag:blogger.com,1999:blog-5701415790759755571.post-7997494819432789169</id><published>2012-04-05T09:42:00.009+02:00</published><updated>2012-05-08T13:11:34.104+02:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2012-05-08T13:11:34.104+02:00</app:edited><category scheme="http://www.blogger.com/atom/ns#" term="Java" /><category scheme="http://www.blogger.com/atom/ns#" term="NIO.2" /><title>Java 7: NIO.2 File Channels on the test bench - Part 2 - Applying custom thread pools</title><content type="html">Asynchronous file processing isn't a green card for high performance. In my &lt;a href="http://niklasschlimm.blogspot.de/2012/04/java-7-asynchronous-file-channels-part.html"&gt;last post&lt;/a&gt; I have demonstrated that conventional I/O can be faster then asynchronous channels. There are some additional important facts to know when applying NIO.2 file channels. The &lt;code&gt;Iocp&lt;/code&gt; class that performs all the asynchronous I/O tasks in NIO.2 file channels is, by default, backed by a so called "cached" thread pool. That's a thread pool that creates new threads as needed, but will reuse previously constructed threads *when* they are available. Look at the code of the &lt;code&gt;ThreadPool&lt;/code&gt; class held by the &lt;code&gt;Iocp&lt;/code&gt;.&lt;br /&gt;
&lt;a name='more'&gt;&lt;/a&gt;&lt;br /&gt;
&lt;script src="https://gist.github.com/1950482.js"&gt;
&lt;/script&gt;&lt;br /&gt;
The thread pool in the default channel group is constructed as &lt;code&gt;ThreadPoolExecutor&lt;/code&gt; with a maximum thread count of Integer.MAX_VALUE and a keep-alive-time of Long.MAX_VALUE. The threads are created as daemon threads by the thread factory. A synchronous hand-over queue is used to trigger thread creation if all threads are busy. There are several issues with this configuration: &lt;br /&gt;
&lt;br /&gt;
1. If you perform write operations on asynchronous channels in a burst you will create thousands of worker threads which likely results in an &lt;code&gt;OutOfMemoryError: unable to create new native thread&lt;/code&gt;. &lt;br /&gt;
2. When the JVM exits, then all deamon threads are abandoned - finally blocks are not executed, stacks are not unwound.&lt;br /&gt;
&lt;br /&gt;
In &lt;a href="http://niklasschlimm.blogspot.de/2012/03/threading-stories-about-robust-thread.html"&gt;my other blog&lt;/a&gt; I have explained why unbounded thread pools can 'cause trouble. Therefore, if you use asynchronous file channels, it may be an option to use custom thread pools instead of the default thread pool. The following snippet shows an example custom setting.&lt;br /&gt;
&lt;br /&gt;
&lt;script src="https://gist.github.com/2135620.js"&gt;
 
&lt;/script&gt;&lt;br /&gt;
The javadoc of &lt;code&gt;AsynchronousFileChannel&lt;/code&gt; states that the custom executor should "minimally [...] support an unbounded work queue and should not run tasks on the caller thread of the execute method." That's a risky statement, it is only reasonable if resources aren't an issue, which is rarely the case. It may make sense to use bounded thread pools for asynchronous file channels. You cannot get a too-many-threads issue, also you cannot flood your heap with work queue tasks. In the example above you have five threads that execute asynchonous I/O tasks and the work queue has a capacity of 2500 tasks. If the capacity limit is exceeded the rejected-execution-handler implements the &lt;code&gt;CallerRunsPolicy&lt;/code&gt; where the client has to execute the write task synchronously. This can (dramatically) slow down the system performance because the workload is "pushed back" to the client and executed synchronously. However, it can also save you from much more severe issues where the result is unpredictable. It's a good practice to work with bounded thread pools and to keep the thread pool sizes configurable, so that you can adjust them at runtime. Again, to learn more about robust thread pool settings &lt;a href="http://niklasschlimm.blogspot.de/2012/03/threading-stories-about-robust-thread.html"&gt;see my other blog entry&lt;/a&gt;.&lt;br /&gt;
&lt;br /&gt;
&lt;blockquote class="tr_bq" style="background-color: #cfe2f3;"&gt;Thread pools with synchronous hand-over queues and unbound maximum thread pool sizes can aggressively create new threads and thus can seriously harm system stability by consuming (pc registers and java stacks) runtime memory of the JVM. The 'longer' (elapsed time) the asynchronous task, the more likely you'll run into this issue.&lt;/blockquote&gt;&lt;blockquote class="tr_bq" style="background-color: #cfe2f3;"&gt;Thread pools with unbounded work queues and fixed thread pool sizes can aggressively create new tasks and objects and thus can seriously harm system stability by consuming heap memory and CPU through excessive garbage collection activity. The larger (in size) and longer (in elapsed time) the asynchronous task the more likely you'll run into this issue.&lt;/blockquote&gt;&lt;script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"&gt;
&lt;/script&gt;&lt;br /&gt;
That's all in terms of applying custom thread pools to asynchronous file channels. My next blog in this series will explain how to close asynchronous channels safely without loosing data.&lt;br /&gt;
&lt;br /&gt;
The NIO.2 file channels series:&lt;br /&gt;
- &lt;a href="http://niklasschlimm.blogspot.de/2012/04/java-7-asynchronous-file-channels-part.html"&gt;Introduction&lt;/a&gt;&lt;br /&gt;
- &lt;a href="http://niklasschlimm.blogspot.de/2012/04/java-7-asynchronous-file-channels-part_05.html"&gt;Applying custom thread pools&lt;/a&gt;&lt;br /&gt;
- &lt;a href="http://niklasschlimm.blogspot.de/2012/05/java-7-9-nio2-file-channels-on-test.html"&gt;Closing file channels without loosing data&lt;/a&gt;&lt;br /&gt;
- &lt;a href="http://niklasschlimm.blogspot.de/2012/05/java-7-10-nio2-file-channels-on-test.html"&gt;I/O operations are not atomic&lt;br /&gt;
&lt;/a&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;script src="http://gist.github.com/raw/454771/gist-line-number-hack.js"&gt;
&lt;/script&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;script type="text/javascript"&gt;
addLineNumbersToAllGists()
&lt;/script&gt;&lt;img src="http://feeds.feedburner.com/~r/blogspot/BufQX/~4/AQ_Qg39otwo" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://niklasschlimm.blogspot.com/feeds/7997494819432789169/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://niklasschlimm.blogspot.com/2012/04/java-7-asynchronous-file-channels-part_05.html#comment-form" title="5 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/5701415790759755571/posts/default/7997494819432789169?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/5701415790759755571/posts/default/7997494819432789169?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/blogspot/BufQX/~3/AQ_Qg39otwo/java-7-asynchronous-file-channels-part_05.html" title="Java 7: NIO.2 File Channels on the test bench - Part 2 - Applying custom thread pools" /><author><name>Niklas Schlimm</name><uri>http://www.blogger.com/profile/12402045792243894660</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="24" height="32" src="http://1.bp.blogspot.com/-T7F8yoGErpc/TjlFwjgDvTI/AAAAAAAAAPo/Uqt54kYww9E/s220/Niki.JPG" /></author><thr:total>5</thr:total><feedburner:origLink>http://niklasschlimm.blogspot.com/2012/04/java-7-asynchronous-file-channels-part_05.html</feedburner:origLink></entry><entry gd:etag="W/&quot;D0MDQHg_eip7ImA9WhVVFEo.&quot;"><id>tag:blogger.com,1999:blog-5701415790759755571.post-4025098492914055339</id><published>2012-04-05T09:40:00.009+02:00</published><updated>2012-05-08T13:11:11.642+02:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2012-05-08T13:11:11.642+02:00</app:edited><category scheme="http://www.blogger.com/atom/ns#" term="Java" /><category scheme="http://www.blogger.com/atom/ns#" term="NIO.2" /><title>Java 7: NIO.2 File Channels on the test bench - Part 1 - Introduction</title><content type="html">Another blog post about new JDK 7 features. This time I am writing about the new &lt;code&gt;AnsynchronousFileChannel&lt;/code&gt; class. I am analyzing the new JDK 7 features in depth for a couple of weeks now and I have decided to number my posts consecutively. Just to make sure I don't get confused :-) Here is my 7th post about Java 7 (I admit that - by coincidence - this was also a little confusing). Using NIO.2 asynchronous file channels effectively is a wide topic. There are some things to consider here. I have decided to devide the stuff into four posts. In this first part I will introduce the involved concepts when you use asynchonous file channels. Since these file channels work asynchronously, it is interesting to look at their performance compared to conventional I/O. The second part deals with issues like memory and CPU consumption and explains how to use the new NIO.2 channels safely in a high performance scenario. You also need to understand how to close asynchronous channels without loosing data, that's part three. Finally, in part four, we'll take a look into concurrency. &lt;br /&gt;
&lt;a name='more'&gt;&lt;/a&gt;&lt;br /&gt;
&lt;blockquote class="tr_bq"&gt;&lt;div style="background-color: #cfe2f3; text-align: left;"&gt;Notice: I won't explain the complete API of asynchronous file channels. There are enough posts out there that do a good job on that. My posts dive more into practical applicability and issues you may have when using asynchronous file channels.&lt;/div&gt;&lt;/blockquote&gt;&lt;br /&gt;
OK, enough vague talking, let's get started. Here is a code snippet that opens an asynchronous channel (line 7), writes a sequence of bytes to the beginning of the file (line 9) and waits for the result to return (line 10). Finally, in line 14 the channel is closed.&lt;br /&gt;
&lt;br /&gt;
&lt;script src="https://gist.github.com/1950035.js"&gt;
&lt;/script&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Important participants in asynchonous file channel calls&lt;/b&gt;&lt;br /&gt;
&lt;br /&gt;
Before I continue to dive into the code, let's introduce quickly the involved concepts in the asynchronous (file) channel galaxy. The callgraph in figure 1 shows the sequence diagram in a call to the &lt;code&gt;open()&lt;/code&gt;-method of the &lt;code&gt;AsynchronousFileChannel&lt;/code&gt; class. A &lt;code&gt;FileSystemProvider&lt;/code&gt; encapsulates all the operating systems specifics. To amuse everybody I am using a Windows 7 client when I am writing this. Therefeore a &lt;code&gt;WindowsFileSystemProvider&lt;/code&gt; calls the &lt;code&gt;WindowsChannelFactory&lt;/code&gt; which actually creates the file and calls the &lt;code&gt;WindowsAsynchronousFileChannelImpl&lt;/code&gt; which returns an instance of itself. The most important concept is the &lt;code&gt;Iocp&lt;/code&gt;, the I/O completion port. It is an API for performing multiple simultaneous asynchronous input/output operations. A completion port object is created and associated with a number of file handles. When I/O services are requested on the object, completion is indicated by a message queued to the I/O completion port. Other processes requesting I/O services are not notified of completion of the I/O services, but instead check the I/O completion port's message queue to determine the status of its I/O requests. The I/O completion port manages multiple threads and their concurrency. Is you can see from the diagram the &lt;code&gt;Iocp&lt;/code&gt; is a subtype of &lt;code&gt;AsynchronousChannelGroup&lt;/code&gt;. So in JDK 7 asynchronous channels the asynchronous channel group is implemented as an I/O completion port. It owns the &lt;code&gt;ThreadPool&lt;/code&gt; responsible for performing the requested asynchronous I/O operation. The &lt;code&gt;ThreadPool&lt;/code&gt; actually encapsulates a &lt;code&gt;ThreadPoolExecutor&lt;/code&gt; that does all the multi-threaded asynchronous task execution management since Java 1.5. Write operations to asnchronous file channels result in calls to the &lt;code&gt;ThreadPoolExecutor.execute()&lt;/code&gt; method. &lt;br /&gt;
&lt;br /&gt;
&lt;table align="center" cellpadding="0" cellspacing="0" class="tr-caption-container" style="margin-left: auto; margin-right: auto; text-align: center;"&gt;&lt;tbody&gt;
&lt;tr&gt;&lt;td style="text-align: center;"&gt;&lt;a href="http://1.bp.blogspot.com/-qUazKStyjbA/T0-NtGqrNPI/AAAAAAAAAUo/DDlobDG3Cc4/s1600/FileChannelCallgraph.JPG" imageanchor="1" style="margin-left: auto; margin-right: auto;"&gt;&lt;img border="0" height="254" src="http://1.bp.blogspot.com/-qUazKStyjbA/T0-NtGqrNPI/AAAAAAAAAUo/DDlobDG3Cc4/s320/FileChannelCallgraph.JPG" width="320" /&gt;&lt;/a&gt;&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td class="tr-caption" style="text-align: center;"&gt;Figure 1: Callgraph on open call to asynchronous file channel&lt;/td&gt;&lt;/tr&gt;
&lt;/tbody&gt;&lt;/table&gt;&lt;br /&gt;
&lt;b&gt;Some benchmarks&lt;/b&gt;&lt;br /&gt;
&lt;br /&gt;
It's always interesting to look at the performance. Asynchronous non blocking I/O must be fast, right? To find an answer to that question I have made my benchmark analysis. Again, I am using &lt;a href="http://www.javaspecialists.eu/archive/Issue124.html"&gt;Heinz' tiny benchmarking framework&lt;/a&gt; to do that. My machine is an Intel Core i5-2310 CPU @ 2.90 GHz with four cores (64-bit). In a benchmark I need a baseline. My baseline is a simple conventional synchronous write operation into an ordinary file. Here is the snippet:&lt;br /&gt;
&lt;br /&gt;
&lt;script src="https://gist.github.com/1950373.js"&gt;
&lt;/script&gt;&lt;br /&gt;
As you can see in line 25, the benchmark performs a single write operation into an ordinary file. And these are the results:&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="java" name="code"&gt;Test: Performance_Benchmark_ConventionalFileAccessExample_1
Warming up ...
EPSILON:20:TESTTIME:1000:ACTTIME:1014:LOOPS:365947
EPSILON:20:TESTTIME:1000:ACTTIME:1014:LOOPS:372298
Starting test intervall ...
EPSILON:20:TESTTIME:1000:ACTTIME:1000:LOOPS:364706
EPSILON:20:TESTTIME:1000:ACTTIME:1014:LOOPS:368309
EPSILON:20:TESTTIME:1000:ACTTIME:1014:LOOPS:370288
EPSILON:20:TESTTIME:1000:ACTTIME:1001:LOOPS:364908
EPSILON:20:TESTTIME:1000:ACTTIME:1014:LOOPS:370820
Mean: 367.806,2
Std. Deviation: 2.588,665
Total started thread count: 12
Peak thread count: 6
Deamon thread count: 4
Thread count: 5&lt;/pre&gt;&lt;br /&gt;
The following snippet is another benchmark which also issues a write operation (line 25), this time to an asynchronous file channel:&lt;br /&gt;
&lt;br /&gt;
&lt;script src="https://gist.github.com/1950310.js"&gt;
&lt;/script&gt;&lt;br /&gt;
This is the result of the above benchmark on my machine:&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="java" name="code"&gt;Test: Performance_Benchmark_AsynchronousFileChannel_1
Warming up ...
EPSILON:20:TESTTIME:1000:ACTTIME:1015:LOOPS:42667
EPSILON:20:TESTTIME:1000:ACTTIME:1015:LOOPS:193351
Starting test intervall ...
EPSILON:20:TESTTIME:1000:ACTTIME:1015:LOOPS:191268
EPSILON:20:TESTTIME:1000:ACTTIME:1015:LOOPS:186916
EPSILON:20:TESTTIME:1000:ACTTIME:1014:LOOPS:189842
EPSILON:20:TESTTIME:1000:ACTTIME:1014:LOOPS:191103
EPSILON:20:TESTTIME:1000:ACTTIME:1015:LOOPS:192005
Mean: 190.226,8
Std. Deviation: 1.795,733
Total started thread count: 17
Peak thread count: 11
Deamon thread count: 9
Thread count: 10&lt;/pre&gt;&lt;br /&gt;
Since the snippets above do the same thing, it's safe to say that asynchronous files channels aren't necessarily faster then conventional I/O. That's an interesting result I think. It's difficult to compare conventional I/O and NIO.2 to each other in a single threaded benchmark. NIO.2 was introduced to provide an I/O technique in highly concurrent scenarios. Therefore asking what's faster - NIO or conventional I/O - isn't quite the right question. The appropriate question was: what is "more concurrent"? However, for now, the results above suggest:&lt;br /&gt;
&lt;div style="text-align: center;"&gt;&lt;blockquote class="tr_bq" style="background-color: #cfe2f3;"&gt;Consider using conventional I/O when only one thread is issueing I/O-operations.&lt;/blockquote&gt;&lt;/div&gt;That's enough for now. I have explained the basic concepts and also pointed out that conventional I/O still has its right to exist. In the second post I will introduce some of the issues you may encounter when you use default asynchronous file channels. I will also show how to avoid those issues by applying some more viable settings.&lt;br /&gt;
&lt;br /&gt;
The NIO.2 file channels series:&lt;br /&gt;
- &lt;a href="http://niklasschlimm.blogspot.de/2012/04/java-7-asynchronous-file-channels-part.html"&gt;Introduction&lt;/a&gt;&lt;br /&gt;
- &lt;a href="http://niklasschlimm.blogspot.de/2012/04/java-7-asynchronous-file-channels-part_05.html"&gt;Applying custom thread pools&lt;/a&gt;&lt;br /&gt;
- &lt;a href="http://niklasschlimm.blogspot.de/2012/05/java-7-9-nio2-file-channels-on-test.html"&gt;Closing file channels without loosing data&lt;/a&gt;&lt;br /&gt;
- &lt;a href="http://niklasschlimm.blogspot.de/2012/05/java-7-10-nio2-file-channels-on-test.html"&gt;I/O operations are not atomic&lt;br /&gt;
&lt;/a&gt;&lt;br /&gt;
&lt;script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"&gt;
&lt;/script&gt;&lt;br /&gt;
&lt;script src="http://gist.github.com/raw/454771/gist-line-number-hack.js"&gt;
&lt;/script&gt;&lt;br /&gt;
&lt;script type="text/javascript"&gt;
addLineNumbersToAllGists()
&lt;/script&gt;&lt;img src="http://feeds.feedburner.com/~r/blogspot/BufQX/~4/pxhjnzRZniE" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://niklasschlimm.blogspot.com/feeds/4025098492914055339/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://niklasschlimm.blogspot.com/2012/04/java-7-asynchronous-file-channels-part.html#comment-form" title="9 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/5701415790759755571/posts/default/4025098492914055339?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/5701415790759755571/posts/default/4025098492914055339?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/blogspot/BufQX/~3/pxhjnzRZniE/java-7-asynchronous-file-channels-part.html" title="Java 7: NIO.2 File Channels on the test bench - Part 1 - Introduction" /><author><name>Niklas Schlimm</name><uri>http://www.blogger.com/profile/12402045792243894660</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="24" height="32" src="http://1.bp.blogspot.com/-T7F8yoGErpc/TjlFwjgDvTI/AAAAAAAAAPo/Uqt54kYww9E/s220/Niki.JPG" /></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="http://1.bp.blogspot.com/-qUazKStyjbA/T0-NtGqrNPI/AAAAAAAAAUo/DDlobDG3Cc4/s72-c/FileChannelCallgraph.JPG" height="72" width="72" /><thr:total>9</thr:total><feedburner:origLink>http://niklasschlimm.blogspot.com/2012/04/java-7-asynchronous-file-channels-part.html</feedburner:origLink></entry><entry gd:etag="W/&quot;D0AERn8yeCp7ImA9WhVRFEk.&quot;"><id>tag:blogger.com,1999:blog-5701415790759755571.post-7010339699457913742</id><published>2012-03-21T12:02:00.007+01:00</published><updated>2012-03-22T20:48:27.190+01:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2012-03-22T20:48:27.190+01:00</app:edited><category scheme="http://www.blogger.com/atom/ns#" term="Java" /><category scheme="http://www.blogger.com/atom/ns#" term="Threading stories" /><title>Threading stories: about robust thread pools</title><content type="html">Another blog of my threading series. This time it's about thread pools, robust thread pool settings in particular. In Java thread pools are implemented by the &lt;code&gt;ThreadPoolExecutor&lt;/code&gt; class introduced in Java 5. The Javadoc of that class is very well organized. So I spare me the effort to give a general introduction here. Basically, what &lt;code&gt;ThreadPoolExecutor&lt;/code&gt; does is, it creates and manages threads that process &lt;code&gt;Runnable&lt;/code&gt; tasks that were submitted to a work queue by an arbitrary client. It's a mechanism to perform work asynchronously, which is an important capability in times of multi-core machines and cloud computing.&lt;br /&gt;
&lt;br /&gt;
&lt;a name='more'&gt;&lt;/a&gt;To be useful in a wide range of contexts &lt;code&gt;ThreadPoolExecutor&lt;/code&gt; provides some adjustable parameters. This is nice, but it also leaves the decision to us, the developers, to choose the right settings for our concrete cases. Here is the largest constructor for a &lt;code&gt;ThreadPoolExecutor&lt;/code&gt;.&lt;br /&gt;
&lt;br /&gt;
&lt;script src="https://gist.github.com/2157551.js"&gt; &lt;/script&gt;&lt;br /&gt;
&lt;b&gt;Thread pool types&lt;/b&gt;&lt;br /&gt;
&lt;br /&gt;
Some of the parameters shown in the construtor above are very sensible ones in terms of resource consumption and resulting system stability. Based on the different parameter settings of the constructor it's possible to distinguish some fundamental categories of thread pools. Here are some default thread pool settings offered by the &lt;code&gt;Executors&lt;/code&gt; class.&lt;br /&gt;
&lt;br /&gt;
&lt;script src="https://gist.github.com/2157553.js"&gt; &lt;/script&gt;&lt;br /&gt;
In the "cached thread pool" the number of threads is unbounded. This is caused by a &lt;code&gt;maximumPoolSize&lt;/code&gt; of &lt;code&gt;Integer.MAX_VALUE&lt;/code&gt; in conjunction with &lt;code&gt;SynchronousQueue&lt;/code&gt;. If you submit tasks in a burst to that thread pool, it will likely create a thread for each single task. In this scenario created threads terminate when they were idle for 60 seconds. The second example shows a "fixed thread pool", where &lt;code&gt;maximumPoolSize&lt;/code&gt; is set to a specific fixed value. The pools thread count will never exceed this value. If tasks arive in a burst and all threads are busy then they will queue up in the work queue (here a &lt;code&gt;LinkedBlockingQueue&lt;/code&gt;). Threads in this fixed thread pool never die. The drawback of unbounded pools is obvious: both settings can cause JVM memory trouble (you get &lt;code&gt;OutOfMemoryError&lt;/code&gt;s - if you're lucky).&lt;br /&gt;
&lt;br /&gt;
Let's look at some bounded thread pool settings:&lt;br /&gt;
&lt;br /&gt;
&lt;script src="https://gist.github.com/2157556.js"&gt; &lt;/script&gt;&lt;br /&gt;
The first snippet creates a chached thread pool with the number of threads bounded to a value of 50. If tasks arrive in a burst and all the threads are busy, a call to the &lt;code&gt;ThreadPoolExecutor.execute()&lt;/code&gt; method would now be rejected by issueing a &lt;code&gt;RejectedExecutionException&lt;/code&gt;. Often this isn't what I typically want, therefore I change the saturation policy by setting the rejected-execution-handler to &lt;code&gt;CallerRunsPolicy&lt;/code&gt;. This policy pushes the work back to the caller. That is, the client thread that issued the task for asynchronous execution will now run the task synchronously. You can develop your own saturation policy by implementing your own &lt;code&gt;RejectedExecutionHandler&lt;/code&gt;. The second snippet creates a fixed thread pool with 50 threads and a work queue that is bounded to a value of 100000 tasks. If the work queue is full, the saturation policy pushes the work back to the client. The cached pool creates threads on demand and it terminates the threads if they idle for 60 seconds. The fixed pool keeps the threads alive.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Thread pool boundaries&lt;/b&gt;&lt;br /&gt;
&lt;br /&gt;
As shown above there are two basic approaches to define thread pools: bounded and unbounded thread pools. Unbounded thread pools, like the default ones of &lt;code&gt;Executors&lt;/code&gt; class work fine, as long you don't submit too many tasks in a burst. If that happens unbounded thread pools can harm your systems stability. Either too many threads are created by a cached thread pool, or too many tasks are queued in a fixed thread pool. The letter is more difficult to achieve, but still possible. For production use it may be better to set the boundaries to some meaningfull values like in the last two thread pool settings. Because it can be tricky to define those "meaningfull boundaries" I have developed a little program that does that work for me. &lt;br /&gt;
&lt;br /&gt;
&lt;script src="https://gist.github.com/2134350.js"&gt;
 
&lt;/script&gt;&lt;br /&gt;
The program will find ideal thread pool boundaries for the maximum capacity of your work queue and the required thread count. The algorithms are based on the work of Brian Goetz and Dr. Heinz Kabutz, you can find the references in the Javadoc. Calculating the capacity required by your work queue in a fixed thread pool is relatively simple. All you need is the desired target size of the work queue in bytes divided by the average size of your submitted tasks in bytes. Unfortunately, calculating the maximum thread count *isn't* an exact science. However, if you use the formulas in the program you avoid the harmful extremes of too large work queues and too many threads. Calculating the ideal pool size depends on the wait time to compute time ratio of your task. The more wait time, the more threads required to achieve a given utilization. The &lt;code&gt;PoolSizeCalculator&lt;/code&gt; requires the desired target utilization and the desired maximum work queue memory consumption as input. Based on an investigation of object sizes and CPU time it returns the ideal settings for maximum thread count and work queue capacity in the thread pool. &lt;br /&gt;
&lt;br /&gt;
Let's go through an example. The following snippet shows how to use the &lt;code&gt;PoolSizeCalculator&lt;/code&gt; in a scenario of 1.0 (=100%) desired utilization and 100000 bytes maximum work queue size.&lt;br /&gt;
&lt;br /&gt;
&lt;script src="https://gist.github.com/2157558.js"&gt; &lt;/script&gt;&lt;br /&gt;
&lt;code&gt;MyPoolSizeCalculator&lt;/code&gt; extends the abstract &lt;code&gt;PoolSizeCalculator&lt;/code&gt;. You need to implement three template methods: &lt;code&gt;getCurrentThreadCPUTime&lt;/code&gt;, &lt;code&gt;creatTask&lt;/code&gt;, &lt;code&gt;createWorkQueue&lt;/code&gt;. The snippet applies standard Java Management Extensions for the CPU time measurement (line 13). If JMX isn't accurate enough, then other frameworks can be considered (e.g. &lt;a href="http://www.hyperic.com/products/sigar"&gt;SIGAR API&lt;/a&gt;). Thread pools work best when tasks are homogeneous and independent. Therefore the &lt;code&gt;createTask&lt;/code&gt;-method creates an instance of a single type of &lt;code&gt;Runnable&lt;/code&gt; task (line 17). This task will be investigated to calculate wait time to CPU time ratio. Finally, I need to create an instance of the work queue to calculate memory usage of submitted task (line 21). The output of that program shows the ideal settings for the work queue capacity and the maximum pool size (number of threads). These are the results for my examplary I/O intense &lt;code&gt;AsynchronousTask&lt;/code&gt; on a dual core machine.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="java" name="code"&gt;Target queue memory usage (bytes): 100000
createTask() produced com.schlimm.java7.nio.threadpools.AsynchronousTask which took 40 bytes in a queue
Formula: 100000 / 40
* Recommended queue capacity (bytes): 2500
Number of CPU: 2
Target utilization: 1.0
Elapsed time (nanos): 3000000000
Compute time (nanos): 906250000
Wait time (nanos): 2093750000
Formula: 2 * 1.0 * (1 + 2093750000 / 906250000)
* Optimal thread count: 6.0
&lt;/pre&gt;&lt;br /&gt;
The 'recommended queue capacity' and the 'optimal thread count' are the important values. An ideal setting for my &lt;code&gt;AsynchronousTask&lt;/code&gt; would be as follows:&lt;br /&gt;
&lt;br /&gt;
&lt;script src="https://gist.github.com/2157560.js"&gt; &lt;/script&gt;&lt;br /&gt;
Using those settings your work queue cannot grow larger then the desired 100000 bytes. And since the desired utilization is 1.0 (100%), it does not make sense to make the pool larger then 6 threads (wait time to compute time ratio is three - for each compute time intervall, three wait time intervalls follow). The results of the program largely depend on the type of tasks you process. If the tasks are homogenous and compute intense the program will likely recommend to set the pool size to the number of available CPU. But if the task has wait time, like in I/O intense tasks, the program will recomend to increase the thread count to achieve 100% utilization. Also notice, some tasks change their wait time to compute time ratio after some time of processing, e.g. if the file size of an I/O operation increases. This fact suggests to develop a self-tuning thread pool (one of my follow up blogs). In any case, you should make the thread pool sizes configurable, so that you can adjust them at runtime. &lt;br /&gt;
&lt;br /&gt;
OK, that's all in terms of robust thread pools for now. I hope you enjoyed it a little. And don't blame me if the formula isn't 100% accurate in terms of maximum pool size. As I said, it's not an exact science, it's about getting an idea of the ideal pool size.&lt;img src="http://feeds.feedburner.com/~r/blogspot/BufQX/~4/YgZK6ZnIbn8" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://niklasschlimm.blogspot.com/feeds/7010339699457913742/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://niklasschlimm.blogspot.com/2012/03/threading-stories-about-robust-thread.html#comment-form" title="13 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/5701415790759755571/posts/default/7010339699457913742?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/5701415790759755571/posts/default/7010339699457913742?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/blogspot/BufQX/~3/YgZK6ZnIbn8/threading-stories-about-robust-thread.html" title="Threading stories: about robust thread pools" /><author><name>Niklas Schlimm</name><uri>http://www.blogger.com/profile/12402045792243894660</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="24" height="32" src="http://1.bp.blogspot.com/-T7F8yoGErpc/TjlFwjgDvTI/AAAAAAAAAPo/Uqt54kYww9E/s220/Niki.JPG" /></author><thr:total>13</thr:total><feedburner:origLink>http://niklasschlimm.blogspot.com/2012/03/threading-stories-about-robust-thread.html</feedburner:origLink></entry><entry gd:etag="W/&quot;CUEHRn04fCp7ImA9WhRbEUQ.&quot;"><id>tag:blogger.com,1999:blog-5701415790759755571.post-6351047835335232663</id><published>2012-02-02T15:40:00.000+01:00</published><updated>2012-02-02T15:40:37.334+01:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2012-02-02T15:40:37.334+01:00</app:edited><category scheme="http://www.blogger.com/atom/ns#" term="Java" /><title>Java 7: A complete invokedynamic example</title><content type="html">Another blog entry in my current Java 7 series. This time it's dealing with &lt;code&gt;invokedynamic&lt;/code&gt;, a new bytecode instruction on the JVM for method invocation. The &lt;code&gt;invokedynamic&lt;/code&gt; instruction allows dynamic linkage between a call site and the receiver of the call. That means you can link the class that is performing a method call to the class (and method) that is receiving the call &lt;i&gt;at run-time&lt;/i&gt;. All the other JVM bytecode instructions for method invocation, like &lt;code&gt;invokevirtual&lt;/code&gt;, hard-wire the target type information into your compilation, i.e. into your class file. Let's look at an example. &lt;a name='more'&gt;&lt;/a&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;script src="https://gist.github.com/1723147.js"&gt;&lt;/script&gt;&lt;br /&gt;
The bytecode snippet above shows an &lt;code&gt;invokevirtual&lt;/code&gt; method call of &lt;code&gt;java.lang.String -&amp;gt; length()&lt;/code&gt; in line 20. It refers to item 65 in the contsant pool table which is a &lt;code&gt;MethodRef&lt;/code&gt; entry (see line 6). Items 42 and 66 in the constant pool table refer to the class and the method descriptor entries. As you can see, the target type and method of the &lt;code&gt;invokevirtual&lt;/code&gt; call is completely resolved and hard-wired into the bytecode. Now, let's return to &lt;code&gt;invokedynamic&lt;/code&gt;!&lt;br /&gt;
&lt;br /&gt;
It is important to notice that it is not possible to compile Java code into bytecode that contains an &lt;code&gt;invokedynamic&lt;/code&gt; instruction. Java is &lt;a href="http://docs.oracle.com/javase/7/docs/technotes/guides/vm/multiple-language-support.html#typing"&gt;statically typed&lt;/a&gt;. That means that Java performs type checking at compile time. Therefore, in Java, it is possible (and wanted!) to hard-wire all type information of method call receivers into the callers class file. The caller knows the type name of the call target, as demonstrated in our example above. The use of &lt;code&gt;invokedynamic&lt;/code&gt; - on the other hand - enables the JVM to resolve exactly that type information at run-time. This is only required (and wanted!) for dynamic languages, such as JRuby or Rhino. &lt;br /&gt;
&lt;br /&gt;
Now, suppose you want to implement a new language on the JVM that is dynamically typed. I am not suggesting you should invent *another* language on the JVM, but *suppose* you would, and *suppose* your new language should be dynamically typed. That would mean, in your new language, the linking between a caller and a receiver of a method call is performed at run-time. Since Java 7 this is possible on the bytecode level using the &lt;code&gt;invokedynamic&lt;/code&gt; instruction. &lt;br /&gt;
&lt;br /&gt;
Because I cannot create an &lt;code&gt;invokedynamic&lt;/code&gt; instruction using a Java compiler, I will create a class file that contains &lt;code&gt;invokedynamic&lt;/code&gt; myself. Once this class file is created I will run that class file's &lt;code&gt;main&lt;/code&gt; method using an ordinary &lt;code&gt;java&lt;/code&gt; launcher. How can you create a class file without a compiler? This is possible by using bytecode manipulation frameworks like &lt;a href="http://asm.ow2.org/"&gt;ASM &lt;/a&gt;or &lt;a href="http://www.csg.is.titech.ac.jp/%7Echiba/javassist/"&gt;Javassist&lt;/a&gt;.&lt;br /&gt;
&lt;br /&gt;
&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;a href="http://3.bp.blogspot.com/-03SehryB-dM/TykyTALfowI/AAAAAAAAAUE/1-5pLlZiC2I/s1600/Foto.JPG" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"&gt;&lt;img border="0" height="240" src="http://3.bp.blogspot.com/-03SehryB-dM/TykyTALfowI/AAAAAAAAAUE/1-5pLlZiC2I/s320/Foto.JPG" width="320" /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;
The following code snippet shows the &lt;code&gt;SimpleDynamicInvokerGenerator&lt;/code&gt; that can generate a class file &lt;code&gt;SimpleDynamicInvoker.class&lt;/code&gt; which contains an invokedynamic instruction.&lt;br /&gt;
&lt;br /&gt;
&lt;script src="https://gist.github.com/1710583.js"&gt;
 
&lt;/script&gt;&lt;br /&gt;
I am using &lt;a href="http://asm.ow2.org/"&gt;ASM&lt;/a&gt; here, an all purpose Java bytecode manipulation and analysis framework, to do the job of creating a correct class file format. In line 30 the &lt;code&gt;visitInvokeDynamicInsn&lt;/code&gt; creates the &lt;code&gt;invokedynamic&lt;/code&gt; instruction. Generating a class that does an &lt;code&gt;invokedynamic&lt;/code&gt; call is only half of the story. You also need some code that links the dynamic call site to the actual target, this is the real purpose of &lt;code&gt;invokedynamic&lt;/code&gt;. Here is an example.&lt;br /&gt;
&lt;br /&gt;
&lt;script src="https://gist.github.com/1710613.js"&gt;
&lt;/script&gt;&lt;br /&gt;
The bootstrap method in line 9-14 selects the actual target of the dynamic call. In our case the target is the &lt;code&gt;sayHello()&lt;/code&gt; method. To learn how the bootstrap method is linked to the &lt;code&gt;invokedynamic&lt;/code&gt; instruction we need to dive into the bytecode of &lt;code&gt;SimpleDynamicInvoker&lt;/code&gt; that we've generated with &lt;code&gt;&lt;a href="https://github.com/nschlimm/playground/blob/master/bytecode-playground/src/main/java/com/schlimm/bytecode/invokedynamic/generator/SimpleDynamicInvokerGenerator.java"&gt;SimpleDynamicInvokerGenerator&lt;/a&gt;&lt;/code&gt;. &lt;br /&gt;
&lt;br /&gt;
&lt;script src="https://gist.github.com/1710655.js"&gt;
 
&lt;/script&gt;&lt;br /&gt;
In line 49 you can see the &lt;code&gt;invokedynamic&lt;/code&gt; instruction. The logical name of the dynamic method is &lt;code&gt;runCalculation&lt;/code&gt;, this is a fictitious name. You can use any name that makes sense, also names like "+" are allowed. The instruction refers to item 20 in the contant pool table (see line 33). This in turn refers to index 0 in the &lt;code&gt;BootstrapMethods&lt;/code&gt; attribute (see line 8). There you can see the link to the &lt;code&gt;&lt;a href="https://github.com/nschlimm/playground/blob/master/bytecode-playground/src/main/java/com/schlimm/bytecode/invokedynamic/linkageclasses/SimpleDynamicLinkageExample.java"&gt;SimpleDynamicLinkageExample.bootstrapDynamic&lt;/a&gt;&lt;/code&gt; method that links the &lt;code&gt;invokedynamic&lt;/code&gt; instruction to the call target.&lt;br /&gt;
&lt;br /&gt;
Now if you call the &lt;code&gt;SimpleDynamicInvoker&lt;/code&gt; using the &lt;code&gt;java&lt;/code&gt; launcher, then the &lt;code&gt;invokedynamic&lt;/code&gt; call is executed.&lt;br /&gt;
&lt;br /&gt;
&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;a href="http://4.bp.blogspot.com/-oyp829YqfVA/TyfztHF6w_I/AAAAAAAAATs/bN2sDL_ssCI/s1600/invoke.bmp" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"&gt;&lt;img border="0" height="158" src="http://4.bp.blogspot.com/-oyp829YqfVA/TyfztHF6w_I/AAAAAAAAATs/bN2sDL_ssCI/s320/invoke.bmp" width="320" /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;
The following sequence diagram illustrates what's happening when the &lt;code&gt;SimpleDynamicInvoker&lt;/code&gt; is called using the &lt;code&gt;java&lt;/code&gt; launcher.&lt;br /&gt;
&lt;br /&gt;
&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;a href="http://4.bp.blogspot.com/-_Bmfs83zIR0/TypO1viJQ9I/AAAAAAAAAUc/XRDbp9F1cA0/s1600/Unbenannt.JPG" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"&gt;&lt;img border="0" height="240" src="http://4.bp.blogspot.com/-_Bmfs83zIR0/TypO1viJQ9I/AAAAAAAAAUc/XRDbp9F1cA0/s320/Unbenannt.JPG" width="320" /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;
The first call of &lt;code&gt;runCalculation&lt;/code&gt; using &lt;code&gt;invokedynamic&lt;/code&gt; issues a call to the &lt;code&gt;bootstrapDynamic&lt;/code&gt; method. This method does the dynamic linkage between the calling class (&lt;code&gt;SimpleDynamicInvoker&lt;/code&gt;) and the receiving class (&lt;code&gt;SimpleDynamicLinkageExample&lt;/code&gt;). The bootstrap method returns a &lt;code&gt;MethodHandle&lt;/code&gt; that targets the receiving class. This method handle is cached for repetitive invocations of the &lt;code&gt;runCalculation&lt;/code&gt; method.&lt;br /&gt;
&lt;br /&gt;
That's all in terms of &lt;code&gt;invokedynamic&lt;/code&gt;. I have some more sophisticated examples published &lt;a href="https://github.com/nschlimm/playground/tree/master/bytecode-playground/src/main/java/com/schlimm/bytecode/invokedynamic"&gt;here&lt;/a&gt; in my Git repo. I hope you've enjoyed reading this - in times of shortage!&lt;br /&gt;
&lt;br /&gt;
Cheers, Niklas&lt;br /&gt;
&lt;br /&gt;
References:&lt;br /&gt;
&lt;br /&gt;
&lt;a href="http://docs.oracle.com/javase/7/docs/technotes/guides/vm/multiple-language-support.html"&gt;http://docs.oracle.com/javase/7/docs/technotes/guides/vm/multiple-language-support.html&lt;/a&gt;&lt;br /&gt;
&lt;a href="http://asm.ow2.org/"&gt;http://asm.ow2.org/&lt;/a&gt;&lt;br /&gt;
&lt;a href="http://java.sun.com/developer/technicalArticles/DynTypeLang/"&gt;http://java.sun.com/developer/technicalArticles/DynTypeLang/&lt;/a&gt;&lt;br /&gt;
&lt;a href="http://asm.ow2.org/doc/tutorial-asm-2.0.html"&gt;http://asm.ow2.org/doc/tutorial-asm-2.0.html&lt;/a&gt;&lt;br /&gt;
&lt;a href="http://weblogs.java.net/blog/forax/archive/2011/01/07/calling-invokedynamic-java"&gt;http://weblogs.java.net/blog/forax/archive/2011/01/07/calling-invokedynamic-java&lt;/a&gt;&lt;br /&gt;
&lt;a href="http://nerds-central.blogspot.com/2011/05/performing-dynamicinvoke-from-java-step.html"&gt;http://nerds-central.blogspot.com/2011/05/performing-dynamicinvoke-from-java-step.html&lt;/a&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"&gt;
&lt;/script&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;script src="http://gist.github.com/raw/454771/gist-line-number-hack.js"&gt;
&lt;/script&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;script type="text/javascript"&gt;
addLineNumbersToAllGists()
&lt;/script&gt;&lt;img src="http://feeds.feedburner.com/~r/blogspot/BufQX/~4/Q8TGMqhZSFQ" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://niklasschlimm.blogspot.com/feeds/6351047835335232663/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://niklasschlimm.blogspot.com/2012/02/java-7-complete-invokedynamic-example.html#comment-form" title="9 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/5701415790759755571/posts/default/6351047835335232663?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/5701415790759755571/posts/default/6351047835335232663?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/blogspot/BufQX/~3/Q8TGMqhZSFQ/java-7-complete-invokedynamic-example.html" title="Java 7: A complete invokedynamic example" /><author><name>Niklas Schlimm</name><uri>http://www.blogger.com/profile/12402045792243894660</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="24" height="32" src="http://1.bp.blogspot.com/-T7F8yoGErpc/TjlFwjgDvTI/AAAAAAAAAPo/Uqt54kYww9E/s220/Niki.JPG" /></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="http://3.bp.blogspot.com/-03SehryB-dM/TykyTALfowI/AAAAAAAAAUE/1-5pLlZiC2I/s72-c/Foto.JPG" height="72" width="72" /><thr:total>9</thr:total><feedburner:origLink>http://niklasschlimm.blogspot.com/2012/02/java-7-complete-invokedynamic-example.html</feedburner:origLink></entry><entry gd:etag="W/&quot;A08DQ3c5eip7ImA9WhVTFks.&quot;"><id>tag:blogger.com,1999:blog-5701415790759755571.post-7076482920099472249</id><published>2012-01-17T17:11:00.218+01:00</published><updated>2012-03-02T07:31:12.922+01:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2012-03-02T07:31:12.922+01:00</app:edited><category scheme="http://www.blogger.com/atom/ns#" term="Java" /><title>Java 7: How to write really fast Java code</title><content type="html">When I first wrote this blog my intention was to introduce you to a class &lt;code&gt;ThreadLocalRandom&lt;/code&gt; which is new in Java 7 to generate random numbers. I have analyzed the performance of &lt;code&gt;ThreadLocalRandom&lt;/code&gt; in a series of micro-benchmarks to find out how it performs in a single threaded environment. The results were relatively surprising: although the code is very similar, &lt;code&gt;ThreadLocalRandom&lt;/code&gt; is twice as fast as &lt;code&gt;Math.random()&lt;/code&gt;! The results drew my interest and I decided to investigate this a little further. I have documented my anlysis process. It is an examplary introduction into analysis steps, technologies and some of the JVM diagnostic tools required to understand differences in the performance of small code segments. Some experience with the described toolset and technologies will enable you to write faster Java code for your specific Hotspot target environment.&lt;a name='more'&gt;&lt;/a&gt;&lt;br /&gt;
&lt;br /&gt;
OK, that's enough talk, let's get started! My machine is an ordinary Intel x86, Family 6, 3 GHz, 32-bit, dual core running Windows XP Professional.&lt;br /&gt;
&lt;br /&gt;
&lt;code&gt;Math.random()&lt;/code&gt; works on a static singleton instance of &lt;code&gt;Random&lt;/code&gt; whilst &lt;code&gt;ThreadLocalRandom -&amp;gt; current() -&amp;gt; nextDouble()&lt;/code&gt; works on a thread local instance of &lt;code&gt;ThreadLocalRandom&lt;/code&gt; which is a subclass of &lt;code&gt;Random&lt;/code&gt;. &lt;code&gt;ThreadLocal&lt;/code&gt; introduces the overhead of variable look up on each call to the &lt;code&gt;current()&lt;/code&gt;-method. Considering what I've just said, then it's really a little surprising that it's twice as fast as &lt;code&gt;Math.random()&lt;/code&gt; in a single thread, isn't it? I didn't expect such a significant difference.  &lt;br /&gt;
&lt;br /&gt;
&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;a href="http://2.bp.blogspot.com/-US7pVobCJc8/Twwf8l5lbvI/AAAAAAAAATU/WizpHW3i-kM/s1600/ThreadLocalRandom.JPG" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"&gt;&lt;img border="0" height="240" src="http://2.bp.blogspot.com/-US7pVobCJc8/Twwf8l5lbvI/AAAAAAAAATU/WizpHW3i-kM/s320/ThreadLocalRandom.JPG" width="320" /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;
Again, I am using a tiny micro-benchmarking framework presented &lt;a href="http://www.javaspecialists.eu/archive/Issue124.html"&gt;in one of Heinz blogs&lt;/a&gt;. The framework that Heinz developed takes care of several challenges in benchmarking Java programs on modern JVMs. These challenges include: warm-up, garbage collection, accuracy of Javas time API, verification of test accuracy and so forth. &lt;br /&gt;
&lt;br /&gt;
Here are my runnable benchmark classes:&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="java" name="code"&gt;public class ThreadLocalRandomGenerator implements BenchmarkRunnable {

 private double r;
 
 @Override
 public void run() {
  r = r + ThreadLocalRandom.current().nextDouble();
 }

 public double getR() {
  return r;
 }

 @Override
 public Object getResult() {
  return r;
 }
  
}

public class MathRandomGenerator implements BenchmarkRunnable {

 private double r;

 @Override
 public void run() {
  r = r + Math.random();
 }

 public double getR() {
  return r;
 }

 @Override
 public Object getResult() {
  return r;
 }
}
&lt;/pre&gt;&lt;br /&gt;
Let's run the benchmark using Heinz' framework:&lt;br /&gt;
&lt;br /&gt;
&lt;script src="https://gist.github.com/1583786.js"&gt;
 
&lt;/script&gt;&lt;br /&gt;
Notice: To make sure the JVM does not identify the code as "dead code" I return a field variable and print out the result of my benchmarking immediately. That's why my runnable classes implement an interface called &lt;a href="https://github.com/nschlimm/playground/blob/master/java7-playground/src/main/java/com/schlimm/java7/concurrency/random/BenchmarkRunnable.java"&gt;RunnableBenchmark&lt;/a&gt;. I am running this benchmark three times. The first run is in default mode, with inlining and JIT optimization enabled:&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="java" name="code"&gt;Benchmark target: MathRandomGenerator
Mean execution count: 14773594,4
Standard deviation: 180484,9
To avoid dead code coptimization: 6.4005410634212025E7
Benchmark target: ThreadLocalRandomGenerator
Mean execution count: 29861911,6
Standard deviation: 723934,46
To avoid dead code coptimization: 1.0155096190946539E8
&lt;/pre&gt;&lt;br /&gt;
Then again without JIT optimization (VM option &lt;code&gt;-Xint&lt;/code&gt;):&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="java" name="code"&gt;Benchmark target: MathRandomGenerator
Mean execution count: 963226,2
Standard deviation: 5009,28
To avoid dead code coptimization: 3296912.509302683
Benchmark target: ThreadLocalRandomGenerator
Mean execution count: 1093147,4
Standard deviation: 491,15
To avoid dead code coptimization: 3811259.7334526842
&lt;/pre&gt;&lt;br /&gt;
The last test is with JIT optimization, but with &lt;code&gt;-XX:MaxInlineSize=0&lt;/code&gt; which (almost) disables inlining:&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="java" name="code"&gt;Benchmark target: MathRandomGenerator
Mean execution count: 13789245
Standard deviation: 200390,59
To avoid dead code coptimization: 4.802723374491231E7
Benchmark target: ThreadLocalRandomGenerator
Mean execution count: 24009159,8
Standard deviation: 149222,7
To avoid dead code coptimization: 8.378231170741305E7
&lt;/pre&gt;&lt;br /&gt;
Let's interpret the results carefully: With full JVM JIT optimization the &lt;code&gt;ThreadLocalRanom&lt;/code&gt; is twice as fast as &lt;code&gt;Math.random()&lt;/code&gt;. Turning JIT optimization off shows that the two perform equally good (bad) then. Method inlining seems to make 30% of the performance difference. The other differences may be due to &lt;a href="http://www.oracle.com/technetwork/java/whitepaper-135217.html"&gt;other otimization techniques&lt;/a&gt;.&lt;br /&gt;
&lt;br /&gt;
One reason why the JIT compiler can tune &lt;code&gt;ThreadLocalRandom&lt;/code&gt; more effectively is the improved implementation of &lt;code&gt;ThreadLocalRandom.next()&lt;/code&gt;. &lt;br /&gt;
&lt;br /&gt;
&lt;pre class="java" name="code"&gt;public class Random implements java.io.Serializable {
...
    protected int next(int bits) {
        long oldseed, nextseed;
        AtomicLong seed = this.seed;
        do {
            oldseed = seed.get();
            nextseed = (oldseed * multiplier + addend) &amp;amp; mask;
        } while (!seed.compareAndSet(oldseed, nextseed));
        return (int)(nextseed &amp;gt;&amp;gt;&amp;gt; (48 - bits));
    }
...
}

public class ThreadLocalRandom extends Random {
...
    protected int next(int bits) {
        rnd = (rnd * multiplier + addend) &amp;amp; mask;
        return (int) (rnd &amp;gt;&amp;gt;&amp;gt; (48-bits));
    }
...
}
&lt;/pre&gt;&lt;br /&gt;
The first snippet shows &lt;code&gt;Random.next()&lt;/code&gt; which is used intensively in the benchmark of &lt;code&gt;Math.random()&lt;/code&gt;. Compared to &lt;code&gt;ThreadLocalRandom.next()&lt;/code&gt; the method requires significantly more instructions, although both methods do the same thing. In the &lt;code&gt;Random&lt;/code&gt; class the &lt;code&gt;seed&lt;/code&gt; variable stores a global shared state to all threads, it changes with every call to the &lt;code&gt;next()&lt;/code&gt;-method. Therefore &lt;code&gt;AtomicLong&lt;/code&gt; is required to safely access and change the &lt;code&gt;seed&lt;/code&gt; value in calls to &lt;code&gt;nextDouble()&lt;/code&gt;. &lt;code&gt;ThreadLocalRandom&lt;/code&gt; on the other hand is - well - thread local :-) The &lt;code&gt;next()&lt;/code&gt;-method does not have to be thread safe and can use an ordinary &lt;code&gt;long&lt;/code&gt; variable as seed value. &lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;About method inlining and &lt;code&gt;ThreadLocalRandom&lt;/code&gt;&lt;br /&gt;
&lt;/b&gt;&lt;br /&gt;
One very effective JIT optimization is method inlining. In hot paths executed frequently the hotspot compiler decides to inline the code of called methods (child method) into the callers method (parent method). "Inlining has important benefits. It dramatically reduces the dynamic frequency of method invocations, which saves the time needed to perform those method invocations. But even more importantly, inlining produces much larger blocks of code for the optimizer to work on. This creates a situation that significantly increases the effectiveness of traditional compiler optimizations, overcoming a major obstacle to increased Java programming language performance."&lt;br /&gt;
&lt;br /&gt;
Since &lt;a href="http://download.java.net/jdk7/archive/b142/binaries/"&gt;OpenJDK 7 debug builds&lt;/a&gt; you can monitor method inlining by using diagnostic JVM options. Running the code with '&lt;code&gt;-XX:+UnlockDiagnosticVMOptions -XX:+PrintInlining&lt;/code&gt;' will show the inlining efforts of the JIT compiler. Here are the relevant sections of the output for &lt;code&gt;Math.random()&lt;/code&gt; benchmark:&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="java" name="code"&gt;@ 13   java.util.Random::nextDouble (24 bytes)
  @ 3   java.util.Random::next (47 bytes)   callee is too large
  @ 13   java.util.Random::next (47 bytes)   callee is too large
&lt;/pre&gt;&lt;br /&gt;
The JIT compiler cannot inline the &lt;code&gt;Random.next()&lt;/code&gt; method that is called in &lt;code&gt;Random.nextDouble()&lt;/code&gt;. This is the inlining output of &lt;code&gt;ThreaLocalRandom.next()&lt;/code&gt;:&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="java" name="code"&gt;@ 8   java.util.Random::nextDouble (24 bytes)
  @ 3   java.util.concurrent.ThreadLocalRandom::next (31 bytes)
  @ 13   java.util.concurrent.ThreadLocalRandom::next (31 bytes)
&lt;/pre&gt;&lt;br /&gt;
Due to the fact that the &lt;code&gt;next()&lt;/code&gt;-method is shorter (31 bytes) it can be inlined. Because the &lt;code&gt;next()&lt;/code&gt;-method is called intensively in both benchmarks this log suggests that method inlining may be one reason why &lt;code&gt;ThreadLocalRandom&lt;/code&gt; performs significantly faster. &lt;br /&gt;
&lt;br /&gt;
To verify that and to find out more it is required to deep dive into assembly code. With Java 7 JDKs it is possible to print out assembly code into the console. See &lt;a href="https://wikis.oracle.com/display/HotSpotInternals/PrintAssembly"&gt;here&lt;/a&gt; on how to enable &lt;code&gt;-XX:+PrintAssembly&lt;/code&gt; VM Option. The option will print out the JIT optimized code, that means you can see the code the JVM actually executes. I have copied the relevant assembly code into the links below.&lt;br /&gt;
&lt;br /&gt;
Assembly code of ThreadLocalRandomGenerator.run() &lt;a href="https://gist.github.com/1583170"&gt;here&lt;/a&gt;.&lt;br /&gt;
Assembly code of MathRandomGenerator.run() &lt;a href="https://gist.github.com/1583188"&gt;here&lt;/a&gt;.&lt;br /&gt;
Assembly code of Random.next() called by Math.random() &lt;a href="https://gist.github.com/1583197"&gt;here&lt;/a&gt;.&lt;br /&gt;
&lt;br /&gt;
&lt;a href="http://en.wikipedia.org/wiki/X86_instruction_listings"&gt;Assembly code&lt;/a&gt; is machine-specific and low level code, it's more complicated to read then &lt;a href="http://en.wikipedia.org/wiki/Java_bytecode_instruction_listings"&gt;bytecode&lt;/a&gt;. Let's try to verify that method inlining has a relevant effect on performance in my benchmarks and: are there other obvious differences how the JIT compiler treats &lt;code&gt;ThreadLocalRandom&lt;/code&gt; and &lt;code&gt;Math.random&lt;/code&gt;()? In &lt;code&gt;ThreadLocalRandomGenerator.run()&lt;/code&gt; there is no procedure call to any of the subroutines like &lt;code&gt;Random.nextDouble()&lt;/code&gt; or &lt;code&gt;ThreatLocalRandom.next()&lt;/code&gt;. There is only one virtual (hence expensive) method call to &lt;code&gt;ThreadLocal.get()&lt;/code&gt; visible (see line 35 in &lt;code&gt;ThreadLocalRandomGenerator.run()&lt;/code&gt; assembly). All the other code is inlined into &lt;code&gt;ThreadLocalRandomGenerator.run()&lt;/code&gt;. In the case of &lt;code&gt;MathRandomGenerator.run()&lt;/code&gt; there are &lt;i&gt;two&lt;/i&gt; virtual method calls to &lt;code&gt;Random.next()&lt;/code&gt; (see block B4 line 204 ff. in the assembly code of &lt;code&gt;MathRandomGenerator.run()&lt;/code&gt;). This fact confirms our suspicion that method inlining is one important root cause for the performance difference. Further more, due to synchronization hassle, there are considerably more (and some expensive!) assembly instructions required in &lt;code&gt;Random.next()&lt;/code&gt; which is also counterproductive in terms of execution speed.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Understanding the overhead of the &lt;code&gt;invokevirtual&lt;/code&gt; instruction&lt;/b&gt;&lt;br /&gt;
&lt;br /&gt;
So why is (virtual) method invocation expensive and method inlining so effective? The pointer of &lt;code&gt;invokevirtual&lt;/code&gt; instructions is not an offset of a concrete method in a class instance. The compiler does not know the internal layout of a class instance. Instead, it generates symbolic references to the methods of an instance, which are stored in the runtime constant pool. Those runtime constant pool items are resolved &lt;i&gt;at run time&lt;/i&gt; to determine the actual method location. This dynamic (run-time) binding requires verification, preparation and resolution which can considerably effect performance. (see &lt;a href="http://java.sun.com/docs/books/jvms/second_edition/html/Compiling.doc.html#14787"&gt;Invoking Methods&lt;/a&gt; and &lt;a href="http://java.sun.com/docs/books/jvms/second_edition/html/Concepts.doc.html#22574"&gt;Linking&lt;/a&gt; in the JVM Spec for details)&lt;br /&gt;
&lt;br /&gt;
That's all for now. The disclaimer: Of course, the list of topics you need to understand to solve performance riddles is endless. There is a lot more to understand then micro-benchmarking, JIT optimization, method inlining, java byte code, assemby language and so forth. Also, there are lot more root causes for performance differences then just virtual method calls or expensive thread synchronization instructions. However, I think the topics I have introduced are a good start into such deep diving stuff. Looking forward to critical and enjoyable comments!&lt;br /&gt;
&lt;br /&gt;
Cheers,&lt;br /&gt;
Niklas&lt;img src="http://feeds.feedburner.com/~r/blogspot/BufQX/~4/JRly8FFWEuI" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://niklasschlimm.blogspot.com/feeds/7076482920099472249/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://niklasschlimm.blogspot.com/2012/01/java-7-how-to-write-really-fast-java.html#comment-form" title="20 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/5701415790759755571/posts/default/7076482920099472249?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/5701415790759755571/posts/default/7076482920099472249?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/blogspot/BufQX/~3/JRly8FFWEuI/java-7-how-to-write-really-fast-java.html" title="Java 7: How to write really fast Java code" /><author><name>Niklas Schlimm</name><uri>http://www.blogger.com/profile/12402045792243894660</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="24" height="32" src="http://1.bp.blogspot.com/-T7F8yoGErpc/TjlFwjgDvTI/AAAAAAAAAPo/Uqt54kYww9E/s220/Niki.JPG" /></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="http://2.bp.blogspot.com/-US7pVobCJc8/Twwf8l5lbvI/AAAAAAAAATU/WizpHW3i-kM/s72-c/ThreadLocalRandom.JPG" height="72" width="72" /><thr:total>20</thr:total><feedburner:origLink>http://niklasschlimm.blogspot.com/2012/01/java-7-how-to-write-really-fast-java.html</feedburner:origLink></entry><entry gd:etag="W/&quot;A0AFRHw9eSp7ImA9WhRWEUo.&quot;"><id>tag:blogger.com,1999:blog-5701415790759755571.post-4611822641687368099</id><published>2011-12-28T19:13:00.009+01:00</published><updated>2011-12-29T18:28:35.261+01:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2011-12-29T18:28:35.261+01:00</app:edited><category scheme="http://www.blogger.com/atom/ns#" term="Java" /><title>Java 7: Understanding the Phaser</title><content type="html">Java 7 introduces a flexible thread synchronization mechanism called &lt;code&gt;Phaser&lt;/code&gt;. If you need to wait for threads to arrive before you can continue or start another set of tasks, then &lt;code&gt;Phaser&lt;/code&gt; is a good choice. Here is the listing, everything is explained step-by-step.&lt;br /&gt;
&lt;a name='more'&gt;&lt;/a&gt;&lt;pre class="java" name="code"&gt;import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.Phaser;

public class PhaserExample {

 public static void main(String[] args) throws InterruptedException {

  List&lt;runnable&gt; tasks = new ArrayList&amp;lt;&amp;gt;();

  for (int i = 0; i &amp;lt; 2; i++) {
   Runnable runnable = new Runnable() {
    @Override
    public void run() {
     int a = 0, b = 1;
     for (int i = 0; i &amp;lt; 2000000000; i++) {
      a = a + b;
      b = a - b;
     }
    }
   };

   tasks.add(runnable);

  }

  new PhaserExample().runTasks(tasks);

 }

 void runTasks(List&lt;runnable&gt; tasks) throws InterruptedException {

  final Phaser phaser = new Phaser(1) {
   protected boolean onAdvance(int phase, int registeredParties) {
    return phase &amp;gt;= 1 || registeredParties == 0;
   }
  };

  for (final Runnable task : tasks) {
   phaser.register();
   new Thread() {
    public void run() {
     do {
      phaser.arriveAndAwaitAdvance();
      task.run();
     } while (!phaser.isTerminated());
    }
   }.start();
   Thread.sleep(500);
  }

  phaser.arriveAndDeregister();

 }

}
&lt;/pre&gt;&lt;br /&gt;
This example allows to learn a lot about the internals of a &lt;code&gt;Phaser&lt;/code&gt;. Let's go through the code:&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Line 8-26&lt;/b&gt;: The &lt;code&gt;main&lt;/code&gt;-Method that creates two &lt;code&gt;Runnable&lt;/code&gt; tasks&lt;br /&gt;
&lt;b&gt;Line 28&lt;/b&gt;: Task list is passed to the &lt;code&gt;runTasks&lt;/code&gt;-Method&lt;br /&gt;
&lt;br /&gt;
The &lt;code&gt;runTasks&lt;/code&gt;-Method actually uses a &lt;code&gt;Phaser&lt;/code&gt; to synchronize the tasks in a way that each task in the list needs to arrive at the barrier before they are executed in parallel. The task list is executed twice. The first cycle is started when both threads arrived at the barrier (see image mark 1). The second cycle is started when both threads arrived at the barrier (see image mark 2).&lt;br /&gt;
&lt;br /&gt;
&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;a href="http://3.bp.blogspot.com/-GWdkIwe1_7w/TvtA1mU7noI/AAAAAAAAATI/8jBsUiGQaJk/s1600/Unbenannt.JPG" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"&gt;&lt;img border="0" height="240" src="http://3.bp.blogspot.com/-GWdkIwe1_7w/TvtA1mU7noI/AAAAAAAAATI/8jBsUiGQaJk/s320/Unbenannt.JPG" width="320" /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;
&lt;blockquote style="background-color: #cfe2f3;"&gt;Notice: "party" is a term in the &lt;code&gt;Phaser&lt;/code&gt; context that is equivalent to what we mean by a thread. When one party arrives, then one thread arrived at the synchronization barrier.&lt;/blockquote&gt;&lt;br /&gt;
&lt;b&gt;Line 34&lt;/b&gt;: create a &lt;code&gt;Phaser&lt;/code&gt; that has one registered party (this means: at this time phaser expects one thread=party to arrive before it can start the execution cycle)&lt;br /&gt;
&lt;b&gt;Line 35&lt;/b&gt;: implement the &lt;code&gt;onAdvance&lt;/code&gt;-Method to explain that this task list is executed twice (done by: Line 36 says that it returns true if phase is equal or higher then 1)&lt;br /&gt;
&lt;b&gt;Line 40&lt;/b&gt;: iterate over the list of tasks&lt;br /&gt;
&lt;b&gt;Line 41&lt;/b&gt;: register this thread with the &lt;code&gt;Phaser&lt;/code&gt;. Notice that a &lt;code&gt;Phaser&lt;/code&gt; instance does not know the task instances. &lt;span style="background-color: #ffe599;"&gt;It's a simple counter of registered, unarrived and arrived parties, shared across participating threads.&lt;/span&gt; If two parties are registered then two parties must arrive at the phaser to be able to start the first cycle.&lt;br /&gt;
&lt;b&gt;Line 45&lt;/b&gt;: tell the thread to wait at the barrier until the arrived parties equal the registered parties&lt;br /&gt;
&lt;b&gt;Line 50&lt;/b&gt;: Just for demonstration purposes, this line delays execution. The &lt;a href="https://github.com/nschlimm/playground/blob/master/java7-playground/src/main/java/com/schlimm/java7/concurrency/phaser/PhaserExample.java"&gt;original code snippet&lt;/a&gt; prints internal infos about the Phaser state to standard out.&lt;br /&gt;
&lt;b&gt;Line 51&lt;/b&gt;: two tasks are registered, in total three parties are registered.&lt;br /&gt;
&lt;b&gt;Line 53&lt;/b&gt;: deregister one party. This results in two registered parties and two arrived parties. This causes the threads waiting (Line 45) to execute the first cycle. (in fact the third party arrived while three were registered - but it does not make a difference)&lt;br /&gt;
&lt;br /&gt;
&lt;a href="https://github.com/nschlimm/playground/blob/master/java7-playground/src/main/java/com/schlimm/java7/concurrency/phaser/PhaserExample.java"&gt;The original code snippet&lt;/a&gt; stored in my Git repository creates the following output:&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="java" name="code"&gt;After phaser init -&amp;gt; Registered: 1 - Unarrived: 1 - Arrived: 0 - Phase: 0
After register -&amp;gt; Registered: 2 - Unarrived: 2 - Arrived: 0 - Phase: 0
After arrival -&amp;gt; Registered: 2 - Unarrived: 1 - Arrived: 1 - Phase: 0
After register -&amp;gt; Registered: 3 - Unarrived: 2 - Arrived: 1 - Phase: 0
After arrival -&amp;gt; Registered: 3 - Unarrived: 1 - Arrived: 2 - Phase: 0
Before main thread arrives and deregisters -&amp;gt; Registered: 3 - Unarrived: 1 - Arrived: 2 - Phase: 0
On advance -&amp;gt; Registered: 2 - Unarrived: 0 - Arrived: 2 - Phase: 0
After main thread arrived and deregistered -&amp;gt; Registered: 2 - Unarrived: 2 - Arrived: 0 - Phase: 1
Main thread will terminate ...
Thread-0:go  :Wed Dec 28 16:09:16 CET 2011
Thread-1:go  :Wed Dec 28 16:09:16 CET 2011
Thread-0:done:Wed Dec 28 16:09:20 CET 2011
Thread-1:done:Wed Dec 28 16:09:20 CET 2011
On advance -&amp;gt; Registered: 2 - Unarrived: 0 - Arrived: 2 - Phase: 1
Thread-0:go  :Wed Dec 28 16:09:20 CET 2011
Thread-1:go  :Wed Dec 28 16:09:20 CET 2011
Thread-1:done:Wed Dec 28 16:09:23 CET 2011
Thread-0:done:Wed Dec 28 16:09:23 CET 2011
&lt;/pre&gt;&lt;br /&gt;
&lt;b&gt;Line 1&lt;/b&gt;: when the &lt;code&gt;Phaser&lt;/code&gt; is initialized in line 34 of the code snippet then one party is registered and none arrived&lt;br /&gt;
&lt;b&gt;Line 2&lt;/b&gt;: after the first thread is registered in Line 41 in the code example there are two registered parties and two unarrived parties. Since no thread reached the barrier yet, no party is arrived.&lt;br /&gt;
&lt;b&gt;Line 3&lt;/b&gt;: the first thread arrives and waits at the barrier (line 45 in the code snippet)&lt;br /&gt;
&lt;b&gt;Line 4&lt;/b&gt;: register the second thread, three registered, two unarrived, one arrived&lt;br /&gt;
&lt;b&gt;Line 5&lt;/b&gt;: the second thread arrived at the barrier, hence two arrived now&lt;br /&gt;
&lt;b&gt;Line 7&lt;/b&gt;: one party is deregistered in the code line 53 of the code example, therefore &lt;code&gt;onAdvance&lt;/code&gt;-Method is called and returns &lt;code&gt;false&lt;/code&gt;. This starts the first cycle since registered parties equals arrived parties (i.e. two). Phase 1 is started -&amp;gt; cycle one (see image mark 1)&lt;br /&gt;
&lt;b&gt;Line 8&lt;/b&gt;: since all threads are notified and start their work, two parties are unarrived again, non arrived&lt;br /&gt;
&lt;b&gt;Line 14&lt;/b&gt;: After the threads executed their tasks once they arrive again (code line 45) the &lt;code&gt;onAdvance&lt;/code&gt;-Method is called, now the 2nd cycle is executed&lt;br /&gt;
&lt;br /&gt;
OK, go through it and look into my comments in &lt;a href="https://github.com/nschlimm/playground/blob/master/java7-playground/src/main/java/com/schlimm/java7/concurrency/phaser/PhaserExample.java"&gt;the original code snippet&lt;/a&gt; to learn more.&lt;img src="http://feeds.feedburner.com/~r/blogspot/BufQX/~4/i0sYti88Rxk" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://niklasschlimm.blogspot.com/feeds/4611822641687368099/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://niklasschlimm.blogspot.com/2011/12/java-7-understanding-phaser.html#comment-form" title="5 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/5701415790759755571/posts/default/4611822641687368099?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/5701415790759755571/posts/default/4611822641687368099?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/blogspot/BufQX/~3/i0sYti88Rxk/java-7-understanding-phaser.html" title="Java 7: Understanding the Phaser" /><author><name>Niklas Schlimm</name><uri>http://www.blogger.com/profile/12402045792243894660</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="24" height="32" src="http://1.bp.blogspot.com/-T7F8yoGErpc/TjlFwjgDvTI/AAAAAAAAAPo/Uqt54kYww9E/s220/Niki.JPG" /></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="http://3.bp.blogspot.com/-GWdkIwe1_7w/TvtA1mU7noI/AAAAAAAAATI/8jBsUiGQaJk/s72-c/Unbenannt.JPG" height="72" width="72" /><thr:total>5</thr:total><feedburner:origLink>http://niklasschlimm.blogspot.com/2011/12/java-7-understanding-phaser.html</feedburner:origLink></entry><entry gd:etag="W/&quot;D0IMSXk5fSp7ImA9WhRXEE8.&quot;"><id>tag:blogger.com,1999:blog-5701415790759755571.post-6008953617994921424</id><published>2011-12-15T18:02:00.003+01:00</published><updated>2011-12-16T09:53:08.725+01:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2011-12-16T09:53:08.725+01:00</app:edited><category scheme="http://www.blogger.com/atom/ns#" term="Java" /><category scheme="http://www.blogger.com/atom/ns#" term="dip-framework" /><title>Java 7: Fork and join decomposable input pattern</title><content type="html">In my &lt;a href="http://niklasschlimm.blogspot.com/2011/12/java-7-fork-and-join-and-jar-jam.html"&gt;recent blog&lt;/a&gt; I have introduced the fork and join framework of Java 7. This blog presents a little framework on top of raw fork and join. The framework implements the decomposable input pattern (dip) - which originated from my own laziness when I was using the framework a couple of times. I have realized that I was writing the same code every time when I was implementing a slightly different use case. And you know, let's write a little peace of software that I can reuse. The decomposable input pattern framwork was born. &lt;br /&gt;
&lt;br /&gt;
&lt;a name='more'&gt;&lt;/a&gt;You can &lt;a href="https://github.com/nschlimm/playground/blob/master/forkjoindip-project-build/forkjoindip-project-1.0-SNAPSHOT.jar?raw=true"&gt;download the binary here&lt;/a&gt;.&lt;br /&gt;
The &lt;a href="http://nschlimm.github.com/playground/forkjoindip-project-build/javadoc/apidocs/index.html"&gt;API-documentation is hosted here&lt;/a&gt;.&lt;br /&gt;
And the &lt;a href="https://github.com/nschlimm/playground/blob/master/forkjoindip-project-build/forkjoindip-project-1.0-SNAPSHOT-sources.jar?raw=true"&gt;sources are also available here&lt;/a&gt;.&lt;br /&gt;
&lt;br /&gt;
Now what's different when you use that framework? I'd say the difference is that the dip-framework follows good &lt;a href="http://www.objectmentor.com/resources/articles/Principles_and_Patterns.pdf"&gt;OO design principles&lt;/a&gt;, like the open-closed-principle that says: "A module should be open for extension but closed for modification." In other words I have seperated concerns in a fork and join scenario to make the whole more flexible and easy to change.&lt;br /&gt;
&lt;br /&gt;
In my last blog I presented a code snippet that illustrated how to use plain fork and join to calculate offers of car insurances. Let's see how this can be done using my dip-framwork.&lt;br /&gt;
&lt;br /&gt;
The input to the proposal calculation is - well - a list of proposals :-) In the dip framework you wrap the input of a &lt;code&gt;ForkJoinTask&lt;/code&gt; into a subclass of &lt;code&gt;DecomposableInput&lt;/code&gt;. The name originates from the fact that input to  &lt;code&gt;ForkJoinTask&lt;/code&gt; is decomposable. Here is the snippet:&lt;br /&gt;
&lt;br /&gt;
&lt;script src="https://gist.github.com/1481682.js"&gt;
 
&lt;/script&gt;&lt;br /&gt;
&lt;br /&gt;
The class wraps the raw input to &lt;code&gt;ForkJoinTask&lt;/code&gt; and provides a method how that input can be decomposed. Also, it provides a method &lt;code&gt;computeDirectly()&lt;/code&gt; that can decide on whether this input needs further decomposition to be small enough for direct computation.&lt;br /&gt;
&lt;br /&gt;
The output of proposal calculation is a list of maps of prices. If you have four input proposals, you'll get a list of four maps with various prices. In the dip framework, you wrap the output into a subclass of &lt;code&gt;ComposableResult&lt;/code&gt;.&lt;br /&gt;
&lt;br /&gt;
&lt;script src="https://gist.github.com/1481730.js"&gt;
 
&lt;/script&gt;&lt;br /&gt;
&lt;br /&gt;
The class implements the &lt;code&gt;compose&lt;/code&gt; method that can compose an atomic  result of a computation into the existing raw result. It returns a &lt;code&gt;ComposableResult&lt;/code&gt; instance that holds the new composition.&lt;br /&gt;
&lt;br /&gt;
I agree it's a little abtsract. Not only that concurrency is inherently complex. I am also putting another abstraction onto it. But once you've used the framework you'll realize the strength. So stay tuned, we're almost finnished :-)&lt;br /&gt;
&lt;br /&gt;
Now, you have an input and an ouptut and the last thing you need is a computation object. In my example that's the pricing engine. To connect the pricing engine to the dip framework, you'll need to implement a subclass of &lt;code&gt;ComputationActivityBridge&lt;/code&gt;. &lt;br /&gt;
&lt;br /&gt;
&lt;script src="https://gist.github.com/1481754.js"&gt;
 
&lt;/script&gt;&lt;br /&gt;
&lt;br /&gt;
The PricingEngineBridge implements the &lt;code&gt;compute&lt;/code&gt; method that calls the pricing engine. It translates the &lt;code&gt;DecomposableInput&lt;/code&gt; into an input that the pricing engine accepts. And it creates an instance of &lt;code&gt;ComposableResult&lt;/code&gt; that contains the output of the pricing engine.&lt;br /&gt;
&lt;br /&gt;
Last thing to do is to get the stuff started.&lt;br /&gt;
&lt;br /&gt;
&lt;script src="https://gist.github.com/1481770.js"&gt;
 
&lt;/script&gt;&lt;br /&gt;
&lt;br /&gt;
The example creates an instance of &lt;code&gt;GenericRecursiveTask&lt;/code&gt; and passes the &lt;code&gt;ListOfProposals&lt;/code&gt; as well as the &lt;code&gt;PricingEngineBrige&lt;/code&gt; as input. If you pass that to the &lt;code&gt;ForkJoinPool&lt;/code&gt; then you receive an instance of &lt;code&gt;ListOfPrices&lt;/code&gt; as ouput.&lt;br /&gt;
&lt;br /&gt;
What's the advantage when you use the dip-framework? For instance:&lt;br /&gt;
&lt;br /&gt;
- you could pass arbitrary processing input to &lt;code&gt;GenericRecursiveTask&lt;/code&gt; by implementing a subclass of &lt;code&gt;DecomposableInput&lt;/code&gt;&lt;br /&gt;
- you could implement your own custom &lt;code&gt;RecursiveTask&lt;/code&gt; the same way I have implemented &lt;code&gt;GenericRecursiveTask&lt;/code&gt; and pass the proposals and the &lt;code&gt;PricingEngineBridge&lt;/code&gt; to that task&lt;br /&gt;
- you could implement a custom &lt;code&gt;ForkAndJoinProcessor&lt;/code&gt; and use that by subclassing &lt;code&gt;GenericRecursiveTask&lt;/code&gt;: that way you can control the creation of subtask and their distribution across threads&lt;br /&gt;
- you could exchange the processing activity (here: &lt;code&gt;PricingEngineBridge&lt;/code&gt;) by implementing a custom &lt;code&gt;ComputationActivityBridge&lt;/code&gt; and try alternative pricing engines or make something completely different then calculating prices ...&lt;br /&gt;
&lt;br /&gt;
I think I have made my point: the whole is closed for modification, but open for extention now.&lt;br /&gt;
&lt;br /&gt;
The complete example code is &lt;a href="https://github.com/nschlimm/playground/tree/master/java7-playground/src/main/java/com/schlimm/java7/concurrency/forkjoin/dippricingengine"&gt;here in my git repository&lt;/a&gt;.&lt;br /&gt;
&lt;br /&gt;
Let me know if you like it. Looking forward to critical and enjoyable comments.&lt;br /&gt;
&lt;br /&gt;
Cheers, Niklas&lt;img src="http://feeds.feedburner.com/~r/blogspot/BufQX/~4/Vbi5DapaOqA" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://niklasschlimm.blogspot.com/feeds/6008953617994921424/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://niklasschlimm.blogspot.com/2011/12/java-7-fork-and-join-decomposable-input.html#comment-form" title="5 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/5701415790759755571/posts/default/6008953617994921424?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/5701415790759755571/posts/default/6008953617994921424?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/blogspot/BufQX/~3/Vbi5DapaOqA/java-7-fork-and-join-decomposable-input.html" title="Java 7: Fork and join decomposable input pattern" /><author><name>Niklas Schlimm</name><uri>http://www.blogger.com/profile/12402045792243894660</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="24" height="32" src="http://1.bp.blogspot.com/-T7F8yoGErpc/TjlFwjgDvTI/AAAAAAAAAPo/Uqt54kYww9E/s220/Niki.JPG" /></author><thr:total>5</thr:total><feedburner:origLink>http://niklasschlimm.blogspot.com/2011/12/java-7-fork-and-join-decomposable-input.html</feedburner:origLink></entry><entry gd:etag="W/&quot;C0INSXg5fSp7ImA9WhRQFk8.&quot;"><id>tag:blogger.com,1999:blog-5701415790759755571.post-1380924384509876542</id><published>2011-12-09T16:01:00.010+01:00</published><updated>2011-12-11T17:39:58.625+01:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2011-12-11T17:39:58.625+01:00</app:edited><category scheme="http://www.blogger.com/atom/ns#" term="Java" /><title>Java 7: Fork and join and the jam jar</title><content type="html">Another Java 7 blog, this time it's about the new concurrency utilities. It's about plain fork and join in particular. Everything is explained with a straight code example. Compared to Project Coin concurrency is an inherently complex topic. The code example is a little more complex. Let's get started.&lt;br /&gt;
&lt;br /&gt;
&lt;a name='more'&gt;&lt;/a&gt;&lt;b&gt;The Fork and Join Executor Service&lt;br /&gt;
&lt;/b&gt;&lt;br /&gt;
Fork and join employs an efficient task scheduling algorithm that ensures optimized resource usage (memory and cpu) on multi core machines. That algorithm is known as "&lt;a href="http://supertech.csail.mit.edu/papers/steal.pdf"&gt;work stealing&lt;/a&gt;". Idle threads in a fork join pool attempt to find and execute subtasks created by other active threads. This is very efficient 'cause larger units get divided into smaller units of work that get distributed accross all active threads (and CPU's). Here is an analogy to explain the strength of fork and join algorithms: if you have a jam jar and you fill it with ping-pong balls, there is a lot air left in the glass. Think of the air as unused CPU resource. If you fill your jam jar with peas (or sand) there is less air in the glass. Fork and join is like filling the jam jar with peas. There is also more volume in your glass using peas, 'cause there is less air (less waste). Fork and join algorithms always ensure an optimal (smaller) number of active threads then work sharing algorithms. This is for the same "peas reason". Think of the jam jar being your thread pool and the peas are your tasks. With fork and join you can host more tasks (and complete volume) with the same amount of threads (in the same jam jar).&lt;br /&gt;
&lt;br /&gt;
&lt;table align="center" cellpadding="0" cellspacing="0" class="tr-caption-container" style="margin-left: auto; margin-right: auto; text-align: center;"&gt;&lt;tbody&gt;
&lt;tr&gt;&lt;td style="text-align: center;"&gt;&lt;a href="http://2.bp.blogspot.com/-cFBcJWoVgwo/TuIgkszj6VI/AAAAAAAAASM/YrU4mmeyH9U/s1600/weird.JPG" imageanchor="1" style="margin-left: auto; margin-right: auto;"&gt;&lt;img border="0" height="172" src="http://2.bp.blogspot.com/-cFBcJWoVgwo/TuIgkszj6VI/AAAAAAAAASM/YrU4mmeyH9U/s320/weird.JPG" width="267" /&gt;&lt;/a&gt;&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td class="tr-caption" style="text-align: center;"&gt;Image 1: Fork and join in the jam jar&lt;/td&gt;&lt;/tr&gt;
&lt;/tbody&gt;&lt;/table&gt;&lt;br /&gt;
Here is a plain fork and join code example:&lt;br /&gt;
&lt;br /&gt;
&lt;script src="https://gist.github.com/1451620.js"&gt;
 
&lt;/script&gt;&lt;br /&gt;
&lt;br /&gt;
Fork and join tasks always have a similar typical fork and join control flow. In my example I do want to calculate the prices for a list of car insurance offers. Let's go through the example.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Line 10&lt;/b&gt;: Fork and join tasks extend &lt;code&gt;RecursiveTask&lt;/code&gt; or &lt;code&gt;RecursiveAction&lt;/code&gt;. Tasks do return a result, actions doesn't. &lt;code&gt;RecursiveTask&lt;/code&gt;s allow to specify the return type using generics. The result of my example is a &lt;code&gt;List&lt;/code&gt; of &lt;code&gt;Map&lt;/code&gt;s which contain the prices for the car insurance covers. One map of prices for each proposal. &lt;br /&gt;
&lt;b&gt;Line 12&lt;/b&gt;: The task will calculate prices for proposals.&lt;br /&gt;
&lt;b&gt;Line 22&lt;/b&gt;: Fork and join tasks implement the &lt;code&gt;compute&lt;/code&gt; method. Again, the &lt;code&gt;compute&lt;/code&gt; method returns a list of maps that contain prices. If there are four proposals in the input list, then there will be four maps of prices.&lt;br /&gt;
&lt;b&gt;Line 24-26&lt;/b&gt;: Is the task stack (list of proposals) small enough to compute directly? If yes, then compute in this thread, which means call the pricing engine to calculate the proposal. If no, continue: split the work and call task recursively.&lt;br /&gt;
&lt;b&gt;Line 31&lt;/b&gt;: Determine where to split the list.&lt;br /&gt;
&lt;b&gt;Line 33&lt;/b&gt;: Create a new task for the first part of the split list.&lt;br /&gt;
&lt;b&gt;Line 34&lt;/b&gt;: Fork that task: allow some other thread to perform that smaller subtask. That thread will call &lt;code&gt;compute&lt;/code&gt; recursively on that subtask instance. &lt;br /&gt;
&lt;b&gt;Line 35&lt;/b&gt;: Create a new task for the second part of the split list.&lt;br /&gt;
&lt;b&gt;Line 36&lt;/b&gt;: Prepare the composed result list of the two devided subtask (you need to compose the results of the two subtwasks into a single result of the parent task)&lt;br /&gt;
&lt;b&gt;Line 37&lt;/b&gt;: Compute the second subtask in this current thread and add the result to the result list.&lt;br /&gt;
&lt;b&gt;Line 38&lt;/b&gt;: In the meantime the first subtask f1 was computed by some other thread. Join the result of the first subtask into the composed result list. &lt;br /&gt;
&lt;b&gt;Line 39&lt;/b&gt;: Return the composed result.&lt;br /&gt;
&lt;br /&gt;
You need to start the fork and join task. &lt;br /&gt;
&lt;b&gt;&lt;br /&gt;
Line 49&lt;/b&gt;: Create the main fork and join task with the initial list of proposals.&lt;br /&gt;
&lt;b&gt;Line 53&lt;/b&gt;: Create a fork and join thread pool.&lt;br /&gt;
&lt;b&gt;Line 55&lt;/b&gt;: Submit the main task to the fork and join pool.&lt;br /&gt;
&lt;br /&gt;
That's it. You can look into the complete code &lt;a href="https://github.com/nschlimm/playground/tree/master/java7-playground/src/main/java/com/schlimm/java7/concurrency/forkjoin/pricingengine"&gt;here&lt;/a&gt;. You'll need the &lt;a href="https://github.com/nschlimm/playground/blob/master/java7-playground/src/main/java/com/schlimm/java7/concurrency/forkjoin/pricingengine/PricingEngine.java"&gt;PricingEngine.java&lt;/a&gt; and the &lt;a href="https://github.com/nschlimm/playground/blob/master/java7-playground/src/main/java/com/schlimm/java7/concurrency/forkjoin/pricingengine/Proposal.java"&gt;Proposal.java&lt;/a&gt;.&lt;br /&gt;
&lt;br /&gt;
&lt;script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"&gt;
&lt;/script&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;script src="http://gist.github.com/raw/454771/gist-line-number-hack.js"&gt;
&lt;/script&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;script type="text/javascript"&gt;
addLineNumbersToAllGists()
&lt;/script&gt;&lt;img src="http://feeds.feedburner.com/~r/blogspot/BufQX/~4/a0FcGsULbi4" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://niklasschlimm.blogspot.com/feeds/1380924384509876542/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://niklasschlimm.blogspot.com/2011/12/java-7-fork-and-join-and-jar-jam.html#comment-form" title="3 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/5701415790759755571/posts/default/1380924384509876542?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/5701415790759755571/posts/default/1380924384509876542?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/blogspot/BufQX/~3/a0FcGsULbi4/java-7-fork-and-join-and-jar-jam.html" title="Java 7: Fork and join and the jam jar" /><author><name>Niklas Schlimm</name><uri>http://www.blogger.com/profile/12402045792243894660</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="24" height="32" src="http://1.bp.blogspot.com/-T7F8yoGErpc/TjlFwjgDvTI/AAAAAAAAAPo/Uqt54kYww9E/s220/Niki.JPG" /></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="http://2.bp.blogspot.com/-cFBcJWoVgwo/TuIgkszj6VI/AAAAAAAAASM/YrU4mmeyH9U/s72-c/weird.JPG" height="72" width="72" /><thr:total>3</thr:total><feedburner:origLink>http://niklasschlimm.blogspot.com/2011/12/java-7-fork-and-join-and-jar-jam.html</feedburner:origLink></entry><entry gd:etag="W/&quot;CkQASHY5eSp7ImA9WhRRGEw.&quot;"><id>tag:blogger.com,1999:blog-5701415790759755571.post-3499578500894012392</id><published>2011-12-02T08:19:00.000+01:00</published><updated>2011-12-02T08:19:09.821+01:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2011-12-02T08:19:09.821+01:00</app:edited><category scheme="http://www.blogger.com/atom/ns#" term="Java" /><title>Java 7: Project Coin in code examples</title><content type="html">This blog introduces - by code examples - some new Java 7 features summarized under the term &lt;a href="http://openjdk.java.net/projects/coin/"&gt;Project Coin&lt;/a&gt;. The goal of Project Coin is to add a set of small language changes to JDK 7. These changes do simplify the Java language syntax. Less typing, cleaner code, happy developer ;-) Let's look into that.&lt;br /&gt;
&lt;br /&gt;
&lt;a name='more'&gt;&lt;/a&gt;&lt;br /&gt;
&lt;div style="background-color: #cfe2f3; text-align: center;"&gt;&lt;b&gt;Prerequisites&lt;/b&gt;&lt;/div&gt;&lt;br /&gt;
Install &lt;a href="http://www.oracle.com/technetwork/java/javase/downloads/index.html"&gt;Java 7 SDK&lt;/a&gt; on your machine&lt;br /&gt;
Install &lt;a href="http://eclipse.org/downloads/"&gt;Eclipse Indigo&lt;/a&gt; 3.7.1&lt;br /&gt;
&lt;br /&gt;
You need to look out for the correct bundles for your operating system.&lt;br /&gt;
&lt;br /&gt;
In your Eclipse workspace you need to define the installed Java 7 JDK in your runtime. In the Workbench go to Window &amp;gt; Preferences &amp;gt; Java &amp;gt; Installed JREs and add your Java 7 home directory. &lt;br /&gt;
&lt;br /&gt;
&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;a href="http://2.bp.blogspot.com/-Xj1yDwWwSN0/TtY_xEIpgGI/AAAAAAAAAR0/_SWH9EfKi3w/s1600/Installed.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"&gt;&lt;img border="0" height="287" src="http://2.bp.blogspot.com/-Xj1yDwWwSN0/TtY_xEIpgGI/AAAAAAAAAR0/_SWH9EfKi3w/s320/Installed.jpg" width="320" /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;
Next you need to set the compiler level to 1.7 in Java &amp;gt; Compiler.&lt;br /&gt;
&lt;br /&gt;
&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;a href="http://4.bp.blogspot.com/-rkJh1XUNJtA/TtY_4PIb9uI/AAAAAAAAASA/I1vAWKJ20Eo/s1600/Compiler.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"&gt;&lt;img border="0" height="287" src="http://4.bp.blogspot.com/-rkJh1XUNJtA/TtY_4PIb9uI/AAAAAAAAASA/I1vAWKJ20Eo/s320/Compiler.jpg" width="320" /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;
&lt;div style="background-color: #cfe2f3; text-align: center;"&gt;&lt;b&gt;Project Coin&lt;/b&gt;&lt;/div&gt;&lt;br /&gt;
&lt;b&gt;Improved literals&lt;br /&gt;
&lt;/b&gt;&lt;br /&gt;
A literal is the source code representation of a fixed value.&lt;br /&gt;
&lt;br /&gt;
"In Java SE 7 and later, any number of underscore characters (_) can appear anywhere between digits in a numerical literal. This feature enables you to separate groups of digits in numeric literals, which can improve the readability of your code." (from &lt;a href="http://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html"&gt;the Java Tutorials&lt;/a&gt;)&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="java" name="code"&gt;public class LiteralsExample {

 public static void main(String[] args) {
  System.out.println("With underscores: ");
  
  long creditCardNumber = 1234_5678_9012_3456L;
  long bytes = 0b11010010_01101001_10010100_10010010;
  
  System.out.println(creditCardNumber);
  System.out.println(bytes);
  
  System.out.println("Without underscores: ");
  
  creditCardNumber = 1234567890123456L;
  bytes = 0b11010010011010011001010010010010;
  
  System.out.println(creditCardNumber);
  System.out.println(bytes);
  
 }
}&lt;/pre&gt;&lt;br /&gt;
Notice the underscores in the literals (e.g. 1234_5678_9012_3456L). Results written to the console:&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="java" name="code"&gt;With underscores: 
1234567890123456
-764832622
Without underscores: 
1234567890123456
-764832622&lt;/pre&gt;&lt;br /&gt;
As you can see, the underscores do not make a difference to the values. They are just used to make the code more readible.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;SafeVarargs&lt;/b&gt;&lt;br /&gt;
&lt;br /&gt;
Pre-JDK 7, you always got an unchecked warning when calling certain varargs library methods. Without the new &lt;code&gt;@SafeVarargs&lt;/code&gt; annotation this example would create unchecked warnings.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="java" name="code"&gt;public class SafeVarargsExample {

 @SafeVarargs
 static void m(List&lt;string&gt;... stringLists) {
  Object[] array = stringLists;
  List&lt;integer&gt; tmpList = Arrays.asList(42);
  array[0] = tmpList; // compiles without warnings
  String s = stringLists[0].get(0); // ClassCastException at runtime
 }

 public static void main(String[] args) {
  m(new ArrayList&lt;string&gt;());
 }
 
}&lt;/string&gt;&lt;/integer&gt;&lt;/string&gt;&lt;/pre&gt;&lt;br /&gt;
The new annotation in line 3 does not help to get around the annoying &lt;code&gt;ClassCastException&lt;/code&gt; at runtime. Also, it can only be applied to static and final methods. Therefore, I believe it will not be a great help. Future versions of Java will have compile time errors for unsafe code like the one in the example above.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Diamond&lt;/b&gt;&lt;br /&gt;
&lt;br /&gt;
In Java 6 it required some patience to create, say, list of maps. Look at this example:&lt;br /&gt;
&lt;br /&gt;
&lt;script src="https://gist.github.com/1409477.js"&gt;
&lt;/script&gt;&lt;br /&gt;
As you can see in the right part of the assignment in lines 3 and 4 you need to repeat your type information for the &lt;code&gt;listOfMaps&lt;/code&gt; variable as well as of the &lt;code&gt;aMap&lt;/code&gt; variable. This isn't necessary anymore in Java 7:&lt;br /&gt;
&lt;br /&gt;
&lt;script src="https://gist.github.com/1409490.js"&gt;
 
&lt;/script&gt;&lt;br /&gt;
&lt;b&gt;Multicatch&lt;/b&gt;&lt;br /&gt;
&lt;br /&gt;
In Java 7 you do not need a catch clause for every single exception, you can catch multiple exceptions in one clause. You remember code like this:&lt;br /&gt;
&lt;pre class="java" name="code"&gt;public class HandleExceptionsJava6Example {
 public static void main(String[] args) {
  Class string;
  try {
   string = Class.forName("java.lang.String");
   string.getMethod("length").invoke("test");
  } catch (ClassNotFoundException e) {
   // do something
  } catch (IllegalAccessException e) {
   // do the same !!
  } catch (IllegalArgumentException e) {
   // do the same !!
  } catch (InvocationTargetException e) {
   // yeah, well, again: do the same!
  } catch (NoSuchMethodException e) {
   // ...
  } catch (SecurityException e) {
   // ...
  }
 }
}&lt;/pre&gt;&lt;br /&gt;
Since Java 7 you can write it like this, which makes our lives a lot easier:&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="java" name="code"&gt;public class HandleExceptionsJava7ExampleMultiCatch {
 public static void main(String[] args) {
  try {
   Class string = Class.forName("java.lang.String");
   string.getMethod("length").invoke("test");
  } catch (ClassNotFoundException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException e) {
   // do something, and only write it once!!!
  }
 }
}&lt;/pre&gt;&lt;br /&gt;
&lt;b&gt;String in switch statements&lt;/b&gt;&lt;br /&gt;
&lt;br /&gt;
Since Java 7 one can use string variables in switch clauses. Here is an example:&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="java" name="code"&gt;public class StringInSwitch {
 public void printMonth(String month) {
  switch (month) {
  case "April":
  case "June":
  case "September":
  case "November":
  case "January":
  case "March":
  case "May":
  case "July":
  case "August":
  case "December":
  default:
   System.out.println("done!");
  }
 }
}&lt;/pre&gt;&lt;br /&gt;
&lt;b&gt;Try-with-resource&lt;/b&gt;&lt;br /&gt;
&lt;br /&gt;
This feature really helps in terms of reducing unexpected runtime execptions. In Java 7 you can use the so called try-with-resource clause that automatically closes all open resources if an exception occurs. Look at the example:&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="java" name="code"&gt;import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

public class TryWithResourceExample {

 public static void main(String[] args) throws FileNotFoundException {
  
  // Java 7 try-with-resource
  
  String file1 = "TryWithResourceFile.out";
  try (OutputStream out = new FileOutputStream(file1)) {
   out.write("Some silly file content ...".getBytes());
   ":-p".charAt(3);
  } catch (StringIndexOutOfBoundsException | IOException e) {
   System.out.println("Exception on operating file " + file1 + ": " + e.getMessage());
  }
  
  // Java 6 style
  
  String file2 = "WithoutTryWithResource.out";
  OutputStream out = new FileOutputStream(file2);
  try {
   out.write("Some silly file content ...".getBytes());
   ":-p".charAt(3);
  } catch (StringIndexOutOfBoundsException | IOException e) {
   System.out.println("Exception on operating file " + file2 + ": " + e.getMessage());
  }

  // Let's try to operate on the resources
  
  File f1 = new File(file1);
  if (f1.delete())
   System.out.println("Successfully deleted: " + file1);
  else
   System.out.println("Problems deleting: " + file1);

  File f2 = new File(file2);
  if (f2.delete())
   System.out.println("Successfully deleted: " + file2);
  else
   System.out.println("Problems deleting: " + file2);
  
 }
}&lt;/pre&gt;&lt;br /&gt;
In line 14 the try-with-resource clause is used to open a file that we want to operate on. Then line 16 generates a runtime exception. Notice that I do not explicitly close the resource. This is done automatically when you use try-with-resource. It *isn't* when you use the Java 6 equivalent shown in lines 21-30.&lt;br /&gt;
&lt;br /&gt;
The code will write the following result to the console:&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="java" name="code"&gt;Exception on operating file TryWithResourceFile.out: String index out of range: 3
Exception on operating file WithoutTryWithResource.out: String index out of range: 3
Successfully deleted: TryWithResourceFile.out
Problems deleting: WithoutTryWithResource.out&lt;/pre&gt;&lt;br /&gt;
That's it in terms of Project Coin. Very useful stuff in my eyes.&lt;img src="http://feeds.feedburner.com/~r/blogspot/BufQX/~4/z0w7vzcg7Gg" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://niklasschlimm.blogspot.com/feeds/3499578500894012392/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://niklasschlimm.blogspot.com/2011/12/java-7-project-coin-in-code-examples.html#comment-form" title="5 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/5701415790759755571/posts/default/3499578500894012392?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/5701415790759755571/posts/default/3499578500894012392?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/blogspot/BufQX/~3/z0w7vzcg7Gg/java-7-project-coin-in-code-examples.html" title="Java 7: Project Coin in code examples" /><author><name>Niklas Schlimm</name><uri>http://www.blogger.com/profile/12402045792243894660</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="24" height="32" src="http://1.bp.blogspot.com/-T7F8yoGErpc/TjlFwjgDvTI/AAAAAAAAAPo/Uqt54kYww9E/s220/Niki.JPG" /></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="http://2.bp.blogspot.com/-Xj1yDwWwSN0/TtY_xEIpgGI/AAAAAAAAAR0/_SWH9EfKi3w/s72-c/Installed.jpg" height="72" width="72" /><thr:total>5</thr:total><feedburner:origLink>http://niklasschlimm.blogspot.com/2011/12/java-7-project-coin-in-code-examples.html</feedburner:origLink></entry><entry gd:etag="W/&quot;CEQMRXo9cCp7ImA9WhRSEk0.&quot;"><id>tag:blogger.com,1999:blog-5701415790759755571.post-5787057077882094116</id><published>2011-11-13T17:37:00.002+01:00</published><updated>2011-11-13T17:39:44.468+01:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2011-11-13T17:39:44.468+01:00</app:edited><category scheme="http://www.blogger.com/atom/ns#" term="Java EE" /><title>Java EE 6 and the snowball effect</title><content type="html">Java EE application servers increase their feature sets (APIs and administration features) whilst business applications get smaller and smaller. This introduces a new issue: if you need a single feature of a new application server version you'll get a complete package of features that you didn't need in the first place (the snowball effect). Let me give you an example: in WebSphere 7 IBM provides a high speed integration adapter for IMS assets. We need that, but we don't need all the rest that gives us a headache in terms of migration efforts. Now, if the amount of APIs  increase in Java EE with every version, I predict that this problem starts to get more and more complicated. That's a reason why I don't appreciate the fact that Java EE standardizes former framework functionality like dependency injection (CDI). Business applications may get smaller, but application server feature sets get huge this way. Is that a good trend? &lt;br /&gt;
&lt;br /&gt;
&lt;a name='more'&gt;&lt;/a&gt;I typically try to keep application bundles small in my business applications. Not in size necessarily but in terms of packaged features. This way I don't create artificial dependencies. You need to deploy a new web service version? Then I can only deploy that specific web service module without creating a snowball effect of additional required deployments. Small packages reduce the need of branch development. Small packages reduce the risk of instability. Small packages reduce the necessity to synchronize deployments of different development teams. If you finnish your work or you need to deploy a new version of your application then you should create as little dependency as possible. In an ideal scenario you don't need to talk to any other developer if you want to deploy the features your responsible for. I think this should also apply to application server software. The trend to shrink business application feature sets and increase those of application servers should stop. Or: administration features of application servers should be seperated and compatible to the different Java EE standards. A more moduralized approach would be desireable.&lt;img src="http://feeds.feedburner.com/~r/blogspot/BufQX/~4/VLoGpRZjgl8" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://niklasschlimm.blogspot.com/feeds/5787057077882094116/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://niklasschlimm.blogspot.com/2011/11/java-ee-6-and-snowball-effect.html#comment-form" title="23 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/5701415790759755571/posts/default/5787057077882094116?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/5701415790759755571/posts/default/5787057077882094116?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/blogspot/BufQX/~3/VLoGpRZjgl8/java-ee-6-and-snowball-effect.html" title="Java EE 6 and the snowball effect" /><author><name>Niklas Schlimm</name><uri>http://www.blogger.com/profile/12402045792243894660</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="24" height="32" src="http://1.bp.blogspot.com/-T7F8yoGErpc/TjlFwjgDvTI/AAAAAAAAAPo/Uqt54kYww9E/s220/Niki.JPG" /></author><thr:total>23</thr:total><feedburner:origLink>http://niklasschlimm.blogspot.com/2011/11/java-ee-6-and-snowball-effect.html</feedburner:origLink></entry><entry gd:etag="W/&quot;DEcMRHc5eip7ImA9WhRSEUU.&quot;"><id>tag:blogger.com,1999:blog-5701415790759755571.post-361790579842432671</id><published>2011-11-12T12:12:00.072+01:00</published><updated>2011-11-13T13:08:05.922+01:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2011-11-13T13:08:05.922+01:00</app:edited><category scheme="http://www.blogger.com/atom/ns#" term="Methodology" /><title>Characteristics of successful developers</title><content type="html">Many blogs exist about personal (soft) characteristics of successful developers. Here is a short listing of some interesting links:&lt;br /&gt;
&lt;br /&gt;
&lt;a href="http://www.supercoders.com.au/blog/50characteristicsofagreatsoftwaredeveloper.shtml"&gt;50 characteristics of a great software developer&lt;/a&gt;&lt;br /&gt;
&lt;a href="http://www.readwriteweb.com/archives/top_10_software_engineer_traits.php"&gt;Top 10 Traits of a Rockstar Software Engineer&lt;/a&gt;&lt;br /&gt;
&lt;a href="http://javablog.franksalinas.net/2009/05/09/five-essential-skills-for-software-developers/"&gt;Five essential skills for software developers&lt;/a&gt;&lt;br /&gt;
&lt;a href="http://agilemanifesto.org/"&gt;Manifesto for Agile Software Development&lt;br /&gt;
&lt;/a&gt;&lt;a href="http://manifesto.softwarecraftsmanship.org/"&gt;Manifesto for Software Craftsmanship&lt;/a&gt;&lt;br /&gt;
&lt;br /&gt;
This one blog now is my personal view on that very topic. It's of course subjective to my own history and environment and I don't claim that the list is complete. Also, I do not have the discipline to always have all those characteristics a 100% myself. We're all humans, so don't take them to serious :-) Last not least: success must not be the target of your work. The target is to work on your own virtues, some of those virtues are the topic of this blog.&lt;br /&gt;
&lt;br /&gt;
&lt;a name='more'&gt;&lt;/a&gt;&lt;b&gt;The will to be good at something&lt;/b&gt;&lt;br /&gt;
&lt;br /&gt;
It's not easy to work as a developer! I say that for a couple of reasons that make our lifes a little harder compared to other professions. The fact - for instance - that the technology cycle in the IT world is very short, the actual knowledge becomes outdated in a few years. Therefore, we need to learn continuously - new things get important. To stay on top of things we really need the strong will to be good at our job. That's probably the most important characteristic to me: being an excellent knowledge worker with great technical abillities, and have the will to be that over decades!&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;To ask one's way&lt;/b&gt;&lt;br /&gt;
&lt;br /&gt;
Because it's impossible to know everything to do the job, it's absolutely necessary that a developer finds its way through a new topic. How I typically do that is I use google and I talk to other experts to find out what they think. "I did not know what to do!" is not an argument for me. 'Cause if I didn't know enough about that new technology yet, I spent the energy that's necessary to learn what I need to know to do the job. We need to work through the learning curve and make the last-ditch effort to get good at what we're doing!&lt;br /&gt;
&lt;b&gt;&lt;br /&gt;
To make oneself useful&lt;/b&gt;&lt;br /&gt;
&lt;br /&gt;
If I have some time left because I completed my tasks earlier then expected, then: I take a coffee and play tabletop soccer. I take a rest. Afterwards I think about what I could do that helps the team to achieve its targets, 'cause some of my team mates probably didn't finish! (at least if I didn't met them at tabletop soccer) If everyone's finished then I think about improvements to the process or team organisation. I make myself usefull.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;To care&lt;/b&gt;&lt;br /&gt;
&lt;br /&gt;
Some years ago I attended a software architecture course held by one of my idols &lt;a href="http://www.bredemeyer.com/"&gt; Dana Bredemeyer&lt;/a&gt;. I had a discussion with him what it really takes to make a team successful or to be a successful team leader. He said: "Well, you need some people that really care!" I think there is a lot truth in that statement. If we do not care about quality, timelines, good team culture, respectful communication (!!), clean code, software-craftsmanship, if all this doen't matter to us, then I believe the probability is higher that we fail. &lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Being productive&lt;/b&gt;&lt;br /&gt;
&lt;br /&gt;
Peter Kruchten put it right in his &lt;a href="http://www.ibm.com/developerworks/rational/library/4032.html"&gt;TAO for the software architect&lt;/a&gt;:&lt;br /&gt;
&lt;br /&gt;
"Those who know don't talk.&lt;br /&gt;
Those who talk don't know.&lt;br /&gt;
Those who do not have a clue are still debating about the process.&lt;br /&gt;
Those who know just do it."&lt;br /&gt;
&lt;br /&gt;
I am trying to be productive every week - at the end of a week I look back and I ask myself what I have produced. This could be paperwork, community days or (best!!) programming code.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Working solution-orientied&lt;/b&gt;&lt;br /&gt;
&lt;br /&gt;
In many situations where people had trouble to achieve it's targets I saw them debating about all the problems and the difficulties to solve the issue. They blamed each other and discussed about THE PAST. I am trying not to do that, I don't blame others, I don't just look at the difficulties. I am trying to suggest solutions instead! And yes, there is always a solution to a problem. Most of the times there are at least three solutions.  &lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Be good with people&lt;/b&gt;&lt;br /&gt;
&lt;br /&gt;
Because our job typically involves to work in a (most wanted: cross-functional!) team, it's important that we're (more or less) good in dealing with other individuals. They have their own strengths and weaknesses, just like ourselves. It's important to treat all the team mates with respect, regardless of their technical competence or contributions. Of course, sometimes people deserve a clear statement, but try to do these things one-on-one. Make sure nobody looses his face. Attend the meetings at the coffe bar, be good at tabletop soccer and go out once in a while to have a beer with your team. You know what I'm talking about.&lt;br /&gt;
&lt;br /&gt;
That's it. I am looking forward to your thoughts and comments!&lt;img src="http://feeds.feedburner.com/~r/blogspot/BufQX/~4/YpnxnB3ENWI" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://niklasschlimm.blogspot.com/feeds/361790579842432671/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://niklasschlimm.blogspot.com/2011/11/characteristics-of-superior-successful.html#comment-form" title="2 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/5701415790759755571/posts/default/361790579842432671?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/5701415790759755571/posts/default/361790579842432671?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/blogspot/BufQX/~3/YpnxnB3ENWI/characteristics-of-superior-successful.html" title="Characteristics of successful developers" /><author><name>Niklas Schlimm</name><uri>http://www.blogger.com/profile/12402045792243894660</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="24" height="32" src="http://1.bp.blogspot.com/-T7F8yoGErpc/TjlFwjgDvTI/AAAAAAAAAPo/Uqt54kYww9E/s220/Niki.JPG" /></author><thr:total>2</thr:total><feedburner:origLink>http://niklasschlimm.blogspot.com/2011/11/characteristics-of-superior-successful.html</feedburner:origLink></entry><entry gd:etag="W/&quot;DEABSHc4cSp7ImA9WhVRE0Q.&quot;"><id>tag:blogger.com,1999:blog-5701415790759755571.post-597953171444657575</id><published>2011-10-25T15:38:00.005+02:00</published><updated>2012-03-22T07:12:39.939+01:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2012-03-22T07:12:39.939+01:00</app:edited><category scheme="http://www.blogger.com/atom/ns#" term="Java" /><category scheme="http://www.blogger.com/atom/ns#" term="Threading stories" /><title>Threading stories: volatile and synchronized</title><content type="html">In &lt;a href="http://niklasschlimm.blogspot.com/2011/10/threading-stories-why-volatile-matters.html"&gt;my last blog&lt;/a&gt; about the &lt;code&gt;volatile&lt;/code&gt; modifier I have introduced a little program that illustrates the behaviour of &lt;code&gt;volatile&lt;/code&gt; in a Java 6 (26) Hotspot VM. Since that day I had some interesting discussions that I wanted to share in this blog. It adds another valuable insights on the &lt;code&gt;volatile&lt;/code&gt; modifier.&lt;br /&gt;
&lt;br /&gt;
&lt;a name='more'&gt;&lt;/a&gt;Here is my little program, which I have adopted a little to make it easier. My previous example was originally thought as a thread contention example, which will be the topic in one of my upcoming posts. &lt;br /&gt;
&lt;pre class="java" name="code"&gt;import java.util.Timer;
import java.util.TimerTask;

public class AnotherVolatileExampleA {

 private volatile boolean expired = false;
 private long counter = 0;
 private Object mutex = new Object();

 private class Worker implements Runnable {
  @Override
  public void run() {
   synchronized (mutex) {
    final Timer timer = new Timer();
    timer.schedule(new TimerTask() {
     public void run() {
      expired = true;
      System.out.println("Timer interrupted main thread ...");
      timer.cancel();
     }
    }, 1000);
    while (!expired) {
     counter++; // do some work
    }
    System.out.println("Main thread was interrupted by timer ...");
   };
  }
 }

 public static void main(String[] args) throws InterruptedException {
  AnotherVolatileExampleA volatileExample = new AnotherVolatileExampleA();
  Thread thread1 = new Thread(volatileExample.new Worker(), "Worker-1");
  thread1.start();
 }
}
&lt;/pre&gt;&lt;br /&gt;
Now, this program still behaves similar like &lt;a href="http://niklasschlimm.blogspot.com/2011/10/threading-stories-why-volatile-matters.html"&gt;the one of my last blog&lt;/a&gt;. With &lt;code&gt;volatile&lt;/code&gt; in line 6 the result written to the console is:&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="java" name="code"&gt;Timer interrupted main thread ...
Main thread was interrupted by timer ...&lt;/pre&gt;&lt;br /&gt;
Without &lt;code&gt;volatile&lt;/code&gt; in line 6 the result is:&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="java" name="code"&gt;Timer interrupted main thread ...
&lt;/pre&gt;&lt;br /&gt;
One question in a discussion was, why that happens although everything takes place in a &lt;code&gt;synchronized&lt;/code&gt; block. The Java VM specification says the &lt;code&gt;synchronized&lt;/code&gt; keywork garantees that (less formal!) a variable is written into the memory heap and is read from the memory heap (&lt;a href="http://java.sun.com/docs/books/jvms/second_edition/html/Threads.doc.html#22253"&gt;read here&lt;/a&gt;). Now, this is true, but it's missing the point that the thread only needs to read the variable ONCE within a single &lt;code&gt;synchronized&lt;/code&gt; block. In the example above the expired variable is read once at the very first while loop. Afterwards the thread does not need to read the variable again. Consider this program:&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="java" name="code"&gt;import java.util.Timer;
import java.util.TimerTask;

public class AnotherVolatileExampleB {

 private boolean expired = false;
 private long counter = 0;
 private Object mutex = new Object();

 private class Worker implements Runnable {
  @Override
  public void run() {
   final Timer timer = new Timer();
   timer.schedule(new TimerTask() {
    public void run() {
     expired = true;
     System.out.println("Timer interrupted main thread ...");
     timer.cancel();
    }
   }, 1000);
   boolean tmpExpired = false;
   while (!tmpExpired) {
    synchronized (mutex) {
     tmpExpired = expired;
    }
    counter++; // do some work
   }
   System.out.println("Main thread was interrupted by timer ...");
  }
 }

 public static void main(String[] args) throws InterruptedException {
  AnotherVolatileExampleB volatileExample = new AnotherVolatileExampleB();
  Thread thread1 = new Thread(volatileExample.new Worker(), "Worker-1");
  thread1.start();
 }
}
&lt;/pre&gt;&lt;br /&gt;
In that case the &lt;code&gt;synchronized&lt;/code&gt; block is within the while loop (lines 23-25) and the thread is now forced to re-read the expired variable from the main memory in each loop 'cause &lt;code&gt;synchronized&lt;/code&gt; garantees to read from memory once (same applies to Java 5 locks). The result of that program will be as expected from a &lt;code&gt;synchronized&lt;/code&gt; block:&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="java" name="code"&gt;Timer interrupted main thread ...
Main thread was interrupted by timer ...
&lt;/pre&gt;&lt;br /&gt;
Therefore, if you wish to read a variable from memory in a &lt;code&gt;synchronized&lt;/code&gt; block (or within a Java 5 lock), remember that the thread only garantees to read the variable once from the memory heap. The &lt;code&gt;volatile&lt;/code&gt; modifier, on the other hand, always garantees a "memory heap read" (&lt;a href="http://java.sun.com/docs/books/jvms/second_edition/html/Threads.doc.html#22258"&gt;see here&lt;/a&gt;).&lt;img src="http://feeds.feedburner.com/~r/blogspot/BufQX/~4/1F8m3SdMT64" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://niklasschlimm.blogspot.com/feeds/597953171444657575/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://niklasschlimm.blogspot.com/2011/10/threading-stories-volatile-and.html#comment-form" title="4 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/5701415790759755571/posts/default/597953171444657575?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/5701415790759755571/posts/default/597953171444657575?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/blogspot/BufQX/~3/1F8m3SdMT64/threading-stories-volatile-and.html" title="Threading stories: volatile and synchronized" /><author><name>Niklas Schlimm</name><uri>http://www.blogger.com/profile/12402045792243894660</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="24" height="32" src="http://1.bp.blogspot.com/-T7F8yoGErpc/TjlFwjgDvTI/AAAAAAAAAPo/Uqt54kYww9E/s220/Niki.JPG" /></author><thr:total>4</thr:total><feedburner:origLink>http://niklasschlimm.blogspot.com/2011/10/threading-stories-volatile-and.html</feedburner:origLink></entry><entry gd:etag="W/&quot;DE8EQng5eip7ImA9WhVRE0Q.&quot;"><id>tag:blogger.com,1999:blog-5701415790759755571.post-8295832879416482207</id><published>2011-10-19T08:16:00.035+02:00</published><updated>2012-03-22T07:13:23.622+01:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2012-03-22T07:13:23.622+01:00</app:edited><category scheme="http://www.blogger.com/atom/ns#" term="Java" /><category scheme="http://www.blogger.com/atom/ns#" term="Threading stories" /><title>Threading stories: Why volatile matters</title><content type="html">Many years ago when I learned Java (in 2000) I was not so concerned about multithreading. In particular I wasn't concerned about the &lt;code&gt;volatile&lt;/code&gt; modifier. I don't know why, but I never had problems without &lt;code&gt;volatile&lt;/code&gt;, so maybe I thought it could not be so relevant. I've suddenly changed my mind when I first analyzed a wierd behaviour of an application that only existed when the application was deployed to a server JVM. Todays JVMs make a lot magic stuff to optimize runtime performance on server applications. In this blog I show you an example to get fimiliar with problems that arrize in multithreaded applications, when you don't recognize the importance of understanding how Java treats shared data in multithreaded programs.&lt;br /&gt;
&lt;br /&gt;
&lt;a name='more'&gt;&lt;/a&gt;This code snippet demonstrates why understanding &lt;code&gt;volatile&lt;/code&gt; is important. Here is the code that you can use to play around. Notice in line 8 the &lt;code&gt;expired&lt;/code&gt; variable is declared &lt;code&gt;volatile&lt;/code&gt;:&lt;br /&gt;
&lt;pre class="java" name="code"&gt;import java.util.Timer;
import java.util.TimerTask;

public class VolatileExample {

 private volatile boolean expired;
 private long counter = 0;
 private Object mutext = new Object();

 @Override
 public Object[] execute(Object... arguments) {
  synchronized (mutext) {
   expired = false;
   final Timer timer = new Timer();
   timer.schedule(new TimerTask() {
    public void run() {
     expired = true;
     System.out.println("Timer interrupted main thread ...");
     timer.cancel();
    }
   }, 1000);
   while (!expired) {
    counter++; // do some work
   }
   System.out.println("Main thread was interrupted by timer ...");
  };
  return new Object[] { counter, expired };
 }

 private class Worker implements Runnable {
  @Override
  public void run() {
   while (!Thread.currentThread().isInterrupted()) {
    execute();
   }
  }
 }

 @SuppressWarnings("static-access")
 public static void main(String[] args) throws InterruptedException {
  VolatileExample volatileExample = new VolatileExample();
  Thread thread1 = new Thread(volatileExample.new Worker(), "Worker-1");
  Thread thread2 = new Thread(volatileExample.new Worker(), "Worker-2");
  thread1.start();
  thread2.start();
  Thread.currentThread().sleep(60000);
  thread1.interrupt();
  thread2.interrupt();
 }
}
&lt;/pre&gt;Start that with Hotspot VM with &lt;code&gt;-server&lt;/code&gt; option set. What you'll get is the following expected output:&lt;br /&gt;
&lt;pre class="java" name="code"&gt;Timer interrupted main thread ...
Main thread was interrupted by timer ...
Timer interrupted main thread ...
Main thread was interrupted by timer ...
Timer interrupted main thread ...
Main thread was interrupted by timer ...
Timer interrupted main thread ...
Main thread was interrupted by timer ...
Timer interrupted main thread ...
Main thread was interrupted by timer ...
&lt;/pre&gt;Now take out the &lt;code&gt;volatile&lt;/code&gt; in line 8 above and restart, again with &lt;code&gt;-server&lt;/code&gt; option set. What you should get is the following output:&lt;br /&gt;
&lt;pre class="java" name="code"&gt;Timer interrupted main thread ...
&lt;/pre&gt;What happened? The Timer thread sets the &lt;code&gt;expired&lt;/code&gt; flag to &lt;code&gt;true&lt;/code&gt; but the main thread does not see the change. This is exactly what &lt;code&gt;volatile&lt;/code&gt; is all about: it ensures that threads share the actual value of a specific variable. If you declare a variable as &lt;code&gt;volatile&lt;/code&gt; all threads read that specific value from the memory heap. In the described example the timer thread set the expired value within the thread and this update was not reflected in the memory heap! Notice, that I cancel the timer thread when I set the &lt;code&gt;expired&lt;/code&gt; variable to &lt;code&gt;true&lt;/code&gt;. This causes the timer thread to die immediately after the &lt;code&gt;run()&lt;/code&gt;-method is passed. The main memory heap may be updated now, but the worker thread continues to work on the 'cached' data in the thread memory.&lt;br /&gt;
&lt;br /&gt;
Next: now restart the code again without the &lt;code&gt;volatile&lt;/code&gt; modifier. This time you set the &lt;code&gt;-client&lt;/code&gt; JVM option (which is the default mode on Windows). The result is the following:&lt;br /&gt;
&lt;pre class="java" name="code"&gt;Timer interrupted main thread ...
Main thread was interrupted by timer ...
Timer interrupted main thread ...
Main thread was interrupted by timer ...
Timer interrupted main thread ...
Main thread was interrupted by timer ...
Timer interrupted main thread ...
Main thread was interrupted by timer ...
Timer interrupted main thread ...
Main thread was interrupted by timer ...
&lt;/pre&gt;&lt;br /&gt;
In the client mode the JVM obviously behaves different and does not optimize so aggressively like in server mode. So even if you missed out the &lt;code&gt;volatile&lt;/code&gt; modifier, you may not necessarily see an error during development. The JVM options influence the way how strict the JVM optimzes your code. Without &lt;code&gt;volatile&lt;/code&gt; it is not garanteed that data changes made by the timer thread are visible to the main thread. But in this case for instance everything still works OK in client mode, which shows that the result of your program relies on the JVM options set.&lt;img src="http://feeds.feedburner.com/~r/blogspot/BufQX/~4/7yBKJTCZyLc" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://niklasschlimm.blogspot.com/feeds/8295832879416482207/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://niklasschlimm.blogspot.com/2011/10/threading-stories-why-volatile-matters.html#comment-form" title="7 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/5701415790759755571/posts/default/8295832879416482207?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/5701415790759755571/posts/default/8295832879416482207?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/blogspot/BufQX/~3/7yBKJTCZyLc/threading-stories-why-volatile-matters.html" title="Threading stories: Why volatile matters" /><author><name>Niklas Schlimm</name><uri>http://www.blogger.com/profile/12402045792243894660</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="24" height="32" src="http://1.bp.blogspot.com/-T7F8yoGErpc/TjlFwjgDvTI/AAAAAAAAAPo/Uqt54kYww9E/s220/Niki.JPG" /></author><thr:total>7</thr:total><feedburner:origLink>http://niklasschlimm.blogspot.com/2011/10/threading-stories-why-volatile-matters.html</feedburner:origLink></entry><entry gd:etag="W/&quot;D08FRnY-fSp7ImA9WhdUGE8.&quot;"><id>tag:blogger.com,1999:blog-5701415790759755571.post-8978853552430604235</id><published>2011-09-30T16:10:00.014+02:00</published><updated>2011-10-05T16:43:37.855+02:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2011-10-05T16:43:37.855+02:00</app:edited><category scheme="http://www.blogger.com/atom/ns#" term="Java" /><title>Benchmark series on simple caching solutions in Java</title><content type="html">Caching is a very common solution when you don't want to repeat CPU intense tasks. The last days I was benchmarking options to do caching with &lt;code&gt;ConcurrentHashMap&lt;/code&gt;. In this blog I publish the first results. I have used &lt;a href="http://www.javaspecialists.eu/archive/Issue124.html"&gt;Heinz Kabutz' Performance Checker&lt;/a&gt; to do this. I also added some features based on my readings of &lt;a href="http://www.ibm.com/developerworks/java/library/j-benchmark1/index.html"&gt;this article series&lt;/a&gt;.&lt;br /&gt;
&lt;br /&gt;
&lt;a name='more'&gt;&lt;/a&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;div style="background-color: #cfe2f3; text-align: center;"&gt;&lt;b&gt;My Conclusions up front&lt;/b&gt;&lt;/div&gt;&lt;br /&gt;
I am testing three different cache implementations: "Check null", "check map" and "putIfAbsent" cache. The code is listed below the results. Also, I am using three different cache sizes: 10 (small), 100000 (large) and 1000000 (very large) possible key values. Again: The 10 units cache can have 10 different key values. The 100000 units cache can have 100000 different key values etc.&lt;br /&gt;
&lt;br /&gt;
None of the implementation options show significant performance differences assuming cache size is equivalent. This is disappointing (!!) but also good to know. It's also a little surprising I think, 'cause for example "putIfAbsent" cache appears to be more complex then the others. All the solutions seem to decrease logarithmical in performance when the cache increases to very large sizes. The main reason for that should be the increased time for cache initialization, 'cause in my test harness I start with an empty cash and a fixed set of possible key values (i.e. 10, 100000 or 1000000). I'll come up with a benchmark series for fully initialized cache later.&lt;br /&gt;
&lt;br /&gt;
Knowing what I know now, I would carefully recommend to use the "putIfAbsent" cache solution. That's because it has equivalent performance but gives you great flexibility to design the behaviour of your cache in highly concurrent scenarios. See &lt;a href="http://niklasschlimm.blogspot.com/2011/09/your-web-applications-work-by-sheer.html"&gt;the pattern solution of my last article &lt;/a&gt;about multithreading as an example of more complex use cases.&lt;br /&gt;
&lt;br /&gt;
If you're interested in the test harness take a look at the implementations: &lt;code&gt;&lt;a href="https://github.com/nschlimm/playground/blob/master/webappbenchmarker-playground/src/main/java/com/schlimm/webappbenchmarker/command/std/CacheSolution_CheckMap.java"&gt;CacheSolution_CheckMap.java&lt;/a&gt;&lt;/code&gt;, &lt;code&gt;&lt;a href="https://github.com/nschlimm/playground/blob/master/webappbenchmarker-playground/src/main/java/com/schlimm/webappbenchmarker/command/std/CacheSolution_CheckNull.java"&gt;CacheSolution_CheckNull.java&lt;/a&gt;&lt;/code&gt; and &lt;code&gt;&lt;a href="https://github.com/nschlimm/playground/blob/master/webappbenchmarker-playground/src/main/java/com/schlimm/webappbenchmarker/command/std/CacheSolution_PutIfAbsent.java"&gt;CacheSolution_PutIfAbsent.java&lt;/a&gt;&lt;/code&gt;. I appreciate your comments very much!&lt;br /&gt;
&lt;br /&gt;
My JVM was in mixed JIT mode and with &lt;code&gt;-server&lt;/code&gt; option set. OK, let's go into this!&lt;br /&gt;
&lt;br /&gt;
&lt;div style="background-color: #cfe2f3; text-align: center;"&gt;&lt;b&gt;Here are the results&lt;br /&gt;
&lt;/b&gt;&lt;/div&gt;&lt;br /&gt;
&lt;div style="background-color: #cfe2f3;"&gt;&lt;script src="https://gist.github.com/1253756.js"&gt;
&lt;/script&gt;&lt;/div&gt;&lt;br /&gt;
5 test runs each / 500 ms each test run&lt;br /&gt;
CL before/after = Classes Loaded before and after test harness&lt;br /&gt;
JIT before/after = Total JIT time before and after test harness&lt;br /&gt;
Small cache = 10 units&lt;br /&gt;
Large cache 100000 units&lt;br /&gt;
Very large cache = 1000000 units&lt;br /&gt;
&lt;br /&gt;
&lt;div style="background-color: #cfe2f3; text-align: center;"&gt;&lt;b&gt;Check null cache&lt;/b&gt;&lt;/div&gt;&lt;br /&gt;
&lt;script src="https://gist.github.com/1253758.js"&gt;
 
&lt;/script&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;div style="background-color: #cfe2f3; text-align: center;"&gt;&lt;b&gt;Check map cache&lt;/b&gt;&lt;/div&gt;&lt;br /&gt;
&lt;script src="https://gist.github.com/1253760.js"&gt;
 
&lt;/script&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;div style="background-color: #cfe2f3; text-align: center;"&gt;&lt;b&gt;The putIfAbsent cache&lt;/b&gt;&lt;/div&gt;&lt;br /&gt;
&lt;script src="https://gist.github.com/1253766.js"&gt;
 
&lt;/script&gt;&lt;img src="http://feeds.feedburner.com/~r/blogspot/BufQX/~4/SV8OK1icfK8" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://niklasschlimm.blogspot.com/feeds/8978853552430604235/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://niklasschlimm.blogspot.com/2011/09/benchmark-series-on-simple-caching.html#comment-form" title="3 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/5701415790759755571/posts/default/8978853552430604235?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/5701415790759755571/posts/default/8978853552430604235?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/blogspot/BufQX/~3/SV8OK1icfK8/benchmark-series-on-simple-caching.html" title="Benchmark series on simple caching solutions in Java" /><author><name>Niklas Schlimm</name><uri>http://www.blogger.com/profile/12402045792243894660</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="24" height="32" src="http://1.bp.blogspot.com/-T7F8yoGErpc/TjlFwjgDvTI/AAAAAAAAAPo/Uqt54kYww9E/s220/Niki.JPG" /></author><thr:total>3</thr:total><feedburner:origLink>http://niklasschlimm.blogspot.com/2011/09/benchmark-series-on-simple-caching.html</feedburner:origLink></entry><entry gd:etag="W/&quot;DE8BR3gzeyp7ImA9WhVRE0Q.&quot;"><id>tag:blogger.com,1999:blog-5701415790759755571.post-1664006158566834428</id><published>2011-09-09T22:01:00.005+02:00</published><updated>2012-03-22T07:14:16.683+01:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2012-03-22T07:14:16.683+01:00</app:edited><category scheme="http://www.blogger.com/atom/ns#" term="Java" /><category scheme="http://www.blogger.com/atom/ns#" term="Threading stories" /><title>Your web applications work - by sheer coincidence!</title><content type="html">This blog describes a solution to a typical concurrency problem in a web application environment, and it illustrates that you - in all likelihood - cannot be sure that your application is thread-safe. It just works - by sheer coincidence.&lt;br /&gt;
&lt;br /&gt;
&lt;a name='more'&gt;&lt;/a&gt;Last week we had a severe problem in a critical web module of our production environment. The problem was that we had to restart a server at a time where we had very high user and transaction volumes (we do ~500.000 transactions in that module per business day). The server shutdown deleted our XSL template cache. As a consequence many threads tried to recompile the templates concurrently after restart. This in turn introduced a (CPU) system overload issue. We could only restart the server by blocking the incoming requests at the web server level. In fact we only allowed some threads to bypass the web server and to enter the application server. After some warmup time we opened the web server and the system started to work at an acceptable CPU load.&lt;br /&gt;
&lt;br /&gt;
We've looked at the application code that caused the issue and decided to implement an intelligent concurrency pattern that fulfills following requirements:&lt;br /&gt;
&lt;br /&gt;
- the number of threads that perform a CPU intense task concurrently (like XSL template compilation) should be limited to a configurable size (=&amp;gt; avoid CPU overload on startup in user load peek times)&lt;br /&gt;
- cache the result of each CPU intense task so that it will only execute once (we had that already in our error prone solution)&lt;br /&gt;
- enable the system to determine whether the CPU intense task needs to execute again (=&amp;gt; if the application was redeployed the templates need to recompile)&lt;br /&gt;
&lt;br /&gt;
I spare me the effort (and the painfullness) to post the old non-safe code. The bugs in that code were:&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;firstly &lt;/b&gt;- it did not limit the number of threads allowed to compile templates&lt;br /&gt;
&lt;b&gt;secondly &lt;/b&gt;- it did not ensure that only one thread compiles a specific template at a given time (e.g. our startup page) - instead many threads tried to compile the &lt;b&gt;same&lt;/b&gt; template concurrently - this one is critical!&lt;br /&gt;
&lt;br /&gt;
That all being said, here comes the solution to such a "too-many-threads concurrency issue". Here's the code and I also added a class diagram 'cause I believe this is a common situation in web applications.&lt;br /&gt;
&lt;br /&gt;
The following snippet shows our new &lt;code&gt;HTMLDocumentGenerator&lt;/code&gt;, its responsibility is to create and cache &lt;code&gt;ConcurrentTransformer&lt;/code&gt; instances, one for each XSL document. The responsibility of &lt;code&gt;ConcurrentTransformer&lt;/code&gt; is to compile a XSL template and to store the result in its &lt;code&gt;template&lt;/code&gt; variable. &lt;code&gt;HTMLDocumentGenerator&lt;/code&gt; owns the cache (Line 3), defines a limit of threads that can compile XSL documents (Line 5) and declares a &lt;code&gt;Semaphore&lt;/code&gt; that implements a "thread bouncer" (Line 6). The &lt;code&gt;createDocument&lt;/code&gt;-Method (Lines 10-20) creates and caches the new &lt;code&gt;ConcurrentTransformer&lt;/code&gt; instances for each XSL document. Example: &lt;code&gt;/start/index.xsl&lt;/code&gt; will have its own &lt;code&gt;ConcurrentTransformer&lt;/code&gt; instance and &lt;code&gt;/start/main_menu.xsl&lt;/code&gt; will also have its own unique instance.&lt;br /&gt;
&lt;br /&gt;
&lt;script src="https://gist.github.com/1206220.js"&gt;
 
&lt;/script&gt;&lt;br /&gt;
&lt;br /&gt;
Notice that we use &lt;code&gt;ConcurrentHashmap.putIfAbsent()&lt;/code&gt; which allows cache lookup and cached object creation in a single step. This is equivalent to:&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="java" name="code"&gt;if (!map.containsKey(key))
   return map.put(key, value);
else
   return map.get(key);
&lt;/pre&gt;&lt;br /&gt;
This is a perfect approach in a multithreaded high volume application. You could do the same with owned locks or &lt;code&gt;synchronized&lt;/code&gt; blocks, but it will hardly be so safe (and fast!) like the example above. You will understand my statement if you look at the implementation of &lt;code&gt;ConcurrentHashmap&lt;/code&gt;. It locks segments internally and not the whole table! This allows very high volumes of concurrent access without lock contention. In Line 18 we call the method &lt;code&gt;generateTemplate&lt;/code&gt; that actually performs the CPU intense task (template compilation). &lt;br /&gt;
&lt;br /&gt;
In Line 5 we declared a &lt;code&gt;Semaphore&lt;/code&gt; which acts as a bouncer for the CPU intense code sections. Using this class you can control the number of concurrent threads that perform a certain task concurrently. It's important to declare the &lt;code&gt;Semaphore&lt;/code&gt; in the &lt;code&gt;HTMLDocumentGenerator&lt;/code&gt; class, 'cause the thread limit applies to all cached &lt;code&gt;ConcurrentTransformer&lt;/code&gt; instances. &lt;br /&gt;
&lt;br /&gt;
Now let's look at the &lt;code&gt;ConcurrentTransformer&lt;/code&gt; that I declared as a protected inner class of &lt;code&gt;HTMLDocumentGenerator&lt;/code&gt;. Using an inner class &lt;code&gt;ConcurrentTransformer&lt;/code&gt; instances have immediate access to member variables of &lt;code&gt;HTMLDocumentGenerator&lt;/code&gt;. There is one &lt;code&gt;ConcurrentTransformer&lt;/code&gt; for each unique XSL template. &lt;br /&gt;
&lt;br /&gt;
&lt;script src="https://gist.github.com/1206265.js"&gt;
 
&lt;/script&gt; &lt;br /&gt;
&lt;br /&gt;
Let's go through &lt;code&gt;generateTemplate&lt;/code&gt; step-by-step:&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Line 9&lt;/b&gt;: check if thread needs to compile this XSL template. If &lt;code&gt;false&lt;/code&gt;, return the compiled template. &lt;code&gt;mustCompile&lt;/code&gt; returns &lt;code&gt;true&lt;/code&gt; if for example the &lt;code&gt;template&lt;/code&gt; variable is &lt;code&gt;null&lt;/code&gt;, which means the template wasn't compiled yet. The first thread that enters &lt;code&gt;generateTemplate&lt;/code&gt; will get &lt;code&gt;mustCompile() = true&lt;/code&gt; 'cause the &lt;code&gt;ConcurrentTransformer&lt;/code&gt; was just created by that thread and the &lt;code&gt;template&lt;/code&gt; variable is &lt;code&gt;null&lt;/code&gt;.&lt;br /&gt;
&lt;b&gt;Line 12&lt;/b&gt;: Block all subsequent threads 'cause only ONE thread can compile THIS XSL template at a given time.&lt;br /&gt;
&lt;b&gt;Line 14&lt;/b&gt;: check again if thread needs to compile the XSL template. Sounds weird? Imagine a second thread that was blocked at Line 12 'cause the first call to &lt;code&gt;mustCompile&lt;/code&gt; returned &lt;code&gt;true&lt;/code&gt;. This thread does not need to compile again 'cause the other (faster/first) thread already compiled the template. &lt;br /&gt;
&lt;b&gt;Line 17&lt;/b&gt;: check if thread exceeds the permitted number of threads allowed to do compile jobs. Because the &lt;code&gt;bouncer&lt;/code&gt; was defined in the &lt;code&gt;HTMLDocumentGenerator&lt;/code&gt; only a limited number of threads will enter the next code block. This actually was the tricky part of the solution: Lock threads that want to compile a specific template but also ensure that the total number of active compilation tasks does not exceed a defined limit! Because the &lt;code&gt;bouncer&lt;/code&gt; applies to all cached &lt;code&gt;ConcurrentTransformer&lt;/code&gt; instances this is possible.&lt;br /&gt;
&lt;b&gt;Line 19-25&lt;/b&gt;: Do the actual compilation work which is the CPU intense part that aused the system overload.&lt;br /&gt;
&lt;b&gt;Line 27&lt;/b&gt;: Release a permit to allow other thread (in a different &lt;code&gt;ConcurrentTransformer&lt;/code&gt; instance) to enter the compilation code.&lt;br /&gt;
&lt;b&gt;Line 30&lt;/b&gt;: Release the lock so that other threads waiting for that XSL document can continue their processing. (they will return the template that was just compiled, see line 14)&lt;br /&gt;
&lt;br /&gt;
Done! This solution will enforce that (1) only one thread will try to compile a specific XSL document and that (2) only a limitted amount of threads can do compilation work. &lt;br /&gt;
&lt;br /&gt;
Here is the class diagram that shows the pattern-style structure of the solution:&lt;br /&gt;
&lt;br /&gt;
&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;a href="http://3.bp.blogspot.com/-uoJ3QttK0Tc/TmofMsbAINI/AAAAAAAAARY/3ohn5WHWJrs/s1600/ConcurrentTrasnformer.JPG" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"&gt;&lt;img border="0" height="177" src="http://3.bp.blogspot.com/-uoJ3QttK0Tc/TmofMsbAINI/AAAAAAAAARY/3ohn5WHWJrs/s320/ConcurrentTrasnformer.JPG" width="320" /&gt;&lt;/a&gt;&lt;/div&gt;&lt;b&gt;&lt;br /&gt;
&lt;br /&gt;
Sleeper bugs and why systems work by coincidence&lt;/b&gt;&lt;br /&gt;
&lt;br /&gt;
Some weeks ago I met &lt;a href="http://www.javaspecialists.eu/"&gt;Dr. Heinz Kabbutz&lt;/a&gt;. I attended his &lt;a href="http://www.javaspecialists.eu/courses/master.jsp"&gt;Java Specialist Master Course&lt;/a&gt; and he opened my eyes for problems like this. Multi-threading was his first lesson and he started by saying something like this: "Your web applications are not thread safe, they just work - by sheer coincidence!" Although its a provocative statement, he is not wrong by saying that ... The described concurrency bug was in our code for a _long_ time, say for 8 years? It just didn't show up. What changed? We migrated from WebSphere Application Server 6 to 7. And we decided to use a new XSL parser, optimized for z/OS. The old XSL parser performed good at compilation time, but the compilation result did not perform so well. The new XSL parser promised an optimized compilation result. But obviously it did take more CPU during compilation. Now, since the compilation was CPU intense with the new parser our consurrency bug turned out to be a big problem suddenly. I'd call that a "sleeper bug". It is there for years, and suddenly it sabotages your system. I believe there are many bugs like this in todays Java applications, and I believe it's not too provocative to say that you will also have some sleeper bugs in your systems. Your systems work - but by sheer coincidence! &lt;br /&gt;
&lt;br /&gt;
&lt;script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"&gt;
&lt;/script&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;script src="http://gist.github.com/raw/454771/gist-line-number-hack.js"&gt;
&lt;/script&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;script type="text/javascript"&gt;
addLineNumbersToAllGists()
&lt;/script&gt;&lt;img src="http://feeds.feedburner.com/~r/blogspot/BufQX/~4/sopsJbnZOCI" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://niklasschlimm.blogspot.com/feeds/1664006158566834428/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://niklasschlimm.blogspot.com/2011/09/your-web-applications-work-by-sheer.html#comment-form" title="7 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/5701415790759755571/posts/default/1664006158566834428?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/5701415790759755571/posts/default/1664006158566834428?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/blogspot/BufQX/~3/sopsJbnZOCI/your-web-applications-work-by-sheer.html" title="Your web applications work - by sheer coincidence!" /><author><name>Niklas Schlimm</name><uri>http://www.blogger.com/profile/12402045792243894660</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="24" height="32" src="http://1.bp.blogspot.com/-T7F8yoGErpc/TjlFwjgDvTI/AAAAAAAAAPo/Uqt54kYww9E/s220/Niki.JPG" /></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="http://3.bp.blogspot.com/-uoJ3QttK0Tc/TmofMsbAINI/AAAAAAAAARY/3ohn5WHWJrs/s72-c/ConcurrentTrasnformer.JPG" height="72" width="72" /><thr:total>7</thr:total><feedburner:origLink>http://niklasschlimm.blogspot.com/2011/09/your-web-applications-work-by-sheer.html</feedburner:origLink></entry><entry gd:etag="W/&quot;CkIERXk_eSp7ImA9WhdXFkQ.&quot;"><id>tag:blogger.com,1999:blog-5701415790759755571.post-6789796549183066235</id><published>2011-08-17T18:04:00.006+02:00</published><updated>2011-08-30T09:48:24.741+02:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2011-08-30T09:48:24.741+02:00</app:edited><category scheme="http://www.blogger.com/atom/ns#" term="Spring-CDI modules" /><title>JSR-299 CDI Interceptors for Spring Beans</title><content type="html">Another early release of a Spring-CDI module, this time it's the interceptor pattern implementation. It implements a JSR-299 compliant interceptor binding model for Spring managed beans. We will use that in our business applications for cross-cutting-concerns.&lt;br /&gt;
&lt;br /&gt;
&lt;a name='more'&gt;&lt;/a&gt;&lt;br /&gt;
&lt;div style="background-color: #cfe2f3; text-align: center;"&gt;&lt;b&gt;Please notice: The intention of my blog is to share and discuss ideas. If you use any of this in your applications you're acting at your own risk. &lt;/b&gt;&lt;/div&gt;&lt;br /&gt;
&lt;b&gt;JSR-299 interceptor pattern implementation&lt;/b&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Features&lt;/b&gt;&lt;br /&gt;
&lt;br /&gt;
The interceptor module provides the following features:&lt;br /&gt;
&lt;br /&gt;
- Use JSR-299 &lt;code&gt;@Interceptor&lt;/code&gt;, &lt;code&gt;@InterceptorBinding&lt;/code&gt;, &lt;code&gt;@AroundInvoke&lt;/code&gt; and &lt;code&gt;@Nonbinding&lt;/code&gt; annotations and their defined semantics in Spring managed beans&lt;br /&gt;
- Support interceptors on the class level (applied to all declared methods) as well as on specific methods (method-level interceptors)&lt;br /&gt;
- Support chains of multiple interceptors for the same target method&lt;br /&gt;
- Support scoped target beans&lt;br /&gt;
- Integrate with Spring AOP (CGLIB proxies only)&lt;br /&gt;
&lt;br /&gt;
Interceptors for lifecycle event callbacks are supported since Spring 2.5 and are therefore not subject of this Sping-CDI module (&lt;code&gt;@PostConstruct&lt;/code&gt; and &lt;code&gt;@PreDestroy&lt;/code&gt; annotations).&lt;br /&gt;
&lt;br /&gt;
This release of the Spring-CDI interceptor module does not support JSR318 &lt;code&gt;@Interceptors&lt;/code&gt; annotation. The CDI spec states: "If an interceptor does not declare an &lt;code&gt;@Interceptor&lt;/code&gt; annotation, it must be bound to beans using &lt;code&gt;@Interceptors&lt;/code&gt; or ejbjar.xml." Because JSR299 specifies &lt;code&gt;@InterceptorBinding&lt;/code&gt; as the binding mechanism I would not recommend to use &lt;/code&gt;@Interceptors&lt;/code&gt; annotation anymore.&lt;br /&gt;
&lt;br /&gt;
Timeout interceptors and default interceptors are not yet supported.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Download Link&lt;/b&gt;&lt;br /&gt;
&lt;br /&gt;
The Spring-CDI interceptor module is an usual Spring IoC-container extension delivered as JAR archive. You can download the module JAR and put that on the classpath of your Spring application.&lt;br /&gt;
&lt;br /&gt;
Compiled Spring-CDI interceptor module JAR: &lt;a href="https://github.com/nschlimm/spring-interceptor/blob/master/build/spring-interceptor-0.5.2.jar?raw=true"&gt;Version 0.5.2&lt;/a&gt;&lt;br /&gt;
Sources: &lt;a href="https://github.com/nschlimm/spring-interceptor/blob/master/build/spring-interceptor-0.5.2-sources.jar?raw=true"&gt;Version 0.5.2&lt;/a&gt;&lt;br /&gt;
API-Doc: &lt;a href="http://nschlimm.github.com/spring-interceptor/build/javadoc/apidocs/index.html"&gt;Version 0.5.2&lt;/a&gt;&lt;br /&gt;
&lt;br /&gt;
Everything is hosted &lt;a href="https://github.com/nschlimm/spring-interceptor"&gt;on a git repository on Github.com&lt;/a&gt;.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Dependencies&lt;/b&gt;&lt;br /&gt;
&lt;br /&gt;
Here are my runtime dependencies:&lt;br /&gt;
&lt;br /&gt;
&lt;pre name="code" class="xml"&gt;&lt;dependency&gt;
	&lt;groupid&gt;org.springframework&lt;/groupId&gt;
	&lt;artifactid&gt;spring-context&lt;/artifactId&gt;
	&lt;version&gt;3.0.5.RELEASE&lt;/version&gt;
&lt;/dependency&gt;

&lt;dependency&gt;
	&lt;groupid&gt;org.springframework&lt;/groupId&gt;
	&lt;artifactid&gt;org.springframework.aop&lt;/artifactId&gt;
	&lt;version&gt;3.0.5.RELEASE&lt;/version&gt;
&lt;/dependency&gt;

&lt;dependency&gt;
	&lt;groupid&gt;javax.enterprise&lt;/groupId&gt;
	&lt;artifactid&gt;cdi-api&lt;/artifactId&gt;
	&lt;version&gt;1.0&lt;/version&gt;
&lt;/dependency&gt;

&lt;dependency&gt;
	&lt;groupid&gt;org.jboss.spec.javax.interceptor&lt;/groupId&gt;
	&lt;artifactid&gt;jboss-interceptors-api_1.1_spec&lt;/artifactId&gt;
	&lt;version&gt;1.0.0.Final&lt;/version&gt;
&lt;/dependency&gt;

&lt;dependency&gt;
	&lt;groupid&gt;cglib&lt;/groupId&gt;
	&lt;artifactid&gt;cglib&lt;/artifactId&gt;
	&lt;version&gt;2.2.2&lt;/version&gt;
&lt;/dependency&gt;
&lt;/pre&gt;&lt;br /&gt;
&lt;b&gt;Configuration&lt;/b&gt;&lt;br /&gt;
&lt;br /&gt;
If the Spring-CDI interceptor module JAR and its dependencies are on your classpath, all you need to do is:&lt;br /&gt;
&lt;br /&gt;
(1) register &lt;code&gt;InterceptorAwareBeanFactoryPostProcessor&lt;/code&gt; in your application context&lt;br /&gt;
(2) define an &lt;code&gt;include-filter&lt;/code&gt; to include &lt;code&gt;javax.interceptor.Interceptor&lt;/code&gt; as component annotation in your &lt;code&gt;context:component-scan&lt;/code&gt; tag&lt;br /&gt;
&lt;br /&gt;
&lt;script src="https://gist.github.com/1151458.js"&gt; &lt;/script&gt;&lt;br /&gt;
&lt;br /&gt;
If you like to order your interceptors you need to configure the &lt;code&gt;interceptorOrder&lt;/code&gt; property of &lt;code&gt;InterceptorAwareBeanFactoryPostProcessor&lt;/code&gt;:&lt;br /&gt;
&lt;br /&gt;
&lt;script src="https://gist.github.com/1151678.js"&gt; &lt;/script&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Use Case&lt;/b&gt;&lt;br /&gt;
&lt;br /&gt;
The following code snippets show how you can use the interceptor pattern ones you have configured your Spring application as described above. For more complex scenarios see my unit test cases.&lt;br /&gt;
&lt;br /&gt;
Let's assume you have a business interface called: &lt;code&gt;Simple_MyServiceInterface&lt;/code&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;pre name="code" class="java"&gt;public interface Simple_MyServiceInterface {

	String sayHello();
	String sayHello(String what);
	String sayGoodBye();
	
}
&lt;/pre&gt;&lt;br /&gt;
This is your implementation of the service. &lt;br /&gt;
&lt;br /&gt;
&lt;pre name="code" class="java"&gt;@Component
@ReturnValueAdopted
public class Simple_MyServiceInterface_Impl implements Simple_MyServiceInterface {

	@Override
	public String sayHello() {
		return "Hello";
	}

	@Override
	public String sayHello(String what) {
		return what;
	}

	@Override
	public String sayGoodBye() {
		return "Good bye";
	}

}
&lt;/pre&gt;&lt;br /&gt;
Notice the &lt;code&gt;@ReturnValueAdopted&lt;/code&gt; annotation on the type level. It is an interceptor binding declaration:&lt;br /&gt;
&lt;br /&gt;
&lt;pre name="code" class="java"&gt;@Inherited
@InterceptorBinding
@Target({TYPE, METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface ReturnValueAdopted { }
&lt;/pre&gt;&lt;br /&gt;
This interceptor also declares the &lt;code&gt;@ReturnValueAdopted&lt;/code&gt; interceptor binding which means the interceptor is applied to the &lt;code&gt;Simple_MyServiceInterface_Impl&lt;/code&gt;. &lt;br /&gt;
&lt;br /&gt;
&lt;pre name="code" class="java"&gt;@Interceptor @ReturnValueAdopted
public class Simple_MyInterceptor {

	@AroundInvoke
	public String extendReturnValueWithSomeNonsense(InvocationContext ctx) throws Exception {
		String result = null;
		ctx.getContextData().put("Some", "Nonsense");
		try {
			result = (String)ctx.proceed();
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
		return result + "_hello_world";
	}
	
}
&lt;/pre&gt;&lt;br /&gt;
The &lt;code&gt;@Interceptor&lt;/code&gt; annotation declares the class as an interceptor. It will intercept all method calls on the &lt;code&gt;Simple_MyServiceInterface_Impl&lt;/code&gt; bean. More specifically it will extend the return values with "_hello_world". Also notice the context data written to the &lt;code&gt;InvocationContext&lt;/code&gt;. This allows chains of interceptors to exchange context data.&lt;br /&gt;
&lt;br /&gt;
You can now autowire the &lt;code&gt;Simple_MyServiceInterface_Impl&lt;/code&gt; bean into arbitrary beans:&lt;br /&gt;
&lt;br /&gt;
&lt;pre name="code" class="java"&gt;@ContextConfiguration("/test-context-interceptor-simple.xml")
@RunWith(SpringJUnit4ClassRunner.class)
@DirtiesContext
public class SimpleInterceptorTestCase {

	@Autowired // will be intercepted
	private Simple_MyServiceInterface someInterceptedBean;
	
	@Test
	public void testHelloWorldExtension() {
		Assert.assertTrue(someInterceptedBean.sayHello().equals("Hello_hello_world"));
	}
	
}
&lt;/pre&gt;&lt;br /&gt;
The injected bean will have the defined &lt;code&gt;Simple_MyInterceptor&lt;/code&gt; applied. When the &lt;code&gt;sayHello()&lt;/code&gt; method is called the interceptor will extend the return value with the "_hello_world" message.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;How it works&lt;/b&gt;&lt;br /&gt;
&lt;br /&gt;
The core is the &lt;code&gt;&lt;a href="http://nschlimm.github.com/spring-interceptor/build/javadoc/apidocs/com/schlimm/springcdi/interceptor/InterceptorAwareBeanFactoryPostProcessor.html"&gt;InterceptorAwareBeanFactoryPostProcessor&lt;/a&gt;&lt;/code&gt;. It uses two strategies to implement the logic. The &lt;code&gt;InterceptorResolutionLogic&lt;/code&gt; scans the application context for registered interceptors. The &lt;code&gt;InterceptorOrderingStrategy&lt;/code&gt; implements the ordering of chained interceptors for a target method call. The result of the data collection within these two strategies is stored in the &lt;code&gt;InterceptorMetaDataBean&lt;/code&gt;. The bean factory post processor also registers the &lt;code&gt;&lt;a href="http://nschlimm.github.com/spring-interceptor/build/javadoc/apidocs/com/schlimm/springcdi/interceptor/processor/InterceptorAwareBeanPostProcessor.html"&gt;InterceptorAwareBeanPostProcessor&lt;/a&gt;&lt;/code&gt; with creates a proxy for each intercepted bean. This proxy has the intercepted bean as target and the &lt;code&gt;&lt;a href="http://nschlimm.github.com/spring-interceptor/build/javadoc/apidocs/com/schlimm/springcdi/interceptor/processor/InterceptedBeanProxyAdvice.html"&gt;InterceptedBeanProxyAdvice&lt;/a&gt;&lt;/code&gt; as interceptor advice applied. This advice creates (and caches) the chains of user defined JSR299 interceptors for each unique method call. It retrieves the required meta data for chaining interceptors from the &lt;code&gt;InterceptorMetaDataBean&lt;/code&gt;.&lt;br /&gt;
&lt;br /&gt;
&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;a href="http://2.bp.blogspot.com/-twy9VmzGOoQ/TkvF4tb2qCI/AAAAAAAAARQ/s-P9GglzVcE/s1600/Fotor_so.TIF" imageanchor="1" style="margin-left:1em; margin-right:1em"&gt;&lt;img border="0" height="239" width="320" src="http://2.bp.blogspot.com/-twy9VmzGOoQ/TkvF4tb2qCI/AAAAAAAAARQ/s-P9GglzVcE/s320/Fotor_so.TIF" /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;
Try everything if you have some time left!&lt;img src="http://feeds.feedburner.com/~r/blogspot/BufQX/~4/lk4nJswnwuM" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://niklasschlimm.blogspot.com/feeds/6789796549183066235/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://niklasschlimm.blogspot.com/2011/08/jsr-299-cdi-interceptors-for-spring.html#comment-form" title="0 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/5701415790759755571/posts/default/6789796549183066235?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/5701415790759755571/posts/default/6789796549183066235?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/blogspot/BufQX/~3/lk4nJswnwuM/jsr-299-cdi-interceptors-for-spring.html" title="JSR-299 CDI Interceptors for Spring Beans" /><author><name>Niklas Schlimm</name><uri>http://www.blogger.com/profile/12402045792243894660</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="24" height="32" src="http://1.bp.blogspot.com/-T7F8yoGErpc/TjlFwjgDvTI/AAAAAAAAAPo/Uqt54kYww9E/s220/Niki.JPG" /></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="http://2.bp.blogspot.com/-twy9VmzGOoQ/TkvF4tb2qCI/AAAAAAAAARQ/s-P9GglzVcE/s72-c/Fotor_so.TIF" height="72" width="72" /><thr:total>0</thr:total><feedburner:origLink>http://niklasschlimm.blogspot.com/2011/08/jsr-299-cdi-interceptors-for-spring.html</feedburner:origLink></entry><entry gd:etag="W/&quot;CkECQXk7fCp7ImA9WhdXFkQ.&quot;"><id>tag:blogger.com,1999:blog-5701415790759755571.post-6469270087557540709</id><published>2011-08-01T07:07:00.010+02:00</published><updated>2011-08-30T09:51:00.704+02:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2011-08-30T09:51:00.704+02:00</app:edited><category scheme="http://www.blogger.com/atom/ns#" term="Java EE" /><category scheme="http://www.blogger.com/atom/ns#" term="Spring" /><category scheme="http://www.blogger.com/atom/ns#" term="Spring-CDI modules" /><title>JSR-299 CDI Decorators for Spring beans</title><content type="html">This blog is about my new Spring-CDI modules effort. It's pupose is to make useful CDI patterns like decorators or interceptors available to a Spring application. I do believe that the explicit pattern implementation in CDI is very useful. It makes it obvious and simple to use patterns for not so experienced developers. Therefore I decided to investigate how to make those patterns and the corresponding CDI annotations available for Spring managed beans. Here is the current status of my work. If you're interested and you have some time left, take a look or try out my early version of the Spring-CDI decorator module. The set-up is straight forward. You'll find all you need below.&lt;br /&gt;
&lt;br /&gt;
&lt;a name='more'&gt;&lt;/a&gt;&lt;br /&gt;
&lt;div style="background-color: #cfe2f3; text-align: center;"&gt;&lt;b&gt;Please notice: The intention of my blog is to share and discuss ideas. If you use any of this in your applications you're acting at your own risk. &lt;/b&gt;&lt;/div&gt;&lt;br /&gt;
&lt;b&gt;JSR-299 decorator pattern implementation&lt;/b&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Features&lt;/b&gt;&lt;br /&gt;
&lt;br /&gt;
The decorator module provides the following features:&lt;br /&gt;
&lt;br /&gt;
- Use JSR-299 &lt;code&gt;@Decorator&lt;/code&gt; and &lt;code&gt;@Delegate&lt;/code&gt; in Spring managed beans&lt;br /&gt;
- Support chains of multiple decorators for the same target delegate bean&lt;br /&gt;
- Allow to qualify decorators to decorate multiple implementations of the same interface with different decorators&lt;br /&gt;
- Support scoped beans, allow scoped decorators&lt;br /&gt;
- Integrate with Spring AOP, both dynamic JDK proxies and CGLIB proxies&lt;br /&gt;
- Allow definition of custom decorator and delegate annotations&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Download Link&lt;/b&gt;&lt;br /&gt;
&lt;br /&gt;
The Spring-CDI decorator module is an usual Spring IoC-container extension delivered as JAR archive. You can download the module JAR and put that on the classpath of your Spring application.&lt;br /&gt;
&lt;br /&gt;
Compiled Spring-CDI decorator module JAR: &lt;a href="https://github.com/nschlimm/spring-decorator/blob/master/build/spring-decorator-0.9.10.jar?raw=true"&gt;Version v0.9.10&lt;/a&gt;&lt;br /&gt;
Sources: &lt;a href="https://github.com/nschlimm/spring-decorator/blob/master/build/spring-decorator-0.9.10-sources.jar?raw=true"&gt;Version v0.9.10&lt;/a&gt;&lt;br /&gt;
API-Doc: &lt;a href="http://nschlimm.github.com/spring-decorator/build/javadoc/index.html"&gt;Version v0.9.10&lt;/a&gt;&lt;br /&gt;
&lt;br /&gt;
Everything is hosted &lt;a href="https://github.com/nschlimm/spring-decorator"&gt;on a git repository on Github.com&lt;/a&gt;.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Dependencies&lt;/b&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;script src="https://gist.github.com/1127845.js"&gt; &lt;/script&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Configuration&lt;/b&gt;&lt;br /&gt;
&lt;br /&gt;
If the Spring-CDI decorator module JAR and its dependencies are on your classpath, all you need to do is:&lt;br /&gt;
&lt;br /&gt;
(1) register &lt;code&gt;&lt;a href="https://github.com/nschlimm/spring-decorator/blob/master/sources/spring-decorator/src/main/java/com/schlimm/springcdi/decorator/DecoratorAwareBeanFactoryPostProcessor.java"&gt;DecoratorAwareBeanFactoryPostProcessor&lt;/a&gt;&lt;/code&gt; in your application context&lt;br /&gt;
(2) define an &lt;code&gt;include-filter&lt;/code&gt; to include &lt;code&gt;javax.decorator.Decorator&lt;/code&gt; as component annotation in your &lt;code&gt;context:component-scan&lt;/code&gt; tag&lt;br /&gt;
&lt;br /&gt;
&lt;script src="https://gist.github.com/1115465.js"&gt;
 
&lt;/script&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Use Case&lt;/b&gt;&lt;br /&gt;
&lt;br /&gt;
The following code snippets show how you can use the decorator pattern ones you have configured your Spring application as described above. For more complex scenarios see my unit test cases.&lt;br /&gt;
&lt;br /&gt;
Let's assume you have a business interface called: &lt;code&gt;MyService&lt;/code&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;script src="https://gist.github.com/1127852.js"&gt; &lt;/script&gt;&lt;br /&gt;
&lt;br /&gt;
This is your implementation of the service. &lt;br /&gt;
&lt;br /&gt;
&lt;script src="https://gist.github.com/1127856.js"&gt; &lt;/script&gt;&lt;br /&gt;
&lt;br /&gt;
You want to do some transaction and security stuff, but you do not want to mess up the business code with it.&lt;br /&gt;
&lt;br /&gt;
For security you'd write a decorator that points to the &lt;code&gt;MyService&lt;/code&gt; business service.&lt;br /&gt;
&lt;br /&gt;
&lt;script src="https://gist.github.com/1127869.js"&gt; &lt;/script&gt;&lt;br /&gt;
&lt;br /&gt;
To seperate the cross-cutting-concerns you write another decorator for transaction handling that points to the &lt;code&gt;MyService&lt;/code&gt; business service.&lt;br /&gt;
&lt;br /&gt;
&lt;script src="https://gist.github.com/1127871.js"&gt; &lt;/script&gt;&lt;br /&gt;
&lt;br /&gt;
Then you can just use standard Spring &lt;code&gt;@Autowired&lt;/code&gt; annotation to make that work. The injected bean will be decorated with your new security and transaction decorator.&lt;br /&gt;
&lt;br /&gt;
&lt;script src="https://gist.github.com/1127873.js"&gt; &lt;/script&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;How it works&lt;/b&gt;&lt;br /&gt;
&lt;br /&gt;
The core is the &lt;code&gt;&lt;a href="https://github.com/nschlimm/spring-decorator/blob/master/sources/spring-decorator/src/main/java/com/schlimm/springcdi/decorator/DecoratorAwareBeanFactoryPostProcessor.java" target="_blank"&gt;DecoratorAwareBeanFactoryPostProcessor&lt;/a&gt;&lt;/code&gt; that scans the registered bean definitions for existing decorators. It gathers meta data and stores that data in the &lt;code&gt;&lt;a href="https://github.com/nschlimm/spring-decorator/blob/master/sources/spring-decorator/src/main/java/com/schlimm/springcdi/decorator/model/DecoratorMetaDataBean.java" target="_blank"&gt;DecoratorMetaDataBean&lt;/a&gt;&lt;/code&gt;. The &lt;code&gt;&lt;a href="https://github.com/nschlimm/spring-decorator/blob/master/sources/spring-decorator/src/main/java/com/schlimm/springcdi/decorator/processor/DecoratorAwareBeanPostProcessor.java" target="_blank"&gt;DecoratorAwareBeanPostProcessor&lt;/a&gt;&lt;/code&gt; uses the meta data to wire the decorators into a chain and creates a CGLIB proxy that intercepts method calls to the target delegate bean. It redirects those calls to the decorator chain. The &lt;code&gt;&lt;a href="https://github.com/nschlimm/spring-decorator/blob/master/sources/spring-decorator/src/main/java/com/schlimm/springcdi/decorator/resolver/DecoratorAwareAutowireCandidateResolver.java" target="_blank"&gt;DecoratorAutowireCandidateResolver&lt;/a&gt;&lt;/code&gt; applies autowiring rules specific to the CDI decorator pattern. It also uses meta data to do that.&lt;br /&gt;
&lt;br /&gt;
&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;a href="http://3.bp.blogspot.com/-R0F8gDkgJ3s/TjXDgAoTBKI/AAAAAAAAAPg/khMk4bAdckA/s1600/design%2Bscatch.JPG" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"&gt;&lt;img border="0" height="303" src="http://3.bp.blogspot.com/-R0F8gDkgJ3s/TjXDgAoTBKI/AAAAAAAAAPg/khMk4bAdckA/s320/design%2Bscatch.JPG" width="320" /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;
&lt;b&gt;The two modes&lt;/b&gt;&lt;br /&gt;
&lt;br /&gt;
The &lt;code&gt;DecoratorAwareBeanFactoryPostProcessor&lt;/code&gt; accepts two runtime modes. The 'processor' (default) mode uses &lt;code&gt;&lt;a href="https://github.com/nschlimm/spring-decorator/blob/master/sources/spring-decorator/src/main/java/com/schlimm/springcdi/decorator/processor/DecoratorAwareBeanPostProcessor.java"&gt;DecoratorAwareBeanPostProcessor&lt;/a&gt;&lt;/code&gt; and the &lt;code&gt;&lt;a href="https://github.com/nschlimm/spring-decorator/blob/master/sources/spring-decorator/src/main/java/com/schlimm/springcdi/decorator/strategies/DecoratorChainingStrategy.java"&gt;DecoratorChainingStrategy&lt;/a&gt;&lt;/code&gt; to wire the decorator chain. The 'resolver' mode uses &lt;code&gt;&lt;a href="https://github.com/nschlimm/spring-decorator/blob/master/sources/spring-decorator/src/main/java/com/schlimm/springcdi/decorator/resolver/DecoratorAwareAutowireCandidateResolver.java"&gt;DecoratorAwareAutowireCandidateResolver&lt;/a&gt;&lt;/code&gt; to implement custom wiring logic based on complex wiring rules implemented in &lt;code&gt;&lt;a href="https://github.com/nschlimm/spring-decorator/blob/master/sources/spring-decorator/src/main/java/com/schlimm/springcdi/decorator/resolver/rules/ResolverCDIAutowiringRules.java"&gt;ResolverCDIAutowiringRules&lt;/a&gt;&lt;/code&gt;. The 'resolver' mode was just another option how one can implement such complex logic. I tried two different options and both work. The 'processor' alternative however implements simpler logic. Therefore it's my prefered mode at the moment.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Decorator Meta Data Model&lt;/b&gt;&lt;br /&gt;
&lt;br /&gt;
The &lt;code&gt;DecoratorAwareBeanFactoryPostProcessor&lt;/code&gt; scans bean definitions and stores meta data about the decorators and delegates in the application context. These are the model beans in their hierarchical access order:&lt;br /&gt;
&lt;br /&gt;
&lt;code&gt;&lt;a href="https://github.com/nschlimm/spring-decorator/blob/master/sources/spring-decorator/src/main/java/com/schlimm/springcdi/decorator/model/DecoratorMetaDataBean.java"&gt;DecoratorMetaDataBean.java&lt;/a&gt;&lt;/code&gt;: Top level entry point to the meta-data. Registered and available in the application context.&lt;br /&gt;
&lt;code&gt;&lt;a href="https://github.com/nschlimm/spring-decorator/blob/master/sources/spring-decorator/src/main/java/com/schlimm/springcdi/decorator/model/QualifiedDecoratorChain.java"&gt;QualifiedDecoratorChain.java&lt;/a&gt;&lt;/code&gt;: A chain of decorators for the same target delegate bean.&lt;br /&gt;
&lt;code&gt;&lt;a href="https://github.com/nschlimm/spring-decorator/blob/master/sources/spring-decorator/src/main/java/com/schlimm/springcdi/decorator/model/DecoratorInfo.java"&gt;DecoratorInfo.java&lt;/a&gt;&lt;/code&gt;: A decorator bean definition wrapper class.&lt;br /&gt;
&lt;code&gt;&lt;a href="https://github.com/nschlimm/spring-decorator/blob/master/sources/spring-decorator/src/main/java/com/schlimm/springcdi/decorator/model/DelegateField.java"&gt;DelegateField.java&lt;/a&gt;&lt;/code&gt;: Contains the delegate field of the decorator implementation.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Strategies&lt;/b&gt;&lt;br /&gt;
&lt;br /&gt;
The Spring-CDI decorator module is easy to adopt by users through the use of strategy pattern in many places. These are the strategies that allow users to change processing logic if required:&lt;br /&gt;
&lt;br /&gt;
&lt;code&gt;&lt;a href="https://github.com/nschlimm/spring-decorator/blob/master/sources/spring-decorator/src/main/java/com/schlimm/springcdi/decorator/strategies/DecoratorChainingStrategy.java"&gt;DecoratorChainingStrategy.java&lt;/a&gt;&lt;/code&gt;: Wires the decorators for a specific target delegate bean.&lt;br /&gt;
&lt;code&gt;&lt;a href="https://github.com/nschlimm/spring-decorator/blob/master/sources/spring-decorator/src/main/java/com/schlimm/springcdi/decorator/strategies/DecoratorOrderingStrategy.java"&gt;DecoratorOrderingStrategy.java&lt;/a&gt;&lt;/code&gt;: Orders the decorators for a specific target delegate bean.&lt;br /&gt;
&lt;code&gt;&lt;a href="https://github.com/nschlimm/spring-decorator/blob/master/sources/spring-decorator/src/main/java/com/schlimm/springcdi/decorator/strategies/DecoratorResolutionStrategy.java"&gt;DecoratorResolutionStrategy.java&lt;/a&gt;&lt;/code&gt;: Scans the bean factory for available decorator beans.&lt;br /&gt;
&lt;code&gt;&lt;a href="https://github.com/nschlimm/spring-decorator/blob/master/sources/spring-decorator/src/main/java/com/schlimm/springcdi/decorator/strategies/DelegateResolutionStrategy.java"&gt;DelegateResolutionStrategy.java&lt;/a&gt;&lt;/code&gt;: Searches the delegate bean for a specific decorator bean.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Decorator Autowiring Rules&lt;/b&gt;&lt;br /&gt;
&lt;br /&gt;
The 'processor' mode and the 'resolver' mode both use a custom &lt;code&gt;AutowireCandidateResolver&lt;/code&gt; applied to the current bean factory. The class is called &lt;code&gt;&lt;a href="https://github.com/nschlimm/spring-decorator/blob/master/sources/spring-decorator/src/main/java/com/schlimm/springcdi/decorator/resolver/DecoratorAwareAutowireCandidateResolver.java"&gt;DecoratorAwareAutowireCandidateResolver&lt;/a&gt;&lt;/code&gt; and it is applied to the bean factory in the &lt;code&gt;DecoratorAwareBeanFactoryPostProcessor&lt;/code&gt;. The custom resolver works with different rule sets. In the 'processor' mode it works with a very simple rule set called &lt;code&gt;&lt;a href="https://github.com/nschlimm/spring-decorator/blob/master/sources/spring-decorator/src/main/java/com/schlimm/springcdi/decorator/resolver/rules/BeanPostProcessorCDIAutowiringRules.java"&gt;BeanPostProcessorCDIAutowiringRules&lt;/a&gt;&lt;/code&gt;. In the 'resolver' mode it uses &lt;code&gt;&lt;a href="https://github.com/nschlimm/spring-decorator/blob/master/sources/spring-decorator/src/main/java/com/schlimm/springcdi/decorator/resolver/rules/ResolverCDIAutowiringRules.java"&gt;ResolverCDIAutowiringRules&lt;/a&gt;&lt;/code&gt; which is far more complex. If these rule sets are not sufficient for your autowiring logic, it's easy to apply additional rule sets by implementing a custom &lt;code&gt;&lt;a href="https://github.com/nschlimm/spring-decorator/blob/master/sources/spring-decorator/src/main/java/com/schlimm/springcdi/SpringCDIPlugin.java"&gt;SpringCDIPlugin&lt;/a&gt;&lt;/code&gt; and adding it to the &lt;code&gt;DecoratorAwareAutowireCandidateResolver&lt;/code&gt;.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Spring-CDI Plugin System&lt;/b&gt;&lt;br /&gt;
&lt;br /&gt;
The Spring-CDI decorator module contains two infrastructure interfaces that allow the modularized approach of Spring-CDI project: &lt;code&gt;&lt;a href="https://github.com/nschlimm/spring-decorator/blob/master/sources/spring-decorator/src/main/java/com/schlimm/springcdi/SpringCDIPlugin.java"&gt;SpringCDIPlugin&lt;/a&gt;&lt;/code&gt; and &lt;code&gt;&lt;a href="https://github.com/nschlimm/spring-decorator/blob/master/sources/spring-decorator/src/main/java/com/schlimm/springcdi/SpringCDIInfrastructure.java"&gt;SpringCDIInfrastructure&lt;/a&gt;&lt;/code&gt;. When I implement additional modules - like the interceptor module - users can decide which modules to use and import into their projects. It's not required to add all Spring-CDI functionality if one only needs decorators.&lt;img src="http://feeds.feedburner.com/~r/blogspot/BufQX/~4/UA8KYcMEclQ" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://niklasschlimm.blogspot.com/feeds/6469270087557540709/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://niklasschlimm.blogspot.com/2011/08/jsr-299-cdi-decorators-for-spring-beans.html#comment-form" title="5 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/5701415790759755571/posts/default/6469270087557540709?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/5701415790759755571/posts/default/6469270087557540709?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/blogspot/BufQX/~3/UA8KYcMEclQ/jsr-299-cdi-decorators-for-spring-beans.html" title="JSR-299 CDI Decorators for Spring beans" /><author><name>Niklas Schlimm</name><uri>http://www.blogger.com/profile/12402045792243894660</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="24" height="32" src="http://1.bp.blogspot.com/-T7F8yoGErpc/TjlFwjgDvTI/AAAAAAAAAPo/Uqt54kYww9E/s220/Niki.JPG" /></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="http://3.bp.blogspot.com/-R0F8gDkgJ3s/TjXDgAoTBKI/AAAAAAAAAPg/khMk4bAdckA/s72-c/design%2Bscatch.JPG" height="72" width="72" /><thr:total>5</thr:total><feedburner:origLink>http://niklasschlimm.blogspot.com/2011/08/jsr-299-cdi-decorators-for-spring-beans.html</feedburner:origLink></entry><entry gd:etag="W/&quot;DkEAQn87fCp7ImA9WhdSFk0.&quot;"><id>tag:blogger.com,1999:blog-5701415790759755571.post-736330485502904863</id><published>2011-07-17T11:27:00.615+02:00</published><updated>2011-07-25T16:37:23.104+02:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2011-07-25T16:37:23.104+02:00</app:edited><category scheme="http://www.blogger.com/atom/ns#" term="Git" /><category scheme="http://www.blogger.com/atom/ns#" term="Tutorials" /><title>More Git beginner commands</title><content type="html">In &lt;a href="http://niklasschlimm.blogspot.com/2011/07/top-10-git-commands-for-newbie.html"&gt;my other blog post&lt;/a&gt; I introduced 10 important Git commands. This blog is a listing of additional usefull commands when working with Git.&lt;br /&gt;
&lt;br /&gt;
&lt;a name='more'&gt;&lt;/a&gt;&lt;br /&gt;
&lt;div style="background-color: #cfe2f3; text-align: center;"&gt;Downloading a remote repository&lt;/div&gt;&lt;br /&gt;
If you like to copy a repository from Github.com (or any other remote address) to your local machine:&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush:bash"&gt;git clone https://nschlimm@github.com/nschlimm/spring-decorator.git
&lt;/pre&gt;&lt;br /&gt;
You can now work on the code and push the changes back to that remote repository if you like.&lt;br /&gt;
&lt;br /&gt;
&lt;div style="background-color: #cfe2f3; text-align: center;"&gt;Working with branches - changing your current context&lt;/div&gt;&lt;br /&gt;
A branch in Git is nothing else but the "current context" you are working in. Typically you start working in the "master" branch. Let's say you want to try some stuff and you're not sure if what you're doing is a good idea (which happens very often actually :-)). In that case you can create a new branch and experiment with your idea:&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush:bash"&gt;git branch [branch_name]&lt;/pre&gt;&lt;br /&gt;
When you just enter &lt;code&gt;git branch&lt;/code&gt; it will list your new branches.&lt;br /&gt;
&lt;br /&gt;
If you'd like to work with your new branch, you can write:&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush:bash"&gt;git checkout [branch_name]&lt;/pre&gt;&lt;br /&gt;
One important fact to notice: if you switch between branches it does not change the state of your modified files. Say you have a modified file &lt;code&gt;foo.java&lt;/code&gt;. You switch from &lt;code&gt;master&lt;/code&gt; branch to your new &lt;code&gt;some_crazy_idea&lt;/code&gt; branch. After the switch &lt;code&gt;foo.java&lt;/code&gt; will still be in modified state. You could commit it to &lt;code&gt;some_crazy_idea&lt;/code&gt; branch now. If you switch to the &lt;code&gt;master&lt;/code&gt; branch however this commit would not be visible, 'cause you did not commit within the &lt;code&gt;master&lt;/code&gt; branch context. If the file was new, you would not even see the file in your working tree anymore.&lt;br /&gt;
&lt;br /&gt;
If you want to let others know about your new idea you push the branch to the remote repository:&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush:bash"&gt;git push [remote_repository_name] [branch_name]&lt;/pre&gt;&lt;br /&gt;
You'd use &lt;code&gt;fetch&lt;/code&gt; instead of &lt;code&gt;push&lt;/code&gt; to get the changes in a remote branch into your local repository again.&lt;br /&gt;
&lt;br /&gt;
This is how you delete a branch again if you don't need it anymore:&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush:bash"&gt;git branch -d [branch_name]&lt;/pre&gt;&lt;br /&gt;
&lt;div style="background-color: #cfe2f3; text-align: center;"&gt;Removing files&lt;/div&gt;&lt;br /&gt;
If you accidentally committed something to a branch you can easily remove the file again. For example, to remove the &lt;code&gt;readme.txt&lt;/code&gt; file in your current branch: &lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush:bash"&gt;git rm --cached readme.txt&lt;/pre&gt;&lt;br /&gt;
The &lt;code&gt;--cached&lt;/code&gt; option only removes the file from the index. Your working directory remains unchanged.&lt;br /&gt;
&lt;br /&gt;
You can also remove a folder. The &lt;code&gt;.settings&lt;/code&gt; folder for an eclipse project - for instance - is nothing you should share with others:&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush:bash"&gt;git rm --cached -r some_eclipse_project/.settings&lt;/pre&gt;&lt;br /&gt;
After you ran the &lt;code&gt;rm&lt;/code&gt; command the file is still in the index (history of Git version control). You can permanently delete the complete history with this command:&lt;br /&gt;
&lt;br /&gt;
&lt;blockquote&gt;&lt;i&gt;Note: be very careful with commands like this and try them in a copy of your repository before you apply them to your productive repository. Always create a copy of the complete repository before you run such commands.&lt;/i&gt;&lt;/blockquote&gt;&lt;br /&gt;
&lt;pre class="brush:bash"&gt;git filter-branch --index-filter 'git rm --cached --ignore-unmatch [your_file_name]' HEAD&lt;/pre&gt;&lt;br /&gt;
&lt;div style="background-color: #cfe2f3; text-align: center;"&gt;Ignoring files: you do not want to version control a certain file or directory&lt;/div&gt;&lt;br /&gt;
To ignore files you just add the file name to the &lt;code&gt;.gitignore&lt;/code&gt; file in the directory that owns the file. This way it will not be added to version control anymore. Here is my &lt;code&gt;.gitignore&lt;/code&gt; for the root directory of an Eclipse project:&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush:java"&gt;/target
/.settings
.project
.classpath
&lt;/pre&gt;&lt;br /&gt;
It ignores the &lt;code&gt;target&lt;/code&gt; and the &lt;code&gt;.settings&lt;/code&gt; folder as well as the &lt;code&gt;.project&lt;/code&gt; and the &lt;code&gt;.classpath&lt;/code&gt; file. &lt;br /&gt;
&lt;br /&gt;
Sometimes its helpful to configure global ignore rules that apply to the complete repository:&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush:bash"&gt;git config --global core.excludesfile ~/.gitignore_global &lt;/pre&gt;&lt;br /&gt;
This added the following entry to my &lt;code&gt;.gitconfig&lt;/code&gt; global parameters file which resides in the git root directory.&lt;br /&gt;
&lt;br /&gt;
&lt;code&gt;excludesfile = d:/dev_home/repositories/git/.gitignore_global&lt;/code&gt;&lt;br /&gt;
&lt;br /&gt;
These are my current global exclude rules in my &lt;code&gt;.gitignore_global&lt;/code&gt; file:&lt;br /&gt;
&lt;br /&gt;
&lt;code&gt;# Compiled source #&lt;br /&gt;
###################&lt;br /&gt;
*.com&lt;br /&gt;
*.class&lt;br /&gt;
*.dll&lt;br /&gt;
*.exe&lt;br /&gt;
*.o&lt;br /&gt;
*.so&lt;br /&gt;
# Logs and databases #&lt;br /&gt;
######################&lt;br /&gt;
*.log&lt;/code&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;blockquote&gt;&lt;i&gt;Note: these rules are shared with other users. Local per-repo rules can be added to the .git/info/exclude file in your repo. These rules are not committed with the repo so they are not shared with others.&lt;/i&gt;&lt;/blockquote&gt;&lt;br /&gt;
&lt;div style="background-color: #cfe2f3; text-align: center;"&gt;Restoring files - put the clocks back&lt;/div&gt;&lt;br /&gt;
Sometimes you make changes to your files and after some time you realize that what you've done was a bad idea. You want go back to your last commit state then. If you made changes to your working directory and you want to restore your last HEAD commit in your working directory enter:&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush:bash"&gt;git reset --hard HEAD&lt;/pre&gt;&lt;br /&gt;
This command sets the current branch head to the last commit (HEAD) and overwrites your local working directory with that last commit state (the &lt;code&gt;--hard&lt;/code&gt; option). So it will overwrite your modified files. &lt;br /&gt;
&lt;br /&gt;
Instead of HEAD (which is your last commit) you could name a branch or a tag like 'v0.6'. You can also reset to a previous commit: HEAD~2 is the commit before your last commit. &lt;br /&gt;
&lt;br /&gt;
May be you want to restore a file you have deleted in your working directory. Here is what I've entered to restore a java file I have deleted accidentally:&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush:bash"&gt;git checkout HEAD sources/spring-decorator/src/test/java/com/schlimm/decorator/simple/SetupSession.java&lt;/pre&gt;&lt;br /&gt;
Again: Instead of HEAD you could name a branch or a tag like 'v0.6'. You can draw the file from a previous commit: HEAD~2 is the commit before your last commit.&lt;br /&gt;
&lt;br /&gt;
&lt;div style="background-color: #cfe2f3; text-align: center;"&gt;Working with tags - making bookmarks to your source code&lt;/div&gt;&lt;br /&gt;
Sometimes you want to make a version of your source code. This way you can refer to it later on. To apply a version tag v1.0.0 to your files you'd write:&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush:bash"&gt;git tag -a v1.0.0 -m "Creating the first official version"&lt;/pre&gt;&lt;br /&gt;
You can share your tags with others in a remote repository:&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush:bash"&gt;git push [remote_repository_name] --tags&lt;/pre&gt;&lt;br /&gt;
Where &lt;code&gt;remote_repository_name&lt;/code&gt; is the alias name for your remote repository. You write &lt;code&gt;fetch&lt;/code&gt; instead of &lt;code&gt;push&lt;/code&gt; to get tags that others committed to the remote repository down to your local repository.&lt;br /&gt;
&lt;br /&gt;
If you just enter &lt;code&gt;git tag&lt;/code&gt; it will give you the list of known tags. To get infos about the v1.0.0 tag, you'd write:&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush:bash"&gt;git show v1.0.0 -s&lt;/pre&gt;&lt;br /&gt;
If you want to continue work on a tag, for instance on the production branch with version v5.0.1, you enter:&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush:bash"&gt;git checkout v5.0.1 -b [your_production_branch]&lt;/pre&gt;&lt;br /&gt;
Note that this command also creates a new branch for the tag, this way you can make commits and anything else you wish to record back to the repository.&lt;br /&gt;
&lt;br /&gt;
That's all for now. These commands and the ones &lt;a href="http://niklasschlimm.blogspot.com/2011/07/top-10-git-commands-for-newbie.html"&gt;from my last post&lt;/a&gt; should give you everything you need for the day-to-day work with Git. Go experiment a little. Type &lt;code&gt;git help [command]&lt;/code&gt; to get to the Git manual page. And don't forget to celebrate if you get all the stuff running :-)&lt;img src="http://feeds.feedburner.com/~r/blogspot/BufQX/~4/WADjT_nUa0s" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://niklasschlimm.blogspot.com/feeds/736330485502904863/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://niklasschlimm.blogspot.com/2011/07/more-git-commands-rank-11-to-20.html#comment-form" title="0 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/5701415790759755571/posts/default/736330485502904863?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/5701415790759755571/posts/default/736330485502904863?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/blogspot/BufQX/~3/WADjT_nUa0s/more-git-commands-rank-11-to-20.html" title="More Git beginner commands" /><author><name>Niklas Schlimm</name><uri>http://www.blogger.com/profile/12402045792243894660</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="24" height="32" src="http://1.bp.blogspot.com/-T7F8yoGErpc/TjlFwjgDvTI/AAAAAAAAAPo/Uqt54kYww9E/s220/Niki.JPG" /></author><thr:total>0</thr:total><feedburner:origLink>http://niklasschlimm.blogspot.com/2011/07/more-git-commands-rank-11-to-20.html</feedburner:origLink></entry></feed>
