<?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>Smartkey - Java Software Consultancy &#187; Programming</title>
	<atom:link href="http://blog.smartkey.co.uk/tag/programming/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.smartkey.co.uk</link>
	<description></description>
	<lastBuildDate>Tue, 13 Dec 2011 15:03:46 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8.4</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Adding a thread timeout to methods in Java</title>
		<link>http://blog.smartkey.co.uk/2011/09/adding-a-thread-timeout-to-methods-in-java/</link>
		<comments>http://blog.smartkey.co.uk/2011/09/adding-a-thread-timeout-to-methods-in-java/#comments</comments>
		<pubDate>Thu, 01 Sep 2011 13:19:55 +0000</pubDate>
		<dc:creator>Steve Neal</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[Java Programming]]></category>
		<category><![CDATA[Concurrency]]></category>
		<category><![CDATA[Concurrent]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Thread]]></category>

		<guid isPermaLink="false">http://blog.smartkey.co.uk/?p=924</guid>
		<description><![CDATA[When calling a method that could potentially take longer that you&#8217;d like to complete, it is possible to write code that will back out after a given time period. 
This can happen in numerous circumstances where you&#8217;d like an application to maintain a degree of liveness. I&#8217;ve used it recently in an application that needed [...]]]></description>
			<content:encoded><![CDATA[<p>When calling a method that could potentially take longer that you&#8217;d like to complete, it is possible to write code that will back out after a given time period. </p>
<p>This can happen in numerous circumstances where you&#8217;d like an application to maintain a degree of liveness. I&#8217;ve used it recently in an application that needed to run a number of external scripts; if the script does not complete, for whatever reason, the timeout ensures the the calling thread does not get blocked and the remaining scripts can be launched.</p>
<p>Here&#8217;s the basic idea:</p>
<pre class="brush: php">
public class TimeoutDemo {

    //maintains a thread for executing the doWork method
    private ExecutorService executor = Executors.newFixedThreadPool(1);

    public void doWork() {
        //perform some long running task here...
    }

    public void doWorkWithTimeout(int timeoutSecs) {

        //set the executor thread working
        final Future&lt;?&gt; future = executor.submit(new Runnable() {
            public void run() {
                try {
                    doWork();
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
        });

        //check the outcome of the executor thread and limit the time allowed for it to complete
        try {
            future.get(timeoutSecs, TimeUnit.SECONDS);
        } catch (Exception e) {
            //ExecutionException: deliverer threw exception
            //TimeoutException: didn&#039;t complete within downloadTimeoutSecs
            //InterruptedException: the executor thread was interrupted

            //interrupts the worker thread if necessary
            future.cancel(true);

            log.warn(&quot;encountered problem while doing some work&quot;, e);
        }
    }
}
</pre>
<p>The doWork method is the one that will actually do some potentially long running work. The doWorkWithTimeout illustrates how the java.util.concurrent classes can be used to prevent the method from taking too long to complete. When calling the latter method, just specify the timeout period in minutes.</p>
<p>The trick here is that the actual work will be done by a dedicated worker thread. The calling thread will handle the timeout management and also handle any exceptions thrown by the worker.</p>
<p>Variations of this pattern can be used for methods that accept parameters (just make them final) and for ones that return values too (just return the value from the future.get(&#8230;) call).</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.smartkey.co.uk/2011/09/adding-a-thread-timeout-to-methods-in-java/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Using Assertions in Java</title>
		<link>http://blog.smartkey.co.uk/2010/02/java-assertions/</link>
		<comments>http://blog.smartkey.co.uk/2010/02/java-assertions/#comments</comments>
		<pubDate>Thu, 18 Feb 2010 14:47:25 +0000</pubDate>
		<dc:creator>Steve Neal</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[Java Programming]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://blog.smartkey.co.uk/?p=607</guid>
		<description><![CDATA[I&#8217;ve been working on a project this week and have been delighted to see that the original team of programmers who developed it have made the effort to use assertions in their code. 
The assert keyword was introduced in Java 1.4 and has since been a sadly under-used language feature. Assertions offer developers a neat [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve been working on a project this week and have been delighted to see that the original team of programmers who developed it have made the effort to use assertions in their code. </p>
<p>The assert keyword was introduced in Java 1.4 and has since been a sadly under-used language feature. Assertions offer developers a neat way to implement error detecting statements that are only active during development and can be turned off in production environments. </p>
<p>For example you might want to check that appropriate values are passed to a method during development to ensure that it is being called correctly:</p>
<pre class="brush: java">
private void onlyPositiveNumbersPlease(int i) {
    assert i &gt; 0;

    //rest of method implementation...

}
</pre>
<p>If the assertion fails, then an AssertionError is thrown. If you have a lot of assertions in your code, then its useful to be able to specify a value that will be used in the error message:</p>
<pre class="brush: java">
private void onlyPositiveNumbersPlease(int i) {
    assert i &gt; 0 : &quot;only positive numbers are allowed&quot;;

    //rest of method implementation...

}
</pre>
<p>The value that is specified can also be any primitive type, for example:</p>
<pre class="brush: java">
File f = loadFile();
assert f != null : 404;
</pre>
<p>In all cases, the value is converted to a String and set as the detail message of the AssertionException.</p>
<p>When the Java source is compiled, assertions instructions are included in the bytecode that is generated. However, by default, the assertions are not executed at runtime.</p>
<p>In order to activate all of the assertions, a command line flag must be passed to the JVM:<code></p>
<p>$ java <b>-ea</b> co.uk.smartkey.ui.MainClass<br />
</code></p>
<p>it is also possible to specify that assertions should only be activated for classes within a certain package. For example to run the same application as before, but only activate assertions for classes in the util package of our application, you could use something like:<code></p>
<p>$ java <b>-ea:co.uk.smartkey.util</b> co.uk.smartkey.ui.MainClass<br />
</code></p>
<p>if you just wanted to turn on assertions for a single class, you can specify the class name instead of the package name. Finally, if you really feel the need to, you can turn on assertions in the Java system classes with this:<code></p>
<p>$ java <b>-esa</b> co.uk.smartkey.ui.MainClass<br />
</code></p>
<p>Personally, I like using assertions as they can help to iron out problems during development that are unlikely to need checking for in production. Language level support for them means that the statements are only used if the JVM is launched with them activated; this ensures that there is no performance overhead associated with them when they are not in use.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.smartkey.co.uk/2010/02/java-assertions/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>

