<?xml version='1.0' encoding='UTF-8'?><?xml-stylesheet href="http://www.blogger.com/styles/atom.css" type="text/css"?><feed xmlns='http://www.w3.org/2005/Atom' xmlns:openSearch='http://a9.com/-/spec/opensearchrss/1.0/' xmlns:georss='http://www.georss.org/georss' xmlns:gd='http://schemas.google.com/g/2005' xmlns:thr='http://purl.org/syndication/thread/1.0'><id>tag:blogger.com,1999:blog-7677021887363364182</id><updated>2011-11-27T16:25:34.335-08:00</updated><title type='text'>Tobe expressed</title><subtitle type='html'></subtitle><link rel='http://schemas.google.com/g/2005#feed' type='application/atom+xml' href='http://tobega.blogspot.com/feeds/posts/default'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7677021887363364182/posts/default?max-results=100'/><link rel='alternate' type='text/html' href='http://tobega.blogspot.com/'/><link rel='hub' href='http://pubsubhubbub.appspot.com/'/><author><name>tobe</name><uri>http://www.blogger.com/profile/00792674914237130365</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='26' height='32' src='http://bp1.blogger.com/_OD0rKvKkvVw/R8f0-n5OxgI/AAAAAAAAAAM/toWm_WfWjVU/S220/tobe.jpg'/></author><generator version='7.00' uri='http://www.blogger.com'>Blogger</generator><openSearch:totalResults>14</openSearch:totalResults><openSearch:startIndex>1</openSearch:startIndex><openSearch:itemsPerPage>100</openSearch:itemsPerPage><entry><id>tag:blogger.com,1999:blog-7677021887363364182.post-2921199182552630186</id><published>2011-01-05T21:49:00.000-08:00</published><updated>2011-01-05T22:58:28.700-08:00</updated><title type='text'>Prove your assumptions, but remember Murphy was an optimist</title><content type='html'>Continuing on my unremarkable coding task, having gotten it to work, it was now time to clean up the code.&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Given the large load expected, I couldn't allocate a new direct ByteBuffer for every piece of data I wanted to handle. But code that accepts a ByteBuffer is equivalent to code that accepts a byte array, a starting offset and a length (or a limit), right? So I just set the position and the limit on the boundaries of the data and I'm good to go.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Now I ran into some of my own previous assumptions. Luckily, the failure resulted in a log message that made it clear where something was going wrong. It was one of those places where a deviation from the happy path either cannot happen, should not happen or we didn't really care too much. A place where I used to code an empty block "&lt;span class="Apple-style-span"  style="font-family:'courier new';"&gt;{}&lt;/span&gt;", or when I was feeling diligent, with a comment "&lt;span class="Apple-style-span"  style="font-family:'courier new';"&gt;{/*cannot happen*/}&lt;/span&gt;".  Now I'll code it as "&lt;span class="Apple-style-span"  style="font-family:'courier new';"&gt;{throw new AssertionError("Cannot happen.");}&lt;/span&gt;" or at least "&lt;span class="Apple-style-span"  style="font-family:'courier new';"&gt;{LOG.fine("Don't care.");}&lt;/span&gt;".&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Anyway, a quick analysis showed a likely cause. I say likely, because it's an assumption until proven. I wrote a quick unit test that failed, fixed the code and the test passed. But the program still failed, with the same log message as before. Imagine what I might have been doing if I hadn't proven the failure and the fix with the unit test, I'd still be staring at the same place and possibly ripping my code to shreds in desperation. Now I could immediately move on and fix the second error.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;OK, on a roll now, all assumptions proven by assertions, I'm just about done. Except that the code still doesn't work and no sign of why. Murphy's law in full action.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Finally I find it. There's a trap in ExecutorService. What's the difference between calling "&lt;span class="Apple-style-span"  style="font-family:'courier new';"&gt;execute(Runnable)&lt;/span&gt;" versus "&lt;span class="Apple-style-span"  style="font-family:'courier new';"&gt;submit(Runnable)&lt;/span&gt;"? Nothing much, when the code works. But "&lt;span class="Apple-style-span"  style="font-family:'courier new';"&gt;submit(Runnable)&lt;/span&gt;" should have a big red warning sticker. It returns a Future, with no result. You don't bother to "&lt;span class="Apple-style-span"  style="font-family:'courier new';"&gt;get()&lt;/span&gt;" nothing. The devastating side-effect is that all exceptions get preserved until "&lt;span class="Apple-style-span"  style="font-family:'courier new';"&gt;get()&lt;/span&gt;" is called, so this is a hidden equivalent of "&lt;span class="Apple-style-span"  style="font-family:'courier new';"&gt;catch(Exception e){}&lt;/span&gt;". Next task: change this everywhere and add a rule to FindBugs.&lt;/div&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7677021887363364182-2921199182552630186?l=tobega.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://tobega.blogspot.com/feeds/2921199182552630186/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=7677021887363364182&amp;postID=2921199182552630186' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7677021887363364182/posts/default/2921199182552630186'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7677021887363364182/posts/default/2921199182552630186'/><link rel='alternate' type='text/html' href='http://tobega.blogspot.com/2011/01/prove-your-assumptions-but-remember.html' title='Prove your assumptions, but remember Murphy was an optimist'/><author><name>tobe</name><uri>http://www.blogger.com/profile/00792674914237130365</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='26' height='32' src='http://bp1.blogger.com/_OD0rKvKkvVw/R8f0-n5OxgI/AAAAAAAAAAM/toWm_WfWjVU/S220/tobe.jpg'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7677021887363364182.post-1930381224271335762</id><published>2011-01-01T11:06:00.001-08:00</published><updated>2011-01-02T04:10:52.925-08:00</updated><title type='text'>Your assumptions are dangerous, you know too much.</title><content type='html'>I have just completed a rather unremarkable piece of code. The system was designed to allow this type of addition, so it just took a couple of hours or three to write the code and touch up the parts to selectively enable the functionality by user.&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Then a colleague and I spent two days debugging. We hacked around issue after issue, just to prove basic workability before trying to solve the issues.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;The final obstacle was that our socket channel was not being selected for reading on the selector. So I hacked around that by creating a new thread to loop infinitely around reading the channel. Which made things work fine up to the point where actual data was coming in and the server blew up with a segmentation fault.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;After reflecting while travelling on the bus home, I remembered that perhaps our JNI code needed a direct byte buffer, with data starting at position 0 and the whole backing array available for use. Inconvenient in this case, but another little hack and everything worked like a charm.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Back to the previous question: why no reads? Perhaps my server socket in non-blocking mode actually returned a socket configured for blocking mode instead of for non-blocking mode? It did, and explicitly setting it to non-blocking fixed it.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;As I backtracked through the issues, it struck me that every single problem we'd run into had to do with assumptions.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;I could of course have checked my assumption about the blocking mode. But I also have another assumption, which is more valid: incorrect usage of an API should not fail silently. This turns out to be correct, because a SelectableChannel throws an IllegalBlockingModeException. &lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Unfortunately, the "helper" framework that we have in place inadvertently masked that by running the register call in a FutureTask that had a boolean "success" return value that nobody had found the need to check, because "true" was the only possibility. Well, that is, assuming no exceptions are thrown.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Perhaps there is also a flaw in the assumption that a helper framework that obscures the standard API is actually helpful.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;div&gt;Certainly, the direct byte buffer assumption mentioned above should probably have been asserted somewhere, it's easy enough to throw an IllegalArgumentException if buffer.isDirect() returns false. Obviously, the programmer who created the JNI call was not assuming we had a direct byte buffer, he knew we had one. But that's the trick of maintainable and re-usable object oriented code: you cannot rely on any knowledge outside the class you are currently in. From the point of view of the class, such knowledge is an assumption.&lt;/div&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Another issue I had hit on the way concerned the UserIdentifier class. It is really just a wrapper around a string, but because it has a specific semantic meaning it was correctly exposed as a separate value class. To limit the new functionality by groups of users, I found it convenient to construct the user identifier slightly differently. The code did not work as expected.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;At another point in the code, a programmer had used his knowledge of how the user identifier was constructed, which introduced a hidden assumption about the structure of the user identifier. The correct code would have been to obtain the user identifier from a single authoritative place.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;The root cause of the user identifier hack was a design assumption that two things were independent. When they were not, a co-dependency web was created. In a sense, this is also a case of classes having too much knowledge: they knew about too many different other classes that they needed to collaborate with. To keep your code clean and honest, such things need to be refactored (re-designed).&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Consider the small amount of care and time it would have taken to avoid the assumptions in the first place and compare it to the four man-days of lost productivity that was caused. We are always under time pressure, but that will be the case next week, month or year as well. If you don't pay the price now, you pay it with interest later.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;The more things your classes know about your system, the harder it is to change or re-use the code. Make sure that the knowledge you put into a class is appropriate and doesn't create a dangerous web of assumptions.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7677021887363364182-1930381224271335762?l=tobega.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://tobega.blogspot.com/feeds/1930381224271335762/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=7677021887363364182&amp;postID=1930381224271335762' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7677021887363364182/posts/default/1930381224271335762'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7677021887363364182/posts/default/1930381224271335762'/><link rel='alternate' type='text/html' href='http://tobega.blogspot.com/2011/01/your-assumptions-are-dangerous-you-know.html' title='Your assumptions are dangerous, you know too much.'/><author><name>tobe</name><uri>http://www.blogger.com/profile/00792674914237130365</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='26' height='32' src='http://bp1.blogger.com/_OD0rKvKkvVw/R8f0-n5OxgI/AAAAAAAAAAM/toWm_WfWjVU/S220/tobe.jpg'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7677021887363364182.post-400957207855204856</id><published>2009-08-28T11:43:00.000-07:00</published><updated>2009-08-28T13:26:26.758-07:00</updated><title type='text'>Clarity of code is clarity of thought</title><content type='html'>I remember at my first job when we introduced the concept of code reviews. I don't think anybody really looked at anybody else's code before pressing the "approve" button, I know I didn't. Reading code is boring and it can be hard and it felt like a waste of time. I had my own code to write and why shouldn't the author of the code have written it right in the first place?&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;When I moved to another job, they talked about how, in theory, code reviews was the number one most effective way to increase code quality. But they had given up on it, because they felt it came down to a discussion of where to put the dots and commas (or, rather, semi-colons and parentheses).&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Quite aside from the issue of code reviews, I had come to realize that I spent much more time reading my code than I spent writing it. Every debugging session is spent reading code over and over. Every time you have to add a feature or change some functionality you have to read the code, and re-read it to avoid breaking stuff. Don't tell me tests will do it for you. Now don't get me wrong, tests are great and I strongly advocate test-first coding, it's a great way to achieve focus and clarity of thought. But when a test fails, you're thrown into debugging mode, which means reading code.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;So I concluded it was worth spending a little extra time typing longer variable names, and taking the time to find descriptive names. It was worth spending a little more time breaking down those long methods and simplifying those complex structures. Whenever I was reading code that made me stop and think, I would usually refactor  it to be clearer (although the term refactoring hadn't been invented yet). I would also change existing code to make a new feature fit in better, in a more readable and more logical way.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;In "The Pragmatic Programmer" the distinction is made between "programming by coincidence" and "programming by intention". We all have to do it occasionally, a little trial-and-error programming, because we're not quite sure how things work. That's "programming by coincidence". Before you check your code in, you want to make sure you understand what each statement does and that all unnecessary statements are removed. Then you've transformed the code from coincidental to intentional.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;But that's not enough. Your very functional and intentional code is going to lose you valuable time unless you also transform it to readable code, which clearly displays your intent.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;A much-touted wisdom is that you should document and comment your code. Fair enough, that works, but it has many weaknesses. Your energy is far better spent making the code explain itself. Comments often lie, but the code is always pure truth, so prove it in code. Only comment on "why" you are doing something, and that only if you cannot make it evident in the code.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;I like the following sound-bite from "Refactoring": "Any fool can write code that a machine can understand, it takes a good programmer to write code that a human can understand."&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Test-first "anything" is efficient and focused because it sets up the criteria for success and the means to measure it up front. So what's the best way to test if your code is readable? Get another person to read it, i.e. a code review.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;div&gt;I'm very grateful to those who review my code carefully and pick on every detail, it makes the code better and it helps assert that my thinking was clear. That gratitude gives me the energy to return the favour by reviewing their code equally mercilessly.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;/div&gt;&lt;div&gt;You will sometimes, but rarely, find bugs by just reading code (only because everybody has a brain-fart now and then). But the real value of the reviews is in the "dot and comma" discussions and especially in picking good names. In addition to making sure that the code is easy to read, it will sometimes bring a real little nasty bug to the surface.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;An example: An index into an array of values is stored into a variable called "value". When the reviewer makes you change the name to "valueIndex" instead, some parts of your code may start to look weird (the bug was exposed).&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Clarity of code really is clarity of thought.&lt;/div&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7677021887363364182-400957207855204856?l=tobega.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://tobega.blogspot.com/feeds/400957207855204856/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=7677021887363364182&amp;postID=400957207855204856' title='38 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7677021887363364182/posts/default/400957207855204856'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7677021887363364182/posts/default/400957207855204856'/><link rel='alternate' type='text/html' href='http://tobega.blogspot.com/2009/08/clarity-of-code-is-clarity-of-thought.html' title='Clarity of code is clarity of thought'/><author><name>tobe</name><uri>http://www.blogger.com/profile/00792674914237130365</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='26' height='32' src='http://bp1.blogger.com/_OD0rKvKkvVw/R8f0-n5OxgI/AAAAAAAAAAM/toWm_WfWjVU/S220/tobe.jpg'/></author><thr:total>38</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7677021887363364182.post-1238570520350719651</id><published>2008-12-25T14:22:00.000-08:00</published><updated>2008-12-25T15:27:12.954-08:00</updated><title type='text'>Using Java concurrency utilities</title><content type='html'>The inspiration for this post comes from &lt;a href="http://weblogs.java.net/blog/jhook/archive/2008/12/accelerating_ap_1.html"&gt;Jacob Hookom's blog&lt;/a&gt; and I can only second the recommendations he gives. Although, as always, I would caution to test any such implementation properly, that it works well and &lt;a href="http://smallwig.blogspot.com/2008/04/smallwig-theory-of-optimization.html"&gt;actually provides a benefit&lt;/a&gt;. There are lots of pitfalls and concurrency is tricky even with the excellent utilities provided in Java.&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;To summarize the interesting problem: parallelize the execution of lengthy tasks in a web request, without creating many threads for each request, but also ensuring that the thread pool is not starved by one request. The idea is to have a reasonably sized thread pool and to limit the number of tasks executing in parallel to a number small enough to allow the expected amount of concurrent requests to share the pooled threads.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Essentially, limiting the number of tasks executing in parallel can be done in two ways: limit the number of tasks submitted at one time or limit the number of workers that execute a set of tasks. Jacob takes the first approach, I will take the second approach, which seems to make it simpler to manage time-out issues.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Here's some code:&lt;/div&gt;&lt;pre&gt;&lt;br /&gt;&amp;lt;V&amp;gt; Queue&amp;lt;Future&amp;gt;&amp;lt;V&amp;gt;&amp;gt; submit(int numberOfWorkers, Queue&amp;lt;Callable&amp;gt;&amp;lt;V&amp;gt;&amp;gt; tasks,&lt;br /&gt;                           long timeout, TimeUnit unit)&lt;br /&gt;  throws InterruptedException, TimeoutException {&lt;br /&gt;Queue&amp;lt;Future&amp;gt;&amp;lt;V&amp;gt;&amp;gt; result = new ConcurrentLinkedQueue&amp;lt;Future&amp;gt;&amp;lt;V&amp;gt;&amp;gt;();&lt;br /&gt;List&amp;lt;WorkerTask&amp;gt;&amp;lt;V&amp;gt;&amp;gt; workers = new ArrayList&amp;lt;WorkerTask&amp;gt;&amp;lt;V&amp;gt;&amp;gt;(numberOfWorkers);&lt;br /&gt;for (int i = 0; i &amp;lt; numberOfWorkers; i++) {&lt;br /&gt;   workers.add(new WorkerTask&amp;lt;V&amp;gt;(result, tasks));&lt;br /&gt;}&lt;br /&gt;List&amp;lt;Future&amp;gt;&amp;lt;Object&amp;gt;&amp;gt; deadWorkers&lt;br /&gt;    = executor.invokeAll(workers, timeout, unit);&lt;br /&gt;for (Future&amp;lt;Object&amp;gt; obituary : deadWorkers) {&lt;br /&gt;  if (obituary.isCancelled()) {&lt;br /&gt;    throw new TimeoutException();&lt;br /&gt;  }&lt;br /&gt;}&lt;br /&gt;return result;&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;div&gt;And the code for a WorkerTask:&lt;/div&gt;&lt;pre&gt;&lt;br /&gt;private static class WorkerTask&amp;lt;V&amp;gt; implements Callable&amp;lt;Object&amp;gt; {&lt;br /&gt;&lt;br /&gt;private Queue&amp;lt;Callable&amp;gt;&amp;lt;V&amp;gt;&amp;gt; tasks;&lt;br /&gt;private Queue&amp;lt;Future&amp;gt;&amp;lt;V&amp;gt;&amp;gt; result;&lt;br /&gt;&lt;br /&gt;public WorkerTask(Queue&amp;lt;Future&amp;gt;&amp;lt;V&amp;gt;&amp;gt; result, Queue&amp;lt;Callable&amp;gt;&amp;lt;V&amp;gt;&amp;gt; tasks) {&lt;br /&gt;   this.result = result;&lt;br /&gt;   this.tasks = tasks;&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;public Object call() {&lt;br /&gt;  for (Callable&amp;lt;V&amp;gt; task = tasks.poll(); task != null; task = tasks.poll()) {&lt;br /&gt;  FutureTask&amp;lt;V&amp;gt; future = new FutureTask&amp;lt;V&amp;gt;(task);&lt;br /&gt;    future.run();&lt;br /&gt;    if (Thread.interrupted()) {&lt;br /&gt;      Thread.currentThread().interrupt(); // Restore interrupt.&lt;br /&gt;      break;&lt;br /&gt;    }&lt;br /&gt;    result.add(future);&lt;br /&gt;  }&lt;br /&gt;  return null;&lt;br /&gt;}&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;div&gt;Note that it is important to have thread-safe collections for tasks and result, we should actually make sure that the tasks are in a thread-safe collection, but I'll ignore that for now. Note also the check if the thread has been interrupted in the call() method of WorkerTask. That is vital to be able to cancel the task when you don't want to wait for it any longer (i.e. on time-out). If possible, the submitted tasks should also handle interrupts. Note the careful restoration of the interrupt status so that the caller of the method may also be notified.&lt;br /&gt;&lt;/div&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7677021887363364182-1238570520350719651?l=tobega.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://tobega.blogspot.com/feeds/1238570520350719651/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=7677021887363364182&amp;postID=1238570520350719651' title='3 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7677021887363364182/posts/default/1238570520350719651'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7677021887363364182/posts/default/1238570520350719651'/><link rel='alternate' type='text/html' href='http://tobega.blogspot.com/2008/12/using-java-concurrency-utilities.html' title='Using Java concurrency utilities'/><author><name>tobe</name><uri>http://www.blogger.com/profile/00792674914237130365</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='26' height='32' src='http://bp1.blogger.com/_OD0rKvKkvVw/R8f0-n5OxgI/AAAAAAAAAAM/toWm_WfWjVU/S220/tobe.jpg'/></author><thr:total>3</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7677021887363364182.post-1292945835961222977</id><published>2008-11-24T12:55:00.000-08:00</published><updated>2008-11-24T14:24:29.739-08:00</updated><title type='text'>GC is for Goodstuff Collector</title><content type='html'>I have over the past few months noticed that there is a fairly common fear of creating objects in Java. When I query the authors, it always seems to boil down to an attempt to create more performant code through avoiding garbage collection.&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;So why would one want to create more objects, anyway? Well, one good reason would be to get more readable code, e.g. through &lt;a href="'http://www.refactoring.com/catalog/replaceMethodWithMethodObject.html'"&gt;encapsulating an algorithm&lt;/a&gt; or using appropriate helper objects to express an algorithm more clearly.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Even when the code does get put into a helper object, there seems to be a tendency to keep that instance around and reuse it, to avoid garbage collection so that the code performs better. My first comment is always "You should measure that". If I wanted to put it more sharply I should say "If you can't prove it's a performance benefit, then it probably isn't". I have worked with enough optimization to know that what's true for one language will not be true for another. Even using the same language, something that gives a performance benefit on one machine may be a detriment on another kind of machine (or even the same kind of machine with different "tweaks" like page sizes and such).&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;If you create a temporary object that lives only as long as you need it you gain the following benefits:&lt;/div&gt;&lt;div&gt;&lt;ol&gt;&lt;li&gt;Your object is always in a pristine state when you want to use it.&lt;/li&gt;&lt;li&gt;Your code is a big step closer to being thread safe.&lt;/li&gt;&lt;li&gt;Your code is more readable and easier to analyze.&lt;/li&gt;&lt;li&gt;Your garbage collector gets to do less work.&lt;/li&gt;&lt;/ol&gt;"What?", you say, "The garbage collector does less work by collecting more garbage?".&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Indeed it does. When we hear "garbage collector" we tend to think of the work involved in clearing out an overfilled store room, all that work to haul all the garbage out. But the garbage collector doesn't even know the garbage exists, the very definition of garbage is that it can no longer be reached from anywhere. What the garbage collector really does is create a whole new store room and move the stuff you want to keep over to it and then it lets the old store room and all the garbage disappear in a puff of smoke. So all the work done by the garbage collector is really done to keep objects alive, i.e. the GC is really the "goodstuff" collector.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;This is obviously a somewhat simplified view and I don't think it holds completely for objects with finalizers (which is probably why finalizers are really bad for performance). Every single measurement and microbenchmark I've done confirms that creating and destroying objects is never worse and often much better than trying to keep objects around. I've done a few, first because I didn't trust it, then because others were so convinced of the opposite that I had to research it. That isn't an absolute proof that it will be true for all scenarios, but I think it's a pretty good indication of where you should be pointing when shooting from the hip.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;From &lt;a href="'http://www.ibm.com/developerworks/java/library/j-jtp09275.html'"&gt;an IBM developer works article&lt;/a&gt;, we get the numbers that allocating an object in Java takes about 10 machine instructions (an order of magnitude better than the best C/C++ allocation) and that throwing an object away costs, you guessed it, absolutely zero. So just remember that GC stands for "Goodstuff Collector" and you'll be on the right track.&lt;/div&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7677021887363364182-1292945835961222977?l=tobega.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://tobega.blogspot.com/feeds/1292945835961222977/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=7677021887363364182&amp;postID=1292945835961222977' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7677021887363364182/posts/default/1292945835961222977'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7677021887363364182/posts/default/1292945835961222977'/><link rel='alternate' type='text/html' href='http://tobega.blogspot.com/2008/11/gc-is-for-goodstuff-collector.html' title='GC is for Goodstuff Collector'/><author><name>tobe</name><uri>http://www.blogger.com/profile/00792674914237130365</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='26' height='32' src='http://bp1.blogger.com/_OD0rKvKkvVw/R8f0-n5OxgI/AAAAAAAAAAM/toWm_WfWjVU/S220/tobe.jpg'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7677021887363364182.post-7887420679447649275</id><published>2008-08-16T11:39:00.000-07:00</published><updated>2008-08-18T15:17:31.039-07:00</updated><title type='text'>The legacy of inheritance</title><content type='html'>Is inheritance really useful or is it a feature that causes more problems than it solves? Certainly I can't think of a case where I've been really grateful that I've been able to inherit from a superclass but I can think of several instances where it has caused friction and where the extension mechanism of inheritance tended to lead the programmer the wrong way.&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Consider the following code (public fields for brevity):&lt;/div&gt;&lt;div&gt;&lt;pre&gt;&lt;br /&gt;public class Square {&lt;br /&gt;  public int base;&lt;br /&gt;  public int getArea() {&lt;br /&gt;  return base * base;&lt;br /&gt; }&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;public class Rectangle extends Square {&lt;br /&gt;  public int height;&lt;br /&gt;  @Override public int getArea() {&lt;br /&gt;    return base * height;&lt;br /&gt;  }&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;public class Parallelogram extends Rectangle {&lt;br /&gt;  public double angle;&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Now how do we implement a Rhombus? Is it a Square extended with an angle (and overridden area calculation) or a Parallelogram with conditions on setting the properties so that the invariant is preserved (which is why we should have accessors, by the way)?&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Well, the correct answer is neither, even though we have a nice sequence of extensions. The problem is that we have been led astray by the extension mechanism and violated the "is a" rule for subclassing and ended up with a corrupt type system. Clearly a Parallelogram is not a Rectangle which equally clearly is not a Square so a subclass instance may not safely be used in place of a superclass instance. Reversing the class hierarchy solves the issue, however it creates subclasses that are restrictions of the superclass rather than extensions.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;An acquaintance of mine who is highly experienced in creating standardized components for information interchange once claimed that it only works to inherit properties by restriction. This is well worth considering, although I'm not entirely convinced because it causes a different set of problems when restriction means "that particular property is not used", as it so often does in information interchange scenarios. In that case it is usually not interesting nor useful to know what the superclass is. In our case at hand it will work because the subclasses actually have a meaningful and useful value of the property but it is restricted by an invariant, so it is also useful to be able to view them as instances of the superclass.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Let's try coding again:&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;pre&gt;public class Parallelogram {&lt;br /&gt;  protected int base;&lt;br /&gt;  protected int height;&lt;br /&gt;  protected double angle;&lt;br /&gt;&lt;br /&gt;  public void setAngle(double angle) {&lt;br /&gt;    this.angle = angle;&lt;br /&gt; }&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;public class Rectangle extends Parallelogram {&lt;br /&gt;  @Override public void setAngle(double angle) {&lt;br /&gt;      &lt;b&gt;// What should we do here?&lt;/b&gt;&lt;br /&gt;  }&lt;br /&gt;}&lt;br /&gt;...&lt;br /&gt;&lt;/pre&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Oops, this doesn't seem to work well, either. Obviously we can't just inherit the setAngle method or we could end up with a corrupt Rectangle, nor is there any reasonable action we can take. We can get out of our pickle, however, because constructors are &lt;span class="Apple-style-span" style="font-weight: bold;"&gt;not&lt;/span&gt; inherited! Simply make our instances immutable:&lt;/div&gt;&lt;div&gt;&lt;pre&gt;public class Parallelogram {&lt;br /&gt;  public final int base;&lt;br /&gt;  public final int height;&lt;br /&gt;  public final int angle;&lt;br /&gt;&lt;br /&gt;  public Parallelogram(int base, int height, double angle) {&lt;br /&gt;    this.base = base;&lt;br /&gt;    this.height = height;&lt;br /&gt;    this.angle = angle;&lt;br /&gt;  }&lt;br /&gt;&lt;br /&gt;  public int getArea() {&lt;br /&gt;    return base * height;&lt;br /&gt;  }&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;public class Rectangle extends Parallelogram {&lt;br /&gt;  public Rectangle(int base, int height) {&lt;br /&gt;    super(base, height, Math.PI/2);&lt;br /&gt;  }&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;public class Square extends Rectangle {&lt;br /&gt;  public Square(int side) {&lt;br /&gt;     super(side, side);&lt;br /&gt;  }&lt;br /&gt;}&lt;/pre&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;That seems to work, and the implementation of getArea() is actually profitably inherited. But we still have a problem in Java with a Rhombus, since a Square is both a Rectangle and a Rhombus but a Rhombus is not a Rectangle. To solve that would require defining the types as interfaces and have separate implementation classes (now I understand why that is often  recommended :-) ).&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;If we had chosen to implement Parallelogram with a field for the length of the side instead of the height, the formula for the area would have been base*Math.sin(angle)*side. Even if this would have worked for our Rectangle, it would have been inefficient (although when the fields are immutable it could probably be optimized by the compiler and/or JVM).&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;On the whole, I believe it is seldom profitable to inherit the implementation of a method, if you have a good example to the contrary, please share it.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;I think that overriding all public methods would be preferable, even if you just decide to call super's version, at least it would show that you gave some thought to whether it was correct or not. Without having done an exhaustive study, I believe this is especially true for interfaces that indicate that a class "is" something rather than that it "is a" something, i.e. those interfaces whose name usually end in "able". Try Cloneable, Externalizable, Runnable and Printable.&lt;/div&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7677021887363364182-7887420679447649275?l=tobega.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://tobega.blogspot.com/feeds/7887420679447649275/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=7677021887363364182&amp;postID=7887420679447649275' title='2 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7677021887363364182/posts/default/7887420679447649275'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7677021887363364182/posts/default/7887420679447649275'/><link rel='alternate' type='text/html' href='http://tobega.blogspot.com/2008/08/legacy-of-inheritance.html' title='The legacy of inheritance'/><author><name>tobe</name><uri>http://www.blogger.com/profile/00792674914237130365</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='26' height='32' src='http://bp1.blogger.com/_OD0rKvKkvVw/R8f0-n5OxgI/AAAAAAAAAAM/toWm_WfWjVU/S220/tobe.jpg'/></author><thr:total>2</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7677021887363364182.post-7604036030207358878</id><published>2008-07-21T15:01:00.000-07:00</published><updated>2008-07-21T16:12:31.554-07:00</updated><title type='text'>Cedric's coding challenge</title><content type='html'>Although I came late to the party at &lt;a href="http://beust.com/weblog/archives/000491.html"&gt;Cedric's coding challenge&lt;/a&gt;, this is the kind of problem I just can't resist taking at least a little dip into. The idea is to generate all numbers up to a maximum that do not have any repeated digits.&lt;br /&gt;&lt;br /&gt;My initial thought was that the pattern of digits for an n-digit number should be the same, you just need to recode the values. I.e. given 3 digits a, b and c from which you should generate all 3-digit sequences without repeated digits, then generating the 2-digit suffixes ac and ca after choosing b as the first digit is the same as choosing a as the first digit, generating bc and cb and then recoding a-&gt;b, b-&gt;a and c-&gt;c.&lt;br /&gt;&lt;br /&gt;Anyway, I soon realized that I couldn't come up with an efficient recoding algorithm and also that generating the suffixes didn't cost much more than an iteration over a pre-generated suffix list. So I basically ended up with the same algorithm as &lt;a href="http://crazybob.org/FastBeustSequence.java.html"&gt;crazybob&lt;/a&gt; and &lt;a href="http://code.google.com/p/blogcode/source/browse/trunk/BeustChallenge0708/src/beust/ModifiedBeustSequence.java?r=8"&gt;Jonathan Hawkes improvement&lt;/a&gt;. Happily, my implementation was a bit faster still than both of theirs, 30% faster than Bob's and 20% faster than Jonathan's in Bob's way of counting and when measured like Jonathn does it, mine is 65% faster than Bob's and 30% faster than Jonathan's. Here it is:&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;&lt;span class="s0"&gt;/** &lt;br /&gt; * Finds base 10 numbers whose digits don't repeat. Solution to Cedric's coding &lt;br /&gt; * challenge: http://beust.com/weblog/archives/000491.html &lt;br /&gt; * &lt;br /&gt; * &lt;/span&gt;&lt;span class="s1"&gt;@author &lt;/span&gt;&lt;span class="s0"&gt;Torbjorn Gannholm &lt;br /&gt; */&lt;/span&gt;&lt;span class="s2"&gt; &lt;br /&gt;&lt;/span&gt;&lt;span class="s3"&gt;public class &lt;/span&gt;&lt;span class="s2"&gt;NonRepeatingDigits { &lt;br /&gt;  &lt;/span&gt;&lt;span class="s3"&gt;private final long &lt;/span&gt;&lt;span class="s2"&gt;max; &lt;br /&gt;  &lt;/span&gt;&lt;span class="s3"&gt;private final int &lt;/span&gt;&lt;span class="s2"&gt;base; &lt;br /&gt;  &lt;/span&gt;&lt;span class="s3"&gt;private final &lt;/span&gt;&lt;span class="s2"&gt;Listener listener; &lt;br /&gt;  &lt;/span&gt;&lt;span class="s3"&gt;private final &lt;/span&gt;&lt;span class="s2"&gt;Digit head; &lt;br /&gt; &lt;br /&gt;  &lt;/span&gt;&lt;span class="s0"&gt;/** &lt;br /&gt;   * Finds all numbers with non-repeating digits in the supplied base up to max. &lt;br /&gt;   * &lt;/span&gt;&lt;span class="s1"&gt;@param &lt;/span&gt;&lt;span class="s0"&gt;base The base, e.g. octal (8), decimal (10), hexadecimal (16). &lt;br /&gt;   * &lt;/span&gt;&lt;span class="s1"&gt;@param &lt;/span&gt;&lt;span class="s0"&gt;max Upper bound for returned values. &lt;br /&gt;   * &lt;/span&gt;&lt;span class="s1"&gt;@param &lt;/span&gt;&lt;span class="s0"&gt;listener Listener to receive valid numbers. &lt;br /&gt;   */&lt;/span&gt;&lt;span class="s2"&gt; &lt;br /&gt;  &lt;/span&gt;&lt;span class="s3"&gt;public &lt;/span&gt;&lt;span class="s2"&gt;NonRepeatingDigits(&lt;/span&gt;&lt;span class="s3"&gt;int &lt;/span&gt;&lt;span class="s2"&gt;base, &lt;/span&gt;&lt;span class="s3"&gt;long &lt;/span&gt;&lt;span class="s2"&gt;max, Listener listener) { &lt;br /&gt;    &lt;/span&gt;&lt;span class="s3"&gt;this&lt;/span&gt;&lt;span class="s2"&gt;.base = base; &lt;br /&gt;    &lt;/span&gt;&lt;span class="s3"&gt;this&lt;/span&gt;&lt;span class="s2"&gt;.max = max; &lt;br /&gt;    &lt;/span&gt;&lt;span class="s3"&gt;this&lt;/span&gt;&lt;span class="s2"&gt;.listener = listener; &lt;br /&gt;    head = &lt;/span&gt;&lt;span class="s3"&gt;new &lt;/span&gt;&lt;span class="s2"&gt;Digit(base); &lt;br /&gt;  } &lt;br /&gt; &lt;br /&gt;  &lt;/span&gt;&lt;span class="s3"&gt;public void &lt;/span&gt;&lt;span class="s2"&gt;run() { &lt;br /&gt;    &lt;/span&gt;&lt;span class="s0"&gt;// One digit numbers.&lt;/span&gt;&lt;span class="s2"&gt; &lt;br /&gt;    &lt;/span&gt;&lt;span class="s3"&gt;for &lt;/span&gt;&lt;span class="s2"&gt;(Digit current = head.next.next; &lt;br /&gt;         current != &lt;/span&gt;&lt;span class="s3"&gt;null&lt;/span&gt;&lt;span class="s2"&gt;; &lt;br /&gt;         current = current.next) { &lt;br /&gt;      &lt;/span&gt;&lt;span class="s3"&gt;int &lt;/span&gt;&lt;span class="s2"&gt;value = current.value; &lt;br /&gt;      &lt;/span&gt;&lt;span class="s3"&gt;if &lt;/span&gt;&lt;span class="s2"&gt;(value &amp;gt; max) &lt;/span&gt;&lt;span class="s3"&gt;return&lt;/span&gt;&lt;span class="s2"&gt;; &lt;br /&gt;      listener.hear(value); &lt;br /&gt;    } &lt;br /&gt;    &lt;/span&gt;&lt;span class="s0"&gt;// Pick first digit (non-zero), then find the rest of the number.&lt;/span&gt;&lt;span class="s2"&gt; &lt;br /&gt;    &lt;/span&gt;&lt;span class="s3"&gt;for &lt;/span&gt;&lt;span class="s2"&gt;(&lt;/span&gt;&lt;span class="s3"&gt;int &lt;/span&gt;&lt;span class="s2"&gt;digitsAfterFirst = &lt;/span&gt;&lt;span class="s4"&gt;1&lt;/span&gt;&lt;span class="s2"&gt;; &lt;br /&gt;         digitsAfterFirst &amp;lt; base; &lt;br /&gt;         digitsAfterFirst++) { &lt;br /&gt;      &lt;/span&gt;&lt;span class="s3"&gt;for &lt;/span&gt;&lt;span class="s2"&gt;(Digit previous = head.next, current = head.next.next; &lt;br /&gt;          current != &lt;/span&gt;&lt;span class="s3"&gt;null&lt;/span&gt;&lt;span class="s2"&gt;; &lt;br /&gt;          &lt;/span&gt;&lt;span class="s0"&gt;// Restore removed digit to sequence.&lt;/span&gt;&lt;span class="s2"&gt; &lt;br /&gt;          previous.next = current, previous = current, current = current.next) { &lt;br /&gt;        &lt;/span&gt;&lt;span class="s0"&gt;// Remove chosen digit from sequence.&lt;/span&gt;&lt;span class="s2"&gt; &lt;br /&gt;        previous.next = current.next; &lt;br /&gt;        &lt;/span&gt;&lt;span class="s3"&gt;if &lt;/span&gt;&lt;span class="s2"&gt;(followingDigits(digitsAfterFirst, current.value * base)) &lt;/span&gt;&lt;span class="s3"&gt;return&lt;/span&gt;&lt;span class="s2"&gt;; &lt;br /&gt;      } &lt;br /&gt;    } &lt;br /&gt;  } &lt;br /&gt; &lt;br /&gt;  &lt;/span&gt;&lt;span class="s0"&gt;/** A digit, part of a linked list of all digits in a base. &lt;br /&gt;   * (Shamelessly paraphrased from crazybob) */&lt;/span&gt;&lt;span class="s2"&gt; &lt;br /&gt;  &lt;/span&gt;&lt;span class="s3"&gt;private static class &lt;/span&gt;&lt;span class="s2"&gt;Digit { &lt;br /&gt;    &lt;/span&gt;&lt;span class="s3"&gt;private &lt;/span&gt;&lt;span class="s2"&gt;Digit next; &lt;br /&gt;    &lt;/span&gt;&lt;span class="s3"&gt;private final int &lt;/span&gt;&lt;span class="s2"&gt;value; &lt;br /&gt; &lt;br /&gt;    &lt;/span&gt;&lt;span class="s0"&gt;/** Constructs a non-digit that acts as the head for the list, and the &lt;br /&gt;     * digits in the list. */&lt;/span&gt;&lt;span class="s2"&gt; &lt;br /&gt;    Digit(&lt;/span&gt;&lt;span class="s3"&gt;int &lt;/span&gt;&lt;span class="s2"&gt;base) { &lt;br /&gt;      value = -&lt;/span&gt;&lt;span class="s4"&gt;1&lt;/span&gt;&lt;span class="s2"&gt;; &lt;br /&gt;      next = &lt;/span&gt;&lt;span class="s3"&gt;new &lt;/span&gt;&lt;span class="s2"&gt;Digit(base, &lt;/span&gt;&lt;span class="s4"&gt;0&lt;/span&gt;&lt;span class="s2"&gt;); &lt;br /&gt;    } &lt;br /&gt;     &lt;br /&gt;    &lt;/span&gt;&lt;span class="s0"&gt;/** Constructs the real sequence of digits */&lt;/span&gt;&lt;span class="s2"&gt; &lt;br /&gt;    &lt;/span&gt;&lt;span class="s3"&gt;private &lt;/span&gt;&lt;span class="s2"&gt;Digit(&lt;/span&gt;&lt;span class="s3"&gt;int &lt;/span&gt;&lt;span class="s2"&gt;base, &lt;/span&gt;&lt;span class="s3"&gt;int &lt;/span&gt;&lt;span class="s2"&gt;value) { &lt;br /&gt;      &lt;/span&gt;&lt;span class="s3"&gt;this&lt;/span&gt;&lt;span class="s2"&gt;.value = value; &lt;br /&gt;      &lt;/span&gt;&lt;span class="s3"&gt;if &lt;/span&gt;&lt;span class="s2"&gt;(++value &amp;lt; base) { &lt;br /&gt;        next = &lt;/span&gt;&lt;span class="s3"&gt;new &lt;/span&gt;&lt;span class="s2"&gt;Digit(base, value); &lt;br /&gt;      } &lt;br /&gt;    } &lt;br /&gt;  } &lt;br /&gt; &lt;br /&gt;  &lt;/span&gt;&lt;span class="s0"&gt;/** &lt;br /&gt;   * Recursively generates digits after the first of a valid number. &lt;br /&gt;   * &lt;/span&gt;&lt;span class="s1"&gt;@param &lt;/span&gt;&lt;span class="s0"&gt;remaining Number of digits left to generate. &lt;br /&gt;   * &lt;/span&gt;&lt;span class="s1"&gt;@param &lt;/span&gt;&lt;span class="s0"&gt;prefixValue Value of previous digits. &lt;br /&gt;   * &lt;/span&gt;&lt;span class="s1"&gt;@return &lt;/span&gt;&lt;span class="s0"&gt;true when values generated are greater than max. &lt;br /&gt;   */&lt;/span&gt;&lt;span class="s2"&gt; &lt;br /&gt;  &lt;/span&gt;&lt;span class="s3"&gt;private boolean &lt;/span&gt;&lt;span class="s2"&gt;followingDigits(&lt;/span&gt;&lt;span class="s3"&gt;int &lt;/span&gt;&lt;span class="s2"&gt;remaining, &lt;/span&gt;&lt;span class="s3"&gt;int &lt;/span&gt;&lt;span class="s2"&gt;prefixValue) { &lt;br /&gt;    &lt;/span&gt;&lt;span class="s3"&gt;if &lt;/span&gt;&lt;span class="s2"&gt;(remaining &amp;gt; &lt;/span&gt;&lt;span class="s4"&gt;1&lt;/span&gt;&lt;span class="s2"&gt;) { &lt;br /&gt;      &lt;/span&gt;&lt;span class="s3"&gt;for &lt;/span&gt;&lt;span class="s2"&gt;(Digit prev = head , current = head.next; &lt;br /&gt;           current != &lt;/span&gt;&lt;span class="s3"&gt;null&lt;/span&gt;&lt;span class="s2"&gt;; &lt;br /&gt;           &lt;/span&gt;&lt;span class="s0"&gt;// Restore removed digit to sequence.&lt;/span&gt;&lt;span class="s2"&gt; &lt;br /&gt;           prev.next = current, prev = current, current = current.next) { &lt;br /&gt;        &lt;/span&gt;&lt;span class="s0"&gt;// Remove chosen digit from allowable digits.&lt;/span&gt;&lt;span class="s2"&gt; &lt;br /&gt;        prev.next = current.next; &lt;br /&gt;        &lt;/span&gt;&lt;span class="s3"&gt;if&lt;/span&gt;&lt;span class="s2"&gt;(followingDigits(remaining - &lt;/span&gt;&lt;span class="s4"&gt;1&lt;/span&gt;&lt;span class="s2"&gt;, &lt;br /&gt;                           (prefixValue + current.value) * base)) &lt;/span&gt;&lt;span class="s3"&gt;return true&lt;/span&gt;&lt;span class="s2"&gt;; &lt;br /&gt;      } &lt;br /&gt;    } &lt;/span&gt;&lt;span class="s3"&gt;else &lt;/span&gt;&lt;span class="s2"&gt;{ &lt;br /&gt;      &lt;/span&gt;&lt;span class="s3"&gt;for &lt;/span&gt;&lt;span class="s2"&gt;(Digit current = head.next; current != &lt;/span&gt;&lt;span class="s3"&gt;null&lt;/span&gt;&lt;span class="s2"&gt;; current = current.next) { &lt;br /&gt;        &lt;/span&gt;&lt;span class="s3"&gt;int &lt;/span&gt;&lt;span class="s2"&gt;value = prefixValue + current.value; &lt;br /&gt;        &lt;/span&gt;&lt;span class="s3"&gt;if &lt;/span&gt;&lt;span class="s2"&gt;(value &amp;gt; max) &lt;/span&gt;&lt;span class="s3"&gt;return true&lt;/span&gt;&lt;span class="s2"&gt;; &lt;br /&gt;        listener.hear(value); &lt;br /&gt;      } &lt;br /&gt;    } &lt;br /&gt;    &lt;/span&gt;&lt;span class="s3"&gt;return false&lt;/span&gt;&lt;span class="s2"&gt;; &lt;br /&gt;  } &lt;br /&gt;} &lt;br /&gt;&lt;/span&gt;&lt;/pre&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7677021887363364182-7604036030207358878?l=tobega.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://tobega.blogspot.com/feeds/7604036030207358878/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=7677021887363364182&amp;postID=7604036030207358878' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7677021887363364182/posts/default/7604036030207358878'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7677021887363364182/posts/default/7604036030207358878'/><link rel='alternate' type='text/html' href='http://tobega.blogspot.com/2008/07/cedrics-coding-challenge.html' title='Cedric&apos;s coding challenge'/><author><name>tobe</name><uri>http://www.blogger.com/profile/00792674914237130365</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='26' height='32' src='http://bp1.blogger.com/_OD0rKvKkvVw/R8f0-n5OxgI/AAAAAAAAAAM/toWm_WfWjVU/S220/tobe.jpg'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7677021887363364182.post-5541013038785929535</id><published>2008-05-04T04:37:00.000-07:00</published><updated>2008-05-04T05:16:47.115-07:00</updated><title type='text'>Beautiful enums</title><content type='html'>Whatever complaints you may have against java, I think you have to grant that at least enums are a thing of beauty. Consider this code line:&lt;pre&gt;&lt;br /&gt;Collections.sort(myChildren, Child.Order.ByAge.descending());&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;The best part is that this started to appear as a side effect of another rational structuring of code, creating a synergy effect of two positive drives together. This kind of synergy always appeals to my aesthetic sense. Here's the Child class:&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;public final class Child {&lt;br /&gt;  private final Integer age;&lt;br /&gt;  private final String name;&lt;br /&gt;...&lt;br /&gt;  public static enum Order implements Comparator&lt;Child&gt; {&lt;br /&gt;     ByAge() {&lt;br /&gt;        public int compare(Child lhs, Child rhs) {&lt;br /&gt;           return lhs.age.compareTo(rhs.age);&lt;br /&gt;        }&lt;br /&gt;     },&lt;br /&gt;     ByName() {&lt;br /&gt;        public int compare(Child lhs, Child rhs) {&lt;br /&gt;           // TODO: Should really use a collator.&lt;br /&gt;           return lhs.name.compareTo(rhs.name);&lt;br /&gt;        }&lt;br /&gt;     };&lt;br /&gt;&lt;br /&gt;     public abstract int compare(Child lhs, Child rhs);&lt;br /&gt;&lt;br /&gt;     public Comparator&lt;Child&gt; ascending() {&lt;br /&gt;        return this;&lt;br /&gt;     }&lt;br /&gt;&lt;br /&gt;     public Comparator&lt;Child&gt; descending() {&lt;br /&gt;        return Collections.reverseOrder(this);&lt;br /&gt;     }&lt;br /&gt;  }&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;Lovely! Other examples of the synergy effect I've seen recently are my earlier posted thread safe state pattern and &lt;a href='http://weblogs.java.net/blog/giovanisalvador/archive/2008/04/refactoring_for.html'&gt;this blog entry&lt;/a&gt;. In both those cases the synergy was better code structure and better performance.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7677021887363364182-5541013038785929535?l=tobega.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://tobega.blogspot.com/feeds/5541013038785929535/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=7677021887363364182&amp;postID=5541013038785929535' title='6 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7677021887363364182/posts/default/5541013038785929535'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7677021887363364182/posts/default/5541013038785929535'/><link rel='alternate' type='text/html' href='http://tobega.blogspot.com/2008/05/beautiful-enums.html' title='Beautiful enums'/><author><name>tobe</name><uri>http://www.blogger.com/profile/00792674914237130365</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='26' height='32' src='http://bp1.blogger.com/_OD0rKvKkvVw/R8f0-n5OxgI/AAAAAAAAAAM/toWm_WfWjVU/S220/tobe.jpg'/></author><thr:total>6</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7677021887363364182.post-2959686430708832309</id><published>2008-03-31T13:13:00.000-07:00</published><updated>2008-03-31T15:28:23.137-07:00</updated><title type='text'>Java Thread-safe State Design Pattern</title><content type='html'>&lt;h2&gt;Thread-safe State&lt;/h2&gt;&lt;br /&gt;Apart from the things mentioned here, this pattern also conveys the intent and benefits of the GoF State pattern, being an extension thereof. The term "behaviour" is interpreted more strictly so that an object is always considered to change its behaviour when its state changes.&lt;br /&gt;&lt;h3&gt;Intent&lt;/h3&gt;&lt;br /&gt;Make sure that an object is observable only in a valid consistent state and that transitions between valid consistent states are atomic and side-effects occur if and only if the associated transition occurs validly.&lt;br /&gt;&lt;h3&gt;Motivation&lt;/h3&gt;&lt;br /&gt;Consider a class where behaviour depends on more than one field and/or side-effects occur as a result of certain state-changes. Such behaviour can be very difficult to analyze for thread-safety and the safe classic approach is to synchronize all methods. Such behaviour can also be difficult to analyze for logical correctness, bringing the motivation for the state pattern into play.&lt;br /&gt;&lt;br /&gt;The key idea is to leverage the state pattern and store the current state in an AtomicReference. Current state should be represented by an immutable object. State transitions are performed by a compareAndSet (CAS) operation and a retry on failure. For transitions with side-effects, the CAS is performed to a boilerplate blocking state, the side effects performed, the resultant state set and the blocking state released, whereby each thread released from the blocking state retries the attempted operation on the resulting state. The CAS always compares with the "this" reference of the state instance being transitioned from and can only succeed for one thread, all other threads attempting a simultaneous transition have to retry on the new state.&lt;br /&gt;&lt;h3&gt;Applicability&lt;/h3&gt;&lt;br /&gt;Any object that has a method that has a more complex interaction with the object state than one of either a simple get or a simple set (in which case just marking the field volatile is  simpler and more performant).&lt;br /&gt;&lt;h3&gt;Structure (given as implementation examples)&lt;/h3&gt;&lt;br /&gt;Delegate all calls to an immutable state instance:&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;class Implementation implements Interface {&lt;br /&gt;  private final AtomicReference&lt;Interface&gt; state;&lt;br /&gt;&lt;br /&gt;  public ... doSomething(...) {&lt;br /&gt;      return state.get().doSomething(...);&lt;br /&gt;  }&lt;br /&gt;&lt;br /&gt;  private class StateA implements Interface {&lt;br /&gt;    private final ... valueX;&lt;br /&gt;    private final ... valueY;&lt;br /&gt;&lt;br /&gt;    public ... doSomething(...) {&lt;br /&gt;       .... valueX ... valueY ...&lt;br /&gt;    }&lt;br /&gt;  }&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;Simple state changes performed by CAS or retry:&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;class Implementation implements Interface {&lt;br /&gt;  private final AtomicReference&lt;Interface&gt; state;&lt;br /&gt;&lt;br /&gt;  public void setX(y) {&lt;br /&gt;      state.get().setX(y);&lt;br /&gt;  }&lt;br /&gt;&lt;br /&gt;  private class StateA implements Interface {&lt;br /&gt;    private final ... x;&lt;br /&gt;&lt;br /&gt;    public void setX(y) {&lt;br /&gt;       if (!state.compareAndSet(this, new StateA(y))) {&lt;br /&gt;         state.get().setX(y);&lt;br /&gt;       }&lt;br /&gt;    }&lt;br /&gt;  }&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;State changes with side-effects CAS to a blocking state first:&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;class Implementation implements Interface {&lt;br /&gt;  private final AtomicReference&lt;Interface&gt; state;&lt;br /&gt;&lt;br /&gt;  public void printAndSetX(y) {&lt;br /&gt;      state.get().printAndSetX(y);&lt;br /&gt;  }&lt;br /&gt;&lt;br /&gt;  private class StateA implements Interface {&lt;br /&gt;    private final ... x;&lt;br /&gt;&lt;br /&gt;    public void printAndSetX(y) {&lt;br /&gt;       BlockingState guard = new BlockingState();&lt;br /&gt;       if (state.compareAndSet(this, guard)) {&lt;br /&gt;         try {&lt;br /&gt;           print(x);&lt;br /&gt;           state.set(new StateA(y));&lt;br /&gt;         } finally {&lt;br /&gt;           guard.release();&lt;br /&gt;         }&lt;br /&gt;       }&lt;br /&gt;    }&lt;br /&gt;  }&lt;br /&gt;&lt;br /&gt;  private class BlockingState implements Interface {&lt;br /&gt;    private final CountDownLatch latch = new CountDownLatch(1);&lt;br /&gt;&lt;br /&gt;    public void printAndSetX(y) {&lt;br /&gt;      try {&lt;br /&gt;        latch.await();&lt;br /&gt;      } catch (InterruptedException e) {&lt;br /&gt;        // Don't care.&lt;br /&gt;      }&lt;br /&gt;      state.get().printAndSetX(y);&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    private void release() {&lt;br /&gt;      latch.countDown();&lt;br /&gt;    }&lt;br /&gt;  }&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;h3&gt;Participants&lt;/h3&gt;&lt;br /&gt;&lt;ul&gt;&lt;br /&gt;&lt;li&gt;Interface - defines the public interface.&lt;/li&gt;&lt;br /&gt;&lt;li&gt;Implementation - maintains an AtomicReference to current StateImplementation, implements the public interface.&lt;/li&gt;&lt;br /&gt;&lt;li&gt;StateImplementation - the implementation of the public interface for a particular state.&lt;/li&gt;&lt;br /&gt;&lt;li&gt;BlockingState - specialized boilerplate StateImplementation that blocks all calls until released and then delegates to the current state.&lt;/li&gt;&lt;br /&gt;&lt;/ul&gt;&lt;br /&gt;&lt;h3&gt;Collaborations&lt;/h3&gt;&lt;br /&gt;&lt;ul&gt;&lt;br /&gt;&lt;li&gt;Implementation delegates relevant (usually all) calls to the current StateImplementation.&lt;/li&gt;&lt;br /&gt;&lt;li&gt;StateImplementation performs state transitions by a state.compareAndSet(this, nextState) or retry the transition on the current state (which is different from "this" since CAS failed) so that each state object can only be transitioned from once.&lt;/li&gt;&lt;br /&gt;&lt;li&gt;BlockingState blocks all calls until released, thereupon retries on new current StateImplementation.&lt;/li&gt;&lt;br /&gt;&lt;/ul&gt;&lt;br /&gt;&lt;h3&gt;Consequences&lt;/h3&gt;&lt;br /&gt;&lt;ol&gt;&lt;br /&gt;&lt;li&gt;Interactions with the object always occur with a consistent state of the object, the immutability of the state delegate guaranteeing a consistent result of the interaction and each separate interaction is therefore in effect atomic.&lt;/li&gt;&lt;br /&gt;&lt;li&gt;State transitions are explicit and atomic.&lt;/li&gt;&lt;br /&gt;&lt;li&gt;Performance seems to be as good as or better than a straightforward non-thread-safe implementatin with mutable fields. Performance is better than that of synchronization (compare "optimistic locking" versus "read/write locking") for applicable objects if some interactions do not entail state changes, especially when the object is reachable from more than one thread (even if access is never contended).&lt;/li&gt;&lt;br /&gt;&lt;/ol&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7677021887363364182-2959686430708832309?l=tobega.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://tobega.blogspot.com/feeds/2959686430708832309/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=7677021887363364182&amp;postID=2959686430708832309' title='12 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7677021887363364182/posts/default/2959686430708832309'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7677021887363364182/posts/default/2959686430708832309'/><link rel='alternate' type='text/html' href='http://tobega.blogspot.com/2008/03/java-thread-safe-state-design-pattern.html' title='Java Thread-safe State Design Pattern'/><author><name>tobe</name><uri>http://www.blogger.com/profile/00792674914237130365</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='26' height='32' src='http://bp1.blogger.com/_OD0rKvKkvVw/R8f0-n5OxgI/AAAAAAAAAAM/toWm_WfWjVU/S220/tobe.jpg'/></author><thr:total>12</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7677021887363364182.post-5530419684739124750</id><published>2008-03-23T23:23:00.000-07:00</published><updated>2008-03-28T16:12:46.445-07:00</updated><title type='text'>Performance and thread-safe state handling</title><content type='html'>In my &lt;a href='http://tobega.blogspot.com/2008/03/thread-safe-state-handling.html'&gt;previous post&lt;/a&gt; I introduced using the state pattern and an AtomicReference to help maintain thread safety. My reason for starting to play with the pattern was really to make it easier to analyze the code and prove correctness, but obviously the question of performance inevitably comes up and it is interesting to know the trade-offs.&lt;br /&gt;&lt;br /&gt;I set up a benchmark where ten threads would simultaneously try to execute the same code and each thread would just hammer away for an obscenely large number of times. First up for the test was the simple lamp:&lt;pre&gt;&lt;br /&gt;public interface Lamp {&lt;br /&gt;  boolean isOn();&lt;br /&gt;  void setOn(boolean on);&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;The code to execute was:&lt;pre&gt;&lt;br /&gt;              b = lamp.isOn();&lt;br /&gt;              lamp.setOn(!b);&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;I had an implementation with just a volatile field, an implementation with both methods synchronized, a hybrid implementation where the field was volatile and only the setter synchronized and an implementation using the state pattern. I also ran the bad non-thread-safe implementation. The results with the average time for one run through the code: volatile (669 ns), bad (697 ns), state (985 ns), hybrid (1570 ns), synchronized (2535 ns). Interestingly enough, the state pattern kicks butt. Actually the state pattern was even faster than volatile in the first tests I ran, but that is probably because I ran too few iterations to pay the full cost of garbage collection.&lt;br /&gt;&lt;br /&gt;So how about a predicted worst case, the CoffeeMachine where the state changes on every method call?&lt;pre&gt;&lt;br /&gt;public interface CoffeeMachine {&lt;br /&gt;  void fillBeans(int beans);&lt;br /&gt;  void fillWater(int water);&lt;br /&gt;  Coffee makeCoffee(int water, int beans) throws OutOfWaterException, OutOfBeansException;&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;And the test code, same rules as above, ten threads whacking away:&lt;pre&gt;&lt;br /&gt;          Random r = new Random();&lt;br /&gt;....&lt;br /&gt;              int w = r.nextInt(5);&lt;br /&gt;              cm.fillWater(w);&lt;br /&gt;              int b = r.nextInt(3);&lt;br /&gt;              cm.fillBeans(b);&lt;br /&gt;              try {&lt;br /&gt;                cm.makeCoffee(w,b);&lt;br /&gt;              } catch (OutOfWaterException e) {&lt;br /&gt;                oow.getAndIncrement();&lt;br /&gt;              } catch (OutOfBeansException e) {&lt;br /&gt;                oob.getAndIncrement();&lt;br /&gt;              }&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;This was a straight shoot-out between a synchronized implementation and a state pattern implementation. Result: synchronized (5021 ns), state (5333 ns). A slight victory for synchronization, yeah!&lt;br /&gt;&lt;br /&gt;So how about adding some getters into the CoffeeMachine, how does that change things? The test code was changed to:&lt;pre&gt;&lt;br /&gt;     Random r = new Random();&lt;br /&gt;....&lt;br /&gt;         int w = r.nextInt(5);&lt;br /&gt;         if(cm.checkWater() &lt; w*10) cm.fillWater(w*100);&lt;br /&gt;         int b = r.nextInt(3);&lt;br /&gt;         if (cm.checkBeans() &lt; b*10) cm.fillBeans(b*100);&lt;br /&gt;         try {&lt;br /&gt;           cm.makeCoffee(w,b);&lt;br /&gt;         } catch (OutOfWaterException e) {&lt;br /&gt;           ons.getAndIncrement();&lt;br /&gt;         } catch (OutOfBeansException e) {&lt;br /&gt;           offs.getAndIncrement();&lt;br /&gt;         }&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;With the getters present it makes sense to try a hybrid approach again. Result: state (2547 ns), hybrid (3675 ns), synchronized (4930 ns).&lt;br /&gt;&lt;br /&gt;&lt;b&gt;Conclusion:&lt;/b&gt; not only does the state pattern with an AtomicReference to an immutable internal state representation make it easier to manage code complexity, it is also beneficial from a performance point of view, being just slightly slower than synchronization in the worst case and twice as fast in normal cases.&lt;br /&gt;&lt;br /&gt;&lt;b&gt;Addendum:&lt;/b&gt; My keen colleague, the informed sceptic, pointed out to me that perhaps some more testing is needed before it can be generally said that the state pattern is better performing. He claimed that normal usage is that threads do something else and then hit the shared resource, which results in the locks being mostly uncontended. I suppose he has a point. But how to test it?&lt;br /&gt;&lt;br /&gt;First attempt, just run my Lamp benchmark single-threaded: volatile (10 ns), synchronized (10 ns), bad (19 ns),  hybrid (22 ns), state (42 ns). Oops! State pattern is 4 times slower than synchronized. Interesting also that plain old non-thread-safe code is slower than volatile and synchronized. The hybrid approach is twice as slow as synchronized. But what is going on here? We've run a long warm-up and then we're just whacking away at our Lamp from a single thread. Obviously HotSpot is able to do some nice things with the synchronized methods in this case (good to know).&lt;br /&gt;&lt;br /&gt;Next attempt, run a minimal warmup and a short time: volatile (10 ns), bad (18 ns), state (44 ns), hybrid (63 ns), synchronized (87 ns). So now we're not hitting it hard enough for HotSpot to do all its magic synchronized is dog slow again.&lt;br /&gt;&lt;br /&gt;Third attempt, hit the class hard from just two threads: bad (120 ns), volatile (121 ns), state (187 ns), hybrid (338 ns), synchronized (752 ns). But we're still hitting it hard. We need to figure out how to simulate the non-contention scenario with many threads.&lt;br /&gt;&lt;br /&gt;Fourth attempt, put in a sleep in each loop. No good, there's too much noise coming in from the calls to sleep(). For what its worth, the numbers are very similar, differences are less than 1% (duh!). We need another angle of attack.&lt;br /&gt;&lt;br /&gt;Just for a change of pace I decided to run the CoffeeMachine benchmark in one thread: state (114 ns), hybrid (160 ns) and synchronized (212 ns). Hmm, I realize I didn't really run single-threaded because there were two threads that had access to the CoffeeMachine object. One thread was just waiting for the other to finish, though, so all locks were uncontended. Trying that with Lamp I get: volatile (13 ns), bad (20 ns), state (42 ns), hybrid (65 ns) and synchronized (89 ns). It seems that uncontended locks are just as expensive as contended locks and HotSpot was able to do some powerful magic when the object was only accessible from one thread. Sanity check on CoffeeMachine running truly single-threaded: state (110 ns), hybrid (113 ns), synchronized (208 ns). Surprise! HotSpot couldn't do so much this time! I just have to check the performance against a standard non-thread-safe implementation: standard (123 ns) versus state (110 ns)!!!!&lt;br /&gt;&lt;br /&gt;&lt;b&gt;Conclusion 2:&lt;/b&gt; The thread-safe state pattern is excellent to use as a standard pattern. As my eager colleague points out so often, the important thing is to be able to analyze the correctness of the code and performance is usually not so important. Well, the state pattern was originally evolved to make it easier to handle varying behaviour depending on state and transitions between these behavioural states, so that requirement is solidly fulfilled. For anything but the simplest of classes, the thread-safe state pattern also seems to be most performant way of achieving thread safety and actually performs better than an ordinary non-thread-safe implementation in at least the one case tested here.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7677021887363364182-5530419684739124750?l=tobega.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://tobega.blogspot.com/feeds/5530419684739124750/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=7677021887363364182&amp;postID=5530419684739124750' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7677021887363364182/posts/default/5530419684739124750'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7677021887363364182/posts/default/5530419684739124750'/><link rel='alternate' type='text/html' href='http://tobega.blogspot.com/2008/03/performance-and-thread-safe-state.html' title='Performance and thread-safe state handling'/><author><name>tobe</name><uri>http://www.blogger.com/profile/00792674914237130365</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='26' height='32' src='http://bp1.blogger.com/_OD0rKvKkvVw/R8f0-n5OxgI/AAAAAAAAAAM/toWm_WfWjVU/S220/tobe.jpg'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7677021887363364182.post-8275462779414806060</id><published>2008-03-17T03:06:00.000-07:00</published><updated>2008-03-19T07:19:56.072-07:00</updated><title type='text'>Thread-safe state handling</title><content type='html'>In my &lt;a href="http://tobega.blogspot.com/2008/03/is-synchronisation-expensive-is-that.html"&gt;previous post&lt;/a&gt; I noted that handling mutable state in multi-threaded programs is a problem that should preferably be avoided. Sometimes it may be too complicated to avoid mutate state and I will in this post look into some ways of handling it, including how the classic State design pattern can help, with a little twist. A good, if old, introduction to threading issues in Java &lt;a href="http://www.javaworld.com/jw-08-1998/jw-08-techniques.html"&gt;can be found here&lt;/a&gt;.&lt;br /&gt;&lt;br /&gt;Consider the following code:&lt;pre&gt;&lt;br /&gt;public class Lamp {&lt;br /&gt;  private boolean on;&lt;br /&gt;  public boolean isOn() {return on;}&lt;br /&gt;  public void setOn(boolean on) {this.on = on;}&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;No threading problems, right?&lt;br /&gt;&lt;br /&gt;Wrong! I had read about it but learnt it again the hard way when one of my unit tests started failing spuriously. I could tell from other measuring points that there was no way that assert could fail, yet it did, sometimes. The issue is that, especially on a multi-core machine, there is no guarantee that other threads will ever get to see changes. To guarantee that, either the same synchronization monitor must be used for both reads and writes, or the variable needs to be volatile.&lt;br /&gt;&lt;br /&gt;With that lesson in mind, let's look at another example:&lt;pre&gt;&lt;br /&gt;public class WaterDispenser {&lt;br /&gt;  private volatile int water;&lt;br /&gt;  public void fill(int amount) { water += amount; }&lt;br /&gt;  public void get(int amount) throws InsufficientWaterException {&lt;br /&gt;    if (water &amp;gt;= amount) water -= amount;&lt;br /&gt;    else throw new InsufficientWaterException();&lt;br /&gt;  }&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;Unfortunately, += and -= are not atomic operations so two threads filling up at the same time may result in only the one fill being effective. Also there is a gap between the check and the decrement so the class may end up in an invalid state if two threads get water at the same time.&lt;br /&gt;&lt;br /&gt;It is always an option just to synchronize the methods and it may well be the best option in this case. It is when you have frequently used methods that just query the state that you want to avoid synchronization because it will give an overhead on every query.&lt;br /&gt;&lt;br /&gt;Just for illustration, let's use an AtomicInteger here, which has the same memory consistency guarantees as volatile and a bit of extra functionality. The addition in fill is now atomic, but in the get we also check that we have enough water so it's not good enough to just do an atomic subtraction after the check since that precondition may not be valid when we get to the subtraction, we have to atomically check that the value didn't change with a compareAndSet or redo.&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;public class WaterDispenser {&lt;br /&gt;private AtomicInteger water;&lt;br /&gt;public void fill(int amount) { water.addAndGet(amount); }&lt;br /&gt;public void get(int amount) throws InsufficientWaterException {&lt;br /&gt;  int currentWater;&lt;br /&gt;  int nextWater;&lt;br /&gt;  do {&lt;br /&gt;    currentWater = water.get();&lt;br /&gt;    nextWater = currentWater - amount;&lt;br /&gt;    if (nextWater &amp;lt; 0) throw new InsufficientWaterException();&lt;br /&gt;  } while (!water.compareAndSet(currentWater, nextWater));&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;It becomes more and more complex to analyze and avoid race conditions the more you need to do, consider for example extending the WaterDispenser to become a CoffeeMachine, when you have to use coffee beans as well as water.&lt;br /&gt;&lt;br /&gt;The &lt;a href="http://userpages.umbc.edu/%7Etarr/dp/lectures/StateStrategy.pdf"&gt;State pattern&lt;/a&gt; is used to make it easier to analyze and express state-dependent behaviour. Not surprisingly, I suppose, it can also be used to simplify concurrent state-handling, although perhaps with a stricter interpretation of "state-dependent behaviour".&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;public class CoffeeMachine {&lt;br /&gt;  private AtomicReference&amp;lt;CoffeeMachineState&amp;gt; state = new AtomicReference&amp;lt;CoffeeMachineState&amp;gt;(new CoffeeMachineState(0,0));&lt;br /&gt;&lt;br /&gt;  public void fillBeans(int beans) {&lt;br /&gt;    state.get().fillBeans(beans);&lt;br /&gt;  }&lt;br /&gt;  public void fillWater(int water) {&lt;br /&gt;    state.get().fillWater(water);&lt;br /&gt;  }&lt;br /&gt;  public Coffee makeCoffee(int water, int beans) throws OutOfWaterException, OutOfBeansException {&lt;br /&gt;    return state.get().makeCoffee();&lt;br /&gt;  }&lt;br /&gt;&lt;br /&gt;  private class CoffeeMachineState {&lt;br /&gt;    private final int water;&lt;br /&gt;    private final int beans;&lt;br /&gt;    CoffeeMachineState(w, b) {&lt;br /&gt;      water = w;&lt;br /&gt;      beans = b;&lt;br /&gt;    }&lt;br /&gt;    void fillBeans(int moreBeans) {&lt;br /&gt;      if (!state.compareAndSet(this, new CoffeeMachineState(water, beans+moreBeans)) {&lt;br /&gt;        state.get().fillBeans(moreBeans);&lt;br /&gt;      }&lt;br /&gt;    }&lt;br /&gt;    void fillWater(int moreWater) {&lt;br /&gt;      if (!state.compareAndSet(this, new CoffeeMachineState(water+moreWater, beans)) {&lt;br /&gt;        state.get().fillWater(moreWater);&lt;br /&gt;      }&lt;br /&gt;    }&lt;br /&gt;    Coffee makeCoffee(int w, int b) throws OutOfWaterException, OutOfBeansException {&lt;br /&gt;      if (water &amp;lt; w) throw new OutOfWaterException();&lt;br /&gt;      if (beans &amp;lt; b) throw new OutOfBeansException();&lt;br /&gt;      if (!state.compareAndSet(this, new CoffeeMachineState(water+moreWater, beans)) {&lt;br /&gt;        return state.get().makeCoffee(w,b);&lt;br /&gt;      }&lt;br /&gt;      return new Coffee(w,b);&lt;br /&gt;    }&lt;br /&gt;  }&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;Again it would probably be better to just sychronize the methods in this case, but it serves to illustrate the pattern: delegate calls to the current state, which either manages to change the state or delegates to the new state if another thread got in first.&lt;br /&gt;&lt;br /&gt;Back to the lamp example, which is a classic for the state pattern, but we'll add some functionality. The lamp is placed in a room and when we turn it on we should illuminate the room and when we turn it off we should darken the room. Now we have a gap between the state change and the room operation, a gap where another thread can come in and wreak havoc. The solution is to introduce a transitional state that holds other threads at bay while you complete the transition.&lt;pre&gt;&lt;br /&gt;class Lamp {&lt;br /&gt; private AtomicReference&amp;lt;Lamp&amp;gt; state = new AtomicReference&amp;lt;Lamp&amp;gt;(new Off());&lt;br /&gt; private final Room room;&lt;br /&gt; public Lamp(Room room) {this.room = room;}&lt;br /&gt; public boolean isOn() {return state.get().isOn();}&lt;br /&gt; public void setOn(boolean on) {state.get().setOn(on);}&lt;br /&gt;&lt;br /&gt; private class On extends Lamp {&lt;br /&gt;   public boolean isOn() {return true;}&lt;br /&gt;   public void setOn(boolean on) {&lt;br /&gt;     if (on) return;&lt;br /&gt;     synchronized (Lamp.this) {&lt;br /&gt;       TransitionGuard guard = new TransitionGuard();&lt;br /&gt;       if (state.compareAndSet(this, guard) {&lt;br /&gt;         room.darken();&lt;br /&gt;         state.set(new Off());&lt;br /&gt;       } else {&lt;br /&gt;         state.get().setOn(on);&lt;br /&gt;       }&lt;br /&gt;     }&lt;br /&gt;   }&lt;br /&gt; }&lt;br /&gt;&lt;br /&gt; private class Off extends Lamp {&lt;br /&gt;   public boolean isOn() {return false;}&lt;br /&gt;   public void setOn(boolean on) {&lt;br /&gt;     if (!on) return;&lt;br /&gt;     synchronized (Lamp.this) {&lt;br /&gt;       TransitionGuard guard = new TransitionGuard();&lt;br /&gt;       if (state.compareAndSet(this, guard) {&lt;br /&gt;         room.illuminate();&lt;br /&gt;         state.set(new On());&lt;br /&gt;       } else {&lt;br /&gt;         state.get().setOn(on);&lt;br /&gt;       }&lt;br /&gt;     }&lt;br /&gt;   }&lt;br /&gt; }&lt;br /&gt;&lt;br /&gt;  private class TransitionGuard extends Lamp {&lt;br /&gt;    public boolean isOn() {&lt;br /&gt;      synchronized (Lamp.this) {&lt;br /&gt;        return state.get().isOn();&lt;br /&gt;      }&lt;br /&gt;    }&lt;br /&gt;    public void setOn(boolean on) {&lt;br /&gt;      synchronized (Lamp.this) {&lt;br /&gt;        state.get().setOn(on);&lt;br /&gt;      }&lt;br /&gt;    }&lt;br /&gt;  }    &lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;Synchronizing would be easier, but with this pattern we only pay the synchronization cost during complex state transitions, although we do get a certain cost for object creations, but this is generally very low.&lt;br /&gt;&lt;br /&gt;One final word of caution: if using an object involves querying more than one of its stateful values, that is also a potential race and you should consider returning an immutable object representing a snapshot of all the queryable state instead.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7677021887363364182-8275462779414806060?l=tobega.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://tobega.blogspot.com/feeds/8275462779414806060/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=7677021887363364182&amp;postID=8275462779414806060' title='9 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7677021887363364182/posts/default/8275462779414806060'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7677021887363364182/posts/default/8275462779414806060'/><link rel='alternate' type='text/html' href='http://tobega.blogspot.com/2008/03/thread-safe-state-handling.html' title='Thread-safe state handling'/><author><name>tobe</name><uri>http://www.blogger.com/profile/00792674914237130365</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='26' height='32' src='http://bp1.blogger.com/_OD0rKvKkvVw/R8f0-n5OxgI/AAAAAAAAAAM/toWm_WfWjVU/S220/tobe.jpg'/></author><thr:total>9</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7677021887363364182.post-8140192782891922341</id><published>2008-03-06T00:45:00.000-08:00</published><updated>2008-03-23T14:58:38.524-07:00</updated><title type='text'>Is synchronisation expensive? Is that the right question?</title><content type='html'>Sometimes I find that I come across a lot of pieces of information which together end up pointing in a certain direction. If you've ever read &lt;a href="http://en.wikipedia.org/wiki/The_Celestine_Prophecy"&gt;"The celestine prophecy"&lt;/a&gt; you might term this "synchronicity", which, by coincidence (or synchronicity), fits very well with the current topic :-).&lt;br /&gt;&lt;br /&gt;The trigger point for this post was that a colleague of mine got into a discussion with a speaker at jFokus about what happens when you "synchronize" (the speaker even &lt;a href="http://kirk.blog-city.com/jfokus.htm"&gt;blogged a bit about it&lt;/a&gt;). Now I know that my colleague usually knows what he is talking about, so what is it? Is synchronization expensive or not?&lt;br /&gt;&lt;br /&gt;When I asked my colleague he said that grabbing an uncontended lock is on the order of 10&lt;span style='font-size: smaller; vertical-align: super;'&gt;-8&lt;/span&gt; seconds. As I had been benchmarking a hash set implementation, I had everything set up to test (and confirm) this. On my machine the overhead for grabbing an uncontended lock (putting the synchronized keyword on a method) was 70ns. Now that sounds pretty cheap, doesn't it? (I have subsequently found out that there are strange issues when running benchmarks. Running again in a supposedly more correct way, the cost of synchrnization would seem to be more like 7ns, or rather, with other noise involved, between 1 and 30, mostly under 10. So my colleague was dead on.)&lt;br /&gt;&lt;br /&gt;Well, considering that I'd just been very happy about reducing the execution time of the method from 30ns to 20ns, the prospect of adding a 70ns overhead was not appealing. So synchronization is expensive, then?&lt;br /&gt;&lt;br /&gt;Turning it around again, how much does it cost you to get stale data in some threads (the data may actually never be updated for some threads)? How much does it cost you if your object gets into an inconsistent state? In that perspective synchronization is usually very cheap.&lt;br /&gt;&lt;br /&gt;&lt;span style="border: 2px solid grey; float: right; width: 40%; background-color: rgb(255, 255, 192);font-size:smaller;" &gt;Swing tries to do without synchronization by mandating that all access to display state needs to be done from the EDT. I sometimes see this expressed as all modifications need to be done on the EDT, but because how the java memory model publishes modifications, I am fairly sure that even querying the state of components needs to be done on the EDT. I'm beginning to think that the Swing threading model causes a viral spread of things to be done on the EDT which can only be broken by having synchronization at some point. This model is perhaps so subtly difficult to handle that it should be considered broken.&lt;/span&gt;The conclusion must be that you have to do what you have to do to protect yourself against the bad effects of unprotected access to shared mutable state and asking whether synchronization is expensive does not necessarily lead you in the right direction. A better question to ask would be "Can I do this in some other way than by accessing shared mutable state?"&lt;br /&gt;&lt;br /&gt;Accessing shared mutable state is really the issue to look at (and where my synchronicity is leading me) and it is fraught with more dangers than just avoiding race conditions. Spot the bug (and I don't mean the obvious one that the access to lineNumber isn't protected):&lt;pre&gt;&lt;br /&gt;  final int[] lineNumber = new int[1];&lt;br /&gt;  while (in.hasNextLine())&lt;br /&gt;  {&lt;br /&gt;    final String line = in.nextLine();&lt;br /&gt;    lineNumber[0]++;&lt;br /&gt;    EventQueue.invokeLater(new Runnable()&lt;br /&gt;    {&lt;br /&gt;      public void run()&lt;br /&gt;      {&lt;br /&gt;        statusLine.setText("" + lineNumber[0]);&lt;br /&gt;        textArea.append(line);&lt;br /&gt;        textArea.append("\n");&lt;br /&gt;      }&lt;br /&gt;    });&lt;br /&gt;  }&lt;br /&gt;&lt;/pre&gt;(&lt;a href='http://weblogs.java.net/blog/cayhorstmann/archive/2008/03/feel_of_java_re.html'&gt;Background to this example&lt;/a&gt;). An example of avoiding access to shared mutable state can be found in &lt;a href='http://tobega.blogspot.com/2008/02/java-closures-and-threads.html'&gt;my first blog post&lt;/a&gt;.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7677021887363364182-8140192782891922341?l=tobega.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://tobega.blogspot.com/feeds/8140192782891922341/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=7677021887363364182&amp;postID=8140192782891922341' title='1 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7677021887363364182/posts/default/8140192782891922341'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7677021887363364182/posts/default/8140192782891922341'/><link rel='alternate' type='text/html' href='http://tobega.blogspot.com/2008/03/is-synchronisation-expensive-is-that.html' title='Is synchronisation expensive? Is that the right question?'/><author><name>tobe</name><uri>http://www.blogger.com/profile/00792674914237130365</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='26' height='32' src='http://bp1.blogger.com/_OD0rKvKkvVw/R8f0-n5OxgI/AAAAAAAAAAM/toWm_WfWjVU/S220/tobe.jpg'/></author><thr:total>1</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7677021887363364182.post-8657989871707274599</id><published>2008-02-28T00:17:00.000-08:00</published><updated>2008-02-28T01:12:54.816-08:00</updated><title type='text'>I wish languageXYZ had inner classes....</title><content type='html'>I've been in love with inner classes since I first encountered them in the first java course I attended.&lt;br /&gt;&lt;br /&gt;I remember we had an exercise to build a text chat client and one thing we had to do was handle a case where a button behaved differently depending on which state it was in. I proceeded to create two different listeners and removed the one and added the other each time the state changed. This surprised the teacher who had never seen any other solution than a simple if-then-else in the one listener (a solution that didn't even enter my head, strangely enough). Perhaps I was going overboard but it just seemed so much tidier.&lt;br /&gt;&lt;br /&gt;The book we got was "Thinking in Java" and, needless to say, I feasted on the chapter about inner classes (greenhouse controls was the example used there) and the realization that the (non-static) inner class lives in the environment formed by the surrounding object. Really cool, I didn't have to pass all state as parameters any more.&lt;br /&gt;&lt;br /&gt;And an inner class can extend the class it resides in, there's great potential there. I was quite taken by the beauty of the hypergeometric probability calculator I wrote up to calculate the probability of a bridge player holding a specific pattern of cards:&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;public class HypergeometricProbability {&lt;br /&gt;    private class SpecificCard extends HypergeometricProbability {&lt;br /&gt;        ...&lt;br /&gt;    }&lt;br /&gt;    ...&lt;br /&gt;    public HypergeometricProbability andHoldsSpecificCard(int ofRemainingCards) {&lt;br /&gt;       /* I wish I knew how to get a reference to the surrounding object without having to pass "this" explicitly. */&lt;br /&gt;       return new SpecificCard(ofRemainingCards, this);&lt;br /&gt;    }&lt;br /&gt;    ...&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;And then you have anonymous classes that can capture state from the method invocation they're declared in. I must confess I generally don't use anonymous classes, I find it usually much neater and more readable to create a named private inner class with a proper constructor encapsulating the needed state.&lt;br /&gt;&lt;br /&gt;Another cool thing in java that I'm still playing with finding the full potential of is java enums. How great is it that they're actual classes that can implement interfaces, extend classes and completely encapsulate all things about the state they represent?&lt;br /&gt;&lt;br /&gt;When researching for my previous blog entry, I came across a blog entry by Daniel Spiewak, &lt;a href='http://www.jroller.com/djspiewak/entry/magic_closure_syntax'&gt;Magic closure syntax&lt;/a&gt;. This roused my curiosity and got me thinking "Can it be that java is different enough that you have to find the java way of doing things? This won't be exactly like you're used to doing it with your favourite abstraction from languageXYZ, but will it necessarily be less elegant?" I hope to be able to explore this question further in following blog entries and you're welcome to provide me with challenges.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7677021887363364182-8657989871707274599?l=tobega.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://tobega.blogspot.com/feeds/8657989871707274599/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=7677021887363364182&amp;postID=8657989871707274599' title='2 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7677021887363364182/posts/default/8657989871707274599'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7677021887363364182/posts/default/8657989871707274599'/><link rel='alternate' type='text/html' href='http://tobega.blogspot.com/2008/02/i-wish-languagexyz-had-inner-classes.html' title='I wish languageXYZ had inner classes....'/><author><name>tobe</name><uri>http://www.blogger.com/profile/00792674914237130365</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='26' height='32' src='http://bp1.blogger.com/_OD0rKvKkvVw/R8f0-n5OxgI/AAAAAAAAAAM/toWm_WfWjVU/S220/tobe.jpg'/></author><thr:total>2</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7677021887363364182.post-9112413151531170422</id><published>2008-02-21T12:13:00.000-08:00</published><updated>2008-02-21T14:15:03.623-08:00</updated><title type='text'>Java closures and threads</title><content type='html'>I have always thought that the biggest weakness of the proposed closures for Java is threading. Strangely enough, the impression one gets from other articles is that closures and threading is a good match and that closures will somehow make threading easier. To analyze this issue I'll start from &lt;a href="http://gafter.blogspot.com/2006/10/concurrent-loops-using-java-closures.html"&gt;Neal Gafter's blog post about concurrent loops and closures&lt;/a&gt;.&lt;br /&gt;&lt;br /&gt;Neal proposes the following code using closures:&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;public Collection&lt;Principal&gt; getAttendees() {&lt;br /&gt;    List&lt;Principal&gt; result = new ArrayList&lt;Principal&gt;();&lt;br /&gt;    for eachConcurrently(EventResponse r : getResponses(), threadPool) {&lt;br /&gt;        if (r.mayAttend()) {&lt;br /&gt;            Principal attendee = r.getAttendee();&lt;br /&gt;            synchronized (result) {&lt;br /&gt;                result.add(attendee);&lt;br /&gt;            }&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;    return result;&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;Imagining myself coming across this code in some code mass I was analyzing, I would think it looked very neat. Then the &lt;tt&gt;synchronized&lt;/tt&gt; keyword would pop out at me and rouse my curiosity, I would look closer and see &lt;tt&gt;for eachConcurrently&lt;/tt&gt; which explains it nicely and I would move on, no problem.&lt;br /&gt;&lt;br /&gt;But what if the synchronized block was missing? How easily would I catch the error?&lt;br /&gt;&lt;br /&gt;Therein lies the weakness, there is no clear signal that there may be other issues to consider, in this case access to shared resources. You may sometimes even be submitting your closure to multi-threaded execution without knowing it. A variation of the same flaw were mechanisms like DCOM that allowed transparent use of remote components.&lt;br /&gt;&lt;br /&gt;At least you get the idea that something out of the ordinary is happening in the horribly clumsy code presented by Neal as being the current state of affairs without closures, no doubt to emphasize his point and inspire fear in the hearts of the doubters.&lt;br /&gt;&lt;br /&gt;But the &lt;tt&gt;java.util.concurrent&lt;/tt&gt; package actually leads you down the right path if you care to follow. A &lt;tt&gt;Callable&lt;/tt&gt; should normally return a result and a &lt;tt&gt;Future&lt;/tt&gt; returns a "canned" execution result from the &lt;tt&gt;Callable&lt;/tt&gt;, or the exception thrown packaged in an &lt;tt&gt;ExecutionException&lt;/tt&gt;, once the processing is done and you are ready to deal with it. Which might lead to the following code instead:&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;  public Collection&lt;Principal&gt; getAttendees() {&lt;br /&gt;    CompletionService&lt;Principal&gt; ecs =&lt;br /&gt;        new ExecutorCompletionService&lt;Principal&gt;(threadPool);&lt;br /&gt;    int numberOfTasks = 0;&lt;br /&gt;    for (final EventResponse r : getResponses()) {&lt;br /&gt;      if (r.mayAttend()) {&lt;br /&gt;        ++numberOfTasks;&lt;br /&gt;        submitGetAttendeeTask(r, ecs);&lt;br /&gt;      }&lt;br /&gt;    }&lt;br /&gt;    return collectGetAttendeeTaskResults(numberOfTasks, ecs);&lt;br /&gt;  }&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;Does that look so formidable? Fair enough, it needs some more code to be complete, but nothing scary there either:&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;  private void submitGetAttendeeTask(final EventResponse r,&lt;br /&gt;      CompletionService&lt;Principal&gt; ecs) {&lt;br /&gt;    ecs.submit(new Callable&lt;Principal&gt;() {&lt;br /&gt;      public Principal call() {&lt;br /&gt;        return r.getAttendee();&lt;br /&gt;      }&lt;br /&gt;    });&lt;br /&gt;  }&lt;br /&gt;&lt;br /&gt;  private Collection&lt;Principal&gt; collectGetAttendeeTaskResults(int numberOfTasks,&lt;br /&gt;      CompletionService&lt;Principal&gt; ecs) {&lt;br /&gt;    final List&lt;Principal&gt; result = new ArrayList&lt;Principal&gt;();&lt;br /&gt;    for (int i = 0; i &lt; numberOfTasks; ++i) {&lt;br /&gt;      try {&lt;br /&gt;        result.add(ecs.take().get());&lt;br /&gt;      } catch (InterruptedException ex) {&lt;br /&gt;        throw new AssertionError(ex); // shouldn't happen&lt;br /&gt;      } catch (ExecutionException ex) {&lt;br /&gt;        throw new AssertionError(ex); // shouldn't happen&lt;br /&gt;      }&lt;br /&gt;    }&lt;br /&gt;    return result;&lt;br /&gt;  }&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;Having come this far, it would certainly be nice to lose some of the boilerplate in creating the Callable and the possible unwrapping of the ExecutionException, so there are certainly some good motivations behind closures. Can this be solved by other means? Certainly, CICE would help with the first, and for the second there could be devised a cute way of specifying and parametrizing sets of exceptions rather than having &lt;tt&gt;Callable throws Exception&lt;/tt&gt; and &lt;tt&gt;Future.get() throws ExecutionException&lt;/tt&gt;. One thing you still would have to deal with is the &lt;tt&gt;InterruptedException&lt;/tt&gt; that is thrown if your main thread is interrupted while waiting for the results. But that is something you maybe should think about or at least might want to think about or use in the future, it is one of those threading issues after all.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7677021887363364182-9112413151531170422?l=tobega.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://tobega.blogspot.com/feeds/9112413151531170422/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=7677021887363364182&amp;postID=9112413151531170422' title='1 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7677021887363364182/posts/default/9112413151531170422'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7677021887363364182/posts/default/9112413151531170422'/><link rel='alternate' type='text/html' href='http://tobega.blogspot.com/2008/02/java-closures-and-threads.html' title='Java closures and threads'/><author><name>tobe</name><uri>http://www.blogger.com/profile/00792674914237130365</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='26' height='32' src='http://bp1.blogger.com/_OD0rKvKkvVw/R8f0-n5OxgI/AAAAAAAAAAM/toWm_WfWjVU/S220/tobe.jpg'/></author><thr:total>1</thr:total></entry></feed>
