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

<channel>
	<title>Note To Self &#187; java</title>
	<atom:link href="http://www.hawksley.net/tag/java/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.hawksley.net</link>
	<description>John Hawksley &#124; www.hawksley.net</description>
	<lastBuildDate>Sun, 30 May 2010 14:13:46 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=abc</generator>
		<item>
		<title>Mac OS X Snow Leopard Has No Java 5 &#8211; Warning!</title>
		<link>http://www.hawksley.net/2009/09/mac-os-x-snow-leopard-has-no-java-5-warning/</link>
		<comments>http://www.hawksley.net/2009/09/mac-os-x-snow-leopard-has-no-java-5-warning/#comments</comments>
		<pubDate>Thu, 24 Sep 2009 07:59:24 +0000</pubDate>
		<dc:creator>John</dc:creator>
				<category><![CDATA[Software Engineering]]></category>
		<category><![CDATA[eclipse]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[jdbc]]></category>

		<guid isPermaLink="false">http://www.hawksley.net/?p=149</guid>
		<description><![CDATA[Here&#8217;s one I spent a day learning: OS X 10.6 &#8220;Snow Leopard&#8221; has no Java 5 installed, despite appearances to the contrary. The Java 1.5 installation is actually a symbolic link to the Java 1.6 installation. There is a fix available, which essentially entails copying the Java 1.5 installation from a Leopard install, and fixing [...]]]></description>
			<content:encoded><![CDATA[<p>Here&#8217;s one I spent a day learning:  OS X 10.6 &#8220;Snow Leopard&#8221; has <em>no</em> Java 5 installed, despite appearances to the contrary.</p>
<p>The Java 1.5 installation is actually a symbolic link to the Java 1.6 installation.  There is a fix available, which essentially entails copying the Java 1.5 installation from a Leopard install, and fixing up the symlinks.  It&#8217;s available <a href="http://wiki.oneswarm.org/index.php/OS_X_10.6_Snow_Leopard">here</a>.</p>
<p>I found this because we have a product which must be linked against Java 1.5, or rather, the JDBC version 3 specification.  We don&#8217;t yet support all the extended functionality of JDBC 4.</p>
<p>In Eclipse, I had selected Java 5 (= JDBC 3) as the JRE, but was still getting lots of &#8220;method unimplemented&#8221; errors for JDBC 4 (= Java 6) signatures.  These aren&#8217;t present in Java 5, so they should not have appeared.</p>
<p>After unfolding the JRE Library node in the Eclipse Package Explorer, it was clear that, although the JRE was reporting itself as Java 5, the jars within were clearly coming from Java 6.</p>
<p>I applied the <a href="http://wiki.oneswarm.org/index.php/OS_X_10.6_Snow_Leopard">fix</a> and the compiler errors disappeared &#8211; Java 5/JDBC 3 was in use again.</p>
<p>For (my) future reference, here are the JDK / JDBC versions:</p>
<ul>
<li>JDK 1.1 → JDBC 1.2</li>
<li>JDK 1.2 → JDBC 2.1</li>
<li>JDK 1.4 → JDBC 3</li>
<li>JDK 1.5 → JDBC 3</li>
<li>JDK 1.6 → JDBC 4</li>
</ul>
<p><a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save"><img src="http://www.hawksley.net/wp-content/plugins/add-to-any/share_save_120_16.png" width="120" height="16" alt="Share/Bookmark"/></a> </p>]]></content:encoded>
			<wfw:commentRss>http://www.hawksley.net/2009/09/mac-os-x-snow-leopard-has-no-java-5-warning/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Using Eclipse on Small Screens</title>
		<link>http://www.hawksley.net/2009/08/using-eclipse-on-small-screens/</link>
		<comments>http://www.hawksley.net/2009/08/using-eclipse-on-small-screens/#comments</comments>
		<pubDate>Tue, 25 Aug 2009 08:31:25 +0000</pubDate>
		<dc:creator>John</dc:creator>
				<category><![CDATA[Software Engineering]]></category>
		<category><![CDATA[eclipse]]></category>
		<category><![CDATA[java]]></category>

		<guid isPermaLink="false">http://www.hawksley.net/?p=145</guid>
		<description><![CDATA[Two awesome plugins for those of us using Eclipse on screens with low resolutions: Eclipse Visual Studio Presentation &#8211; changes the presentation of Eclipse to require rather less height and width and a lot more besides Eclipse FullScreen Plugin &#8211; adds a context menu and keyboard shortcut (CTRL-ALT-Z) to full-screen Eclipse (covering any menu/taskbars). Also [...]]]></description>
			<content:encoded><![CDATA[<p>Two awesome plugins for those of us using Eclipse on screens with low resolutions:</p>
<ul>
<li><a href="http://andrei.gmxhome.de/skins/index.html">Eclipse Visual Studio Presentation</a> &#8211; changes the presentation of Eclipse to require rather less height and width and a lot more besides</li>
<li><a href="http://code.google.com/p/eclipse-fullscreen/">Eclipse FullScreen Plugin</a> &#8211; adds a context menu and keyboard shortcut (CTRL-ALT-Z) to full-screen Eclipse (covering any menu/taskbars).</li>
</ul>
<p>Also to consider:</p>
<ul>
<li>Is your editor font too big? Can you make it smaller and still be comfortable working with it?</li>
<li>Look at your window layout &#8211; do you have a view docked to the right of the editor &#8211; probably Outline? Do you <em>really</em> ever use outline?  Get rid of it if not, or make it a tab in the dock on the left.</li>
</ul>
<p><a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save"><img src="http://www.hawksley.net/wp-content/plugins/add-to-any/share_save_120_16.png" width="120" height="16" alt="Share/Bookmark"/></a> </p>]]></content:encoded>
			<wfw:commentRss>http://www.hawksley.net/2009/08/using-eclipse-on-small-screens/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Misleading Java Generic Errors in Eclipse</title>
		<link>http://www.hawksley.net/2009/08/misleading-java-generic-errors-in-eclipse/</link>
		<comments>http://www.hawksley.net/2009/08/misleading-java-generic-errors-in-eclipse/#comments</comments>
		<pubDate>Wed, 19 Aug 2009 18:22:06 +0000</pubDate>
		<dc:creator>John</dc:creator>
				<category><![CDATA[Software Engineering]]></category>
		<category><![CDATA[eclipse]]></category>
		<category><![CDATA[java]]></category>

		<guid isPermaLink="false">http://www.hawksley.net/?p=129</guid>
		<description><![CDATA[An incompatibility between Java source versions in Eclipse made a generics error show up as: Type mismatch: cannot convert from Object to ILocationService. when it should really have read something like: Type mismatch: return type of TypeLoader is generic &#8211; this project is not. Here&#8217;s what happened to trigger this error. The type TypeLoader contains [...]]]></description>
			<content:encoded><![CDATA[<p>An incompatibility between Java source versions in Eclipse made a generics error show up as:</p>
<blockquote><p>Type mismatch: cannot convert from Object to ILocationService.</p></blockquote>
<p>when it should really have read something like:</p>
<blockquote><p>Type mismatch: return type of TypeLoader is generic &#8211; this project is not.</p></blockquote>
<p><span id="more-129"></span></p>
<p>Here&#8217;s what happened to trigger this error.</p>
<p>The type <code>TypeLoader</code> contains a generic method with the following signature:</p>
<pre class="brush: java">
    public static &lt;T&gt; T loadType( String name, Class&lt;T&gt; forType ) throws TypeLoaderException
</pre>
<p>My call &#8211; which was not in a generic project &#8211; looks like this:</p>
<pre class="brush: java">
        ILocationService ls = TypeLoader.loadType( locationServiceClass, ILocationService.class );
</pre>
<p>Eclipse&#8217;s exception &#8211; <em>Cannot convert from Object to ILocationService</em> &#8211; is a bit misleading, since there is no cast there:  the generic type parameter is defined by <code>ILocationService.class</code> which is of type <code>Class&lt;ILocationService&gt;</code>, and in fact the <code>TypeLoader</code> passes all its JUnit tests.</p>
<p>The solution was that I&#8217;d upated the master POM for the project containing the call, but not updated the project in Eclipse (using m2eclipse&#8217;s menu <code>Maven &gt; Update Project Configuration</code>.  Once I&#8217;d done this, m2eclipse updated the source version from 1.4 to 1.6 &#8211; and the exception went away.</p>
<p><a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save"><img src="http://www.hawksley.net/wp-content/plugins/add-to-any/share_save_120_16.png" width="120" height="16" alt="Share/Bookmark"/></a> </p>]]></content:encoded>
			<wfw:commentRss>http://www.hawksley.net/2009/08/misleading-java-generic-errors-in-eclipse/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Reducing Tooltip Time in Eclipse 3.5 (Galileo) on Mac OS X</title>
		<link>http://www.hawksley.net/2009/06/reducing-tooltip-time-in-eclipse-3-5-galileo-on-mac-os-x/</link>
		<comments>http://www.hawksley.net/2009/06/reducing-tooltip-time-in-eclipse-3-5-galileo-on-mac-os-x/#comments</comments>
		<pubDate>Thu, 25 Jun 2009 09:42:39 +0000</pubDate>
		<dc:creator>John</dc:creator>
				<category><![CDATA[Software Engineering]]></category>
		<category><![CDATA[eclipse]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[mac]]></category>

		<guid isPermaLink="false">http://www.hawksley.net/?p=103</guid>
		<description><![CDATA[Tooltips in Mac OS X display, by default, after 2 seconds. I find this is ample time in the general operating system, but in Eclipse it&#8217;s an eternity. Eclipse uses Tooltips in the Java tooling to display all kinds of useful information, not the least of which is the javadoc for the element and the [...]]]></description>
			<content:encoded><![CDATA[<p>Tooltips in Mac OS X display, by default, after 2 seconds.  I find this is ample time in the general operating system, but in <a href="http://www.eclipse.org">Eclipse</a> it&#8217;s an eternity.  Eclipse uses Tooltips in the Java tooling to display all kinds of useful information, not the least of which is the javadoc for the element and the source.  Waiting for these is frustrating.</p>
<p>The general workaround of using OS X defaulting to change that didn&#8217;t work with previous versions of Eclipse because the SWT (IBM&#8217;s excellent widget set) was built on Carbon, OS X&#8217;s &#8220;UI Compatibility Library&#8221;, which ignored the default.  Eclipse is now available for Mac in a native Cocoa version, which <em>does </em>take the defaulting into account.</p>
<p>Here&#8217;s how to change the global OS X tooltip delay (in Terminal):</p>
<pre>defaults write -g NSInitialToolTipDelay -int 100</pre>
<p>I personally want to keep the 2-second delay for everything except Eclipse, so I applied the default just to Eclipse using the Eclipse bundle name:</p>
<pre>defaults write org.eclipse.eclipse NSInitialToolTipDelay -int 100</pre>
<p>The delay time is in milliseconds. You might have to log out and back in again to make the default take, but usually restarting Eclipse does the trick.</p>
<p>Nice work IBM!</p>
<p><a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save"><img src="http://www.hawksley.net/wp-content/plugins/add-to-any/share_save_120_16.png" width="120" height="16" alt="Share/Bookmark"/></a> </p>]]></content:encoded>
			<wfw:commentRss>http://www.hawksley.net/2009/06/reducing-tooltip-time-in-eclipse-3-5-galileo-on-mac-os-x/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Overloading the Eclipse Job Management System</title>
		<link>http://www.hawksley.net/2009/04/overloading-the-eclipse-job-management-system/</link>
		<comments>http://www.hawksley.net/2009/04/overloading-the-eclipse-job-management-system/#comments</comments>
		<pubDate>Thu, 30 Apr 2009 12:40:35 +0000</pubDate>
		<dc:creator>John</dc:creator>
				<category><![CDATA[Software Engineering]]></category>
		<category><![CDATA[asynchronous]]></category>
		<category><![CDATA[eclipse]]></category>
		<category><![CDATA[java]]></category>

		<guid isPermaLink="false">http://www.hawksley.net/?p=96</guid>
		<description><![CDATA[We&#8217;ve had an issue with our Eclipse-based application which would cause it to slow down exponentially under stress test.  The problem lie in the job management system:  new fast code could essentially cause it to bog down under the weight of update jobs. Eclipse is one of those pieces of software which is rather difficult [...]]]></description>
			<content:encoded><![CDATA[<p>We&#8217;ve had an issue with our Eclipse-based application which would cause it to slow down exponentially under stress test.  The problem lie in the job management system:  new fast code could essentially cause it to bog down under the weight of update jobs.</p>
<p><span id="more-96"></span></p>
<p>Eclipse is one of those pieces of software which is rather difficult to explain accurately:  it&#8217;s a platform for building GUI applications, it&#8217;s written in Java.  It provides lots of services to make writing applications easier.  It&#8217;s a pretty good choice for building cross-platform GUI apps.  If you are a Java programmer, chances are that you either work inside Eclipse&#8217;s Java Development Tools (JDT) plugins or you&#8217;ve at least evaluated the platform.</p>
<p>One of our products runs as a plugin within Eclipse, and overall we&#8217;re very happy with the platform.  Lately, though, we&#8217;ve been through a refactoring process to split out the core of our product and some of the dependencies.  Coupled with some other fixes, we&#8217;ve managed to obtain quite a significant speed increase in how our backend works.</p>
<p>When we came to stress-test the application in order to check it performed under load, we found that instead of an overall increase in speed, we were seeing quite a significant decrease.</p>
<p>To explain this we had to look at the Eclipse job system.  Internally, the Eclipse platform schedules events from the UI (button presses, pending window updates etc.) as jobs.  Corresponding updates to UI elements are also scheduled in the same way.  When a worker thread becomes free, the job manager selects a suitable job (based on priority) and allows it to run.  Ordinarily there are a handfull of jobs in the job queue and they are cleared quickly, and the UI remains responsive.</p>
<p>Our refactoring had produced such a large increase in speed, that the resulting update jobs were flooding the job manager.  After a two-minute stress test, it would take the platform somewhere in the region of 20 seconds (depending on the CPU cycles available) to clear the job queue and return to a responsive state.</p>
<p>We added debugging to show us the size of the job queue, and figures upwards of 3,000 pending jobs were not uncommon.  A single (non-stress) command event telling our backend to do something would generate around 9 internal Eclipse update jobs to update various parts of the UI.  With a suitably high injection speed (which the new code was handling fine), the number of corresponding UI update jobs quickly went through the roof.</p>
<p>The solution, in the end, was uncomplicated:  we throttled the incoming command events (by abandoning some) if the job queue started to get too large. With a suitable throttle value, the backend could be kept busy (but not <em>too </em>busy) without overloading the job manager.</p>
<p>Kudos to my teammate Peter Bailey for doing excellent work on this problem.</p>
<p><a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save"><img src="http://www.hawksley.net/wp-content/plugins/add-to-any/share_save_120_16.png" width="120" height="16" alt="Share/Bookmark"/></a> </p>]]></content:encoded>
			<wfw:commentRss>http://www.hawksley.net/2009/04/overloading-the-eclipse-job-management-system/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Eclipse Won&#8217;t Update Any More</title>
		<link>http://www.hawksley.net/2009/02/eclipse-wont-update-any-more/</link>
		<comments>http://www.hawksley.net/2009/02/eclipse-wont-update-any-more/#comments</comments>
		<pubDate>Thu, 26 Feb 2009 22:18:25 +0000</pubDate>
		<dc:creator>John</dc:creator>
				<category><![CDATA[Software Engineering]]></category>
		<category><![CDATA[eclipse]]></category>
		<category><![CDATA[java]]></category>

		<guid isPermaLink="false">http://www.hawksley.net/?p=67</guid>
		<description><![CDATA[If you use Eclipse with lots of plugins, eventually you might get into a situation where the Software Updates &#8216;feature&#8217; doesn&#8217;t work any more.  It will find updates okay, but when you come to install them, you&#8217;ll get a message which reads something like &#8220;No repository could be found containing bundle&#8230;&#8221;.   I think I&#8217;ve solved [...]]]></description>
			<content:encoded><![CDATA[<p>If you use <a href="http://www.eclipse.org/">Eclipse</a> with lots of plugins, eventually you might get into a situation where the <strong>Software Updates</strong> &#8216;feature&#8217; doesn&#8217;t work any more.  It will <em>find</em> updates okay, but when you come to install them, you&#8217;ll get a message which reads something like &#8220;No repository could be found containing bundle&#8230;&#8221;.   I think I&#8217;ve solved this problem.</p>
<p><span id="more-67"></span>I&#8217;m guessing this is because:</p>
<ul>
<li>behind the scenes, the new <a href="http://wiki.eclipse.org/Equinox/p2">P2</a> provisioner system (introduced with Ganymede) has located the update and appropriate mirror, but that mirror has not yet received the build products, <strong>or</strong></li>
<li>one or more plugins has added its own &#8216;associate&#8217; update/discovery sites to the list, which is no longer an update site, or is corrupt, or has gone away completely</li>
</ul>
<p>This is incredibly frustrating for those of us trying to keep their tools up to date.</p>
<h3><strong>Solved</strong></h3>
<p>Download, unpack and start the same Eclipse distribution you originally had (J2EE in my case).  Don&#8217;t start it on your live engineering workspace.</p>
<p>In <strong>Software Updates -&gt; Available Software -&gt; Manage Sites</strong>, <em>export</em> the sites which are pre-installed there.</p>
<p>In your non-updating Eclipse, in <strong>Manage Sites</strong>, select all and <strong>Remove. </strong>Then <em>import</em> the sites from the other installation.  That should get it updating again.</p>
<h3>Caveat</h3>
<p>You&#8217;re going to have to find the update sites for your extra plugins and add them in to <strong>Manage Sites</strong> yourself.  This is, in my opinion, a small price to pay to get the updater back.</p>
<h3>Doing Updates</h3>
<p>Here&#8217;s a small trick.  When doing updates in Eclipse, make sure the <strong>Progress</strong> view is visible (<strong>Window -&gt; Show View -&gt; Progress</strong>) somewhere not covered by the Software Updates and Add-ons window and the inevitable modal <strong>Progress Information </strong>window.  If you do that, you can see a progress bar and not the tiny notification in the bottom right of the Eclipse window.</p>
<p><a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save"><img src="http://www.hawksley.net/wp-content/plugins/add-to-any/share_save_120_16.png" width="120" height="16" alt="Share/Bookmark"/></a> </p>]]></content:encoded>
			<wfw:commentRss>http://www.hawksley.net/2009/02/eclipse-wont-update-any-more/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>The Hidden Danger of Synchronization</title>
		<link>http://www.hawksley.net/2009/02/the-hidden-danger-of-synchronization/</link>
		<comments>http://www.hawksley.net/2009/02/the-hidden-danger-of-synchronization/#comments</comments>
		<pubDate>Fri, 20 Feb 2009 13:47:58 +0000</pubDate>
		<dc:creator>John</dc:creator>
				<category><![CDATA[Software Engineering]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[synchronizers]]></category>
		<category><![CDATA[threads]]></category>

		<guid isPermaLink="false">http://www.hawksley.net/?p=48</guid>
		<description><![CDATA[A programmer realised he had a problem which could be solved using threads. Now he has two problems. This isn&#8217;t going to be an anti-thread post, but I do want to sound a few words of caution about threads, and, specifically, synchronizers and monitors, and the order in which you acquire them. Threads are a [...]]]></description>
			<content:encoded><![CDATA[<p><img class="size-thumbnail wp-image-49 alignright" title="Locked Up" src="http://www.hawksley.net/wp-content/uploads/2009/02/padlock-150x150.jpg" alt="padlock" width="150" height="150" /></p>
<blockquote><p>A programmer realised he had a problem which could be solved using threads.<br />
Now he has <em>two</em> problems.</p></blockquote>
<p>This isn&#8217;t going to be an anti-thread post, but I do want to sound a few words of caution about threads, and, specifically, synchronizers and monitors, and the order in which you acquire them.</p>
<p><span id="more-48"></span>Threads <em>are </em>a solution to a number of problems.    Java threads are easy to use and (since we got rid of &#8216;green&#8217; threads and got real ones instead) become real O/S threads, mapping onto available processor cores as required.  This means that any tasks which can be parallelised, where speed of completion is important, or jobs which exhibit properties allowing the job space to be split and processed/merged separately, are prime targets for threading and the inherent speedup of being farmed out to parallel cores.</p>
<p>This will become ever more important as processors stop becoming faster (in fact I think this point has already been reached &#8211; Intel&#8217;s Core i7&#8242;s clock speed is still only 3.20 GHz, clever pipelining notwithstanding), and start gaining massively more cores.  The more parallelization you can find in tasks, the faster your total execution.</p>
<p>The problem with threads is synchronizers. As engineers we try to avoid synchronizers if possible because of the inherent cost of the JVM processing them (especially inflated &#8216;slow&#8217; synchronizers), but there&#8217;s no denying the mechanism <em>is</em> useful.</p>
<p>The old tenets of monitor locking still apply:</p>
<ul>
<li>If you can get away with not doing it and still produce correct code  &#8211; don&#8217;t do it</li>
<li>Reduce the scope of the monitor acquisition as far as possible</li>
<li>Obtain monitors in the same order all over the code</li>
</ul>
<p>The last point is the one which is mostly likely to cause problems.  It&#8217;s easy to find problems if you have code which looks like this:</p>
<pre>synchronized(a){
    synchronized(b){</pre>
<p>.. in some other class:</p>
<pre>synchronized(b) {
    synchronized(a) {</pre>
<p>There we see an explicit pair of synchronizers and the out-of-order acquisition of locks in this case is a prime case for classic deadlock.</p>
<p>But what about this:</p>
<pre>synchronized(a){
    synchronized(b){</pre>
<p>.. in some other class:</p>
<pre>synchronized(b){
    someMethodCall();
}

void someMethodCall() {
   synchronized(a) {</pre>
<p>This case is slightly more tricky:  the locks are indeed obtained out of order, but not immediately.  In fact the acquisition of the second lock on &#8216;a&#8217; might not occur in the next method; it might occur several stack frames later.  You might not find out about it unless you use a thread-analyser package (very pricey), or a ticket hits your mailbox (and deadlocks generally count as <strong>Critical/Escalated</strong> priority).</p>
<p>The acquisition of the second lock isn&#8217;t obvious.   The signature of the method doesn&#8217;t make it obvious;  the only way you&#8217;ll know is by looking at the code, and if there are many execution branches away from this point in the code, that is going to take an unfeasibly long time.</p>
<p>The javadoc for the method might make it clear in the contract for the method, but again:  if there are still many possible method calls after this one, that&#8217;s a lot of javadoc to review.</p>
<p>So how do we solve this problem?</p>
<p>Don&#8217;t obtain the locks at all.  If you don&#8217;t need them, don&#8217;t grab them.  No locking means no chance of deadlock.  The corollary of this rule is that the fewer locks you grab, the lower the chance of deadlock.</p>
<p>Keep the scope of locks as small as possible.  The shorter time you hold a lock for, the lower the chance of deadlock</p>
<p>Obtain the locks in the same order, everywhere.  In extreme cases, this might mean obtaining a lock twice.  To go back to our second example above:</p>
<pre>synchronized(a){
    synchronized(b){</pre>
<p>.. in some other class:</p>
<pre>synchronized(a) {
    synchronized(b){
        someMethodCall();
}

void someMethodCall() {
   synchronized(a) {</pre>
<p>Of course, if you could eliminate one or both synchronizers, that would be the best solution, but this one also works because Java&#8217;s locks are re-entrant:  the second acquisition in <strong>someMethodCall</strong> effectively does nothing, since the thread already holds the monitor thanks to the explicit acquisition prior to the call.  However, it does make the locking order <strong>a -&gt; b</strong>, instead of <strong>b -&gt; a</strong>, eliminating the deadlock.</p>
<p>It&#8217;s not possible in some cases to eliminate synchronizers.  Time pressures may mean the test set for adding a synchronizer is much smaller than that for removing one and therefore preferable;  you may not be able to influence the code in <strong>someMethodCall</strong> for whatever reason, etc. etc.</p>
<p>Being aware of the effects and dangers of synchronization when you write code should help you avoid the pitfalls.  Synchronizers are useful and sometimes necessary, but with great power comes great responsibility.</p>
<p>I think I heard that in a movie somewhere.</p>
<p><a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save"><img src="http://www.hawksley.net/wp-content/plugins/add-to-any/share_save_120_16.png" width="120" height="16" alt="Share/Bookmark"/></a> </p>]]></content:encoded>
			<wfw:commentRss>http://www.hawksley.net/2009/02/the-hidden-danger-of-synchronization/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
	</channel>
</rss>
