<?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>blog.smart-java.nl &#187; Java API</title>
	<atom:link href="http://blog.smart-java.nl/blog/index.php/category/java-api/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.smart-java.nl/blog</link>
	<description>Ordina J-Technologies - Java Blog</description>
	<lastBuildDate>Wed, 05 May 2010 20:06:33 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.1</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Reflection slow? Class vs. Constructor newInstance</title>
		<link>http://blog.smart-java.nl/blog/index.php/2010/05/01/reflection-slow-class-vs-constructor-newinstance/</link>
		<comments>http://blog.smart-java.nl/blog/index.php/2010/05/01/reflection-slow-class-vs-constructor-newinstance/#comments</comments>
		<pubDate>Sat, 01 May 2010 18:53:46 +0000</pubDate>
		<dc:creator>Jan-Kees van Andel</dc:creator>
				<category><![CDATA[Java API]]></category>
		<category><![CDATA[performance]]></category>
		<category><![CDATA[benchmark]]></category>
		<category><![CDATA[hotspot]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[reflection]]></category>

		<guid isPermaLink="false">http://blog.smart-java.nl/blog/?p=1083</guid>
		<description><![CDATA[My last article triggered a lot of responses of people, which I, of course, try to answer.
One question, by Tofarr, was: 

You are not caching the contructor! class.newInstance() internally looks for the no arg constructor each time – I would be curious to see how doing a Constructor c = class.getConstructor() would affect the timing…

This [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://blog.smart-java.nl/blog/index.php/2010/04/25/reflection-slow-well-it-depends/">My last article</a> triggered a lot of responses of people, which I, of course, try to answer.</p>
<p><a href="http://blog.smart-java.nl/blog/index.php/2010/04/25/reflection-slow-well-it-depends/#comment-594">One question, by Tofarr</a>, was: </p>
<blockquote><p>
You are not caching the contructor! class.newInstance() internally looks for the no arg constructor each time – I would be curious to see how doing a Constructor c = class.getConstructor() would affect the timing…
</p></blockquote>
<p>This is not for 100% true, since (at least in my Java version) <a href="http://java.sun.com/javase/6/docs/api/java/lang/Class.html#newInstance%28%29">Class.newInstance()</a> caches the no-arg constructor after it&#8217;s first lookup. But, the suggestion is worth trying.</p>
<p>So, let&#8217;s go!</p>
<h3>Caching and instantiating the Class</h3>
<p>In the <a href="http://blog.smart-java.nl/blog/index.php/2010/04/25/reflection-slow-well-it-depends/">original article</a>, this was the task with the cached Class object.</p>
<pre><script type="syntaxhighlighter" class="brush: java">
    private static Callable<Integer> CACHED_CLASS_REFLECTION_ACCESS_TASK = new Callable<Integer>() {
        private final Class<JavaBean> classCache;
        {
            try {
                classCache = (Class<JavaBean>) Class.forName("nl.jkva.asm.JavaBean");
            } catch (ClassNotFoundException e) {
                throw new RuntimeException("Cannot initialize JavaBean", e);
            }
        }

        @Override
        public Integer call() throws Exception {
            int counter = 31;
            for (int i = 0; i < ITERATIONS; i++) {
                JavaBean bean = classCache.newInstance();
                classCache.getMethod("setValue", Integer.TYPE).invoke(bean, i);
                final int value = (Integer) classCache.getMethod("getValue").invoke(bean);
                counter = 37 * counter + value;
            }

            return counter;
        }
    };
</script></pre>
<h3>Caching and invoking the Constructor</h3>
<p>So I added a simple implementation which caches the <a href="http://java.sun.com/javase/6/docs/api/java/lang/reflect/Constructor.html">Constructor</a> object, like this:</p>
<pre><script type="syntaxhighlighter" class="brush: java">
    private static Callable<Integer> CACHED_CONSTRUCTOR_REFLECTION_ACCESS_TASK = new Callable<Integer>() {
        private final Class<JavaBean> classCache = JavaBean.class;
        private final Constructor<JavaBean> constructorCache;
        {
            try {
                constructorCache = classCache.getDeclaredConstructor();
            } catch (Exception e) {
                throw new RuntimeException("Cannot initialize JavaBean class and constructor", e);
            }
        }

        @Override
        public Integer call() throws Exception {
            int counter = 31;
            for (int i = 0; i < ITERATIONS; i++) {
                JavaBean bean = constructorCache.newInstance();
                classCache.getMethod("setValue", Integer.TYPE).invoke(bean, i);
                final int value = (Integer) classCache.getMethod("getValue").invoke(bean);
                counter = 37 * counter + value;
            }

            return counter;
        }
    };
</script></pre>
<p>The code should speak for itself. We don't just cache the Class object, but also the Constructor object. Caching only the Constructor in not enough, since we still need the Class to reflectively lookup methods. This wouldn't be necessary if we cache the <a href="http://java.sun.com/javase/6/docs/api/java/lang/reflect/Method.html">Method</a>s. But, for the sake of a fair comparison, both implementations don't cache the methods.</p>
<h3>Running the benchmark</h3>
<p>Let's run it, using the following command:</p>
<pre><script type="syntaxhighlighter" class="brush: plain">
java -jar -server \
    -XX:+TraceClassLoading -XX:+PrintCompilation -XX:+PrintGCDetails \
    -Xms512m -Xmx512m -XX:PermSize=256m -XX:MaxPermSize=256m \
    ReflectionSlow.jar
</script></pre>
<p>In the previous article, I didn't show you the run command, so let's catch up.</p>
<ul>
<li><strong>-jar</strong><br />
Nothing special, I just packaged the benchmark in a JAR to easily transfer it across machines</li>
<li><strong>-server</strong><br />
This option is used to enable the high performance "server" VM. Since Java SE 5, <a href="http://java.sun.com/javase/technologies/hotspot/gc/gc_tuning_6.html#ergonomics">Ergonomics</a> are used to automatically pick an appropriate VM, based on the characteristics of the hardware, OS, etc. We explicitly choose server to make the test more reliable.</li>
<li><strong>-XX:+TraceClassLoading</strong><br />
Output each loaded class to the console. Used to make sure that the test isn't disrupted by class loading, which would skew the results.</li>
<li><strong>-XX:+PrintCompilation</strong><br />
Output a line to the console when a method is compiled by the VM. Used to make sure that the test isn't disrupted by dynamic compilation, which would skew the results.</li>
<li><strong>-XX:+PrintGCDetails</strong><br />
Output a detailled message to the console with each garbage collection run. Used to check that no <a href="http://java.sun.com/javase/technologies/hotspot/gc/gc_tuning_6.html#available_collectors.selecting">major collections</a> occur during a test, which would skew the results.</li>
<li><strong>-Xms512m -Xmx512m -XX:PermSize=256m -XX:MaxPermSize=256m</strong><br />
I purposely set high values to delay any garbage collection, because that could decrease performance on the later runs.</li>
</ul>
<h3>The results</h3>
<p><strong>NOTE: I've changed the benchmark since the previous article and the results presented here aren't comparable with the old ones!</strong></p>
<pre><script type="syntaxhighlighter" class="brush: plain">
Total times:
Total Class = 11282ms
Total Constructor = 12107ms
</script></pre>
<p>Hey, that's odd. <a href="http://java.sun.com/javase/6/docs/api/java/lang/reflect/Constructor.html#newInstance%28java.lang.Object...%29">Constructor.newInstance()</a> is more expensive than <a href="http://java.sun.com/javase/6/docs/api/java/lang/Class.html#newInstance%28%29">Class.newInstance()</a>. Strange... (ps. the result is the same on many runs on multiple machines)</p>
<h3>Fixing the problem</h3>
<p>But... Constructor.newInstance() is a <a href="http://java.sun.com/j2se/1.5.0/docs/guide/language/varargs.html">varargs</a> method. This means a new array is created when it is invoked. Let's fix this line:</p>
<pre><script type="syntaxhighlighter" class="brush: java">
                JavaBean bean = constructorCache.newInstance();
</script></pre>
<p>into this:</p>
<pre><script type="syntaxhighlighter" class="brush: java; first-line: 16">
                JavaBean bean = constructorCache.newInstance(NULL_ARRAY);
</script></pre>
<p>We also need to put this thingie somewhere:</p>
<pre><script type="syntaxhighlighter" class="brush: java; first-line: 16">
    private static final Object[] NULL_ARRAY = (Object[]) null;
</script></pre>
<p>This way, we pass in our own array, which is null, but this is enough to disable the creation of a new array.</p>
<p><strong>Note that I didn't just pass in a null literal. This would lead to <a href="http://weblogs.java.net/blog/2006/08/10/varargs-puzzler">a compiler warning and makes the code less obvious</a>.</strong></p>
<p>The results:</p>
<pre><script type="syntaxhighlighter" class="brush: plain">
Total times:
Total Class = 11263ms
Total Constructor = 11078ms
</script></pre>
<p>Yeah, now we're faster, but just a little bit.</p>
<h3>Wrapping up</h3>
<p>So, let's combine this with the other optimizations (method caching) and see where we end up:<br />
<em>"Java HotSpot(TM) Server VM (build 10.0-b23, mixed mode)"</em></p>
<pre><script type="syntaxhighlighter" class="brush: plain">
Total times:
Total Normal = 708ms
Total Reflection = 26492ms
Total Class = 11770ms
Total Constructor = 11682ms
Total Constructor And Methods = 1825ms
</script></pre>
<p>(these are the totals of a *lot* of runs)</p>
<p>And, for the fun of it, some OpenJDK results from my little Atom 330 Ubuntu machine: <em>"OpenJDK 64-Bit Server VM (build 14.0-b16, mixed mode)"</em>:</p>
<pre><script type="syntaxhighlighter" class="brush: plain">
Total Normal = 3713ms
Total Reflection = 136662ms
Total Class = 61733ms
Total Constructor = 62293ms
Total Constructor And Methods = 8246ms
</script></pre>
<p>So, invoking Constructor.newInstance(args...) is slightly cheaper than invoking Class.newInstance().</p>
<p>And, Reflection has gotten pretty damn fast if you ask me. <img src='http://blog.smart-java.nl/blog/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p><strong>Don't forget to pass in a null array to prevent the JVM from automagically creating one for you.</strong></p>
<p><strong>Note: Class.newInstance() and Constructor.newInstance() behave differently with regards to Exceptions. See the <a href="http://java.sun.com/javase/6/docs/api/java/lang/Class.html#newInstance%28%29">Class</a> and <a href="http://java.sun.com/javase/6/docs/api/java/lang/reflect/Constructor.html#newInstance%28java.lang.Object...%29">Constructor</a> documentation for details. The only thing I'm gonna say here, is that Constructor is the preferred way.</strong></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.smart-java.nl/blog/index.php/2010/05/01/reflection-slow-class-vs-constructor-newinstance/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Reflection slow? Well, it depends&#8230;</title>
		<link>http://blog.smart-java.nl/blog/index.php/2010/04/25/reflection-slow-well-it-depends/</link>
		<comments>http://blog.smart-java.nl/blog/index.php/2010/04/25/reflection-slow-well-it-depends/#comments</comments>
		<pubDate>Sun, 25 Apr 2010 15:29:30 +0000</pubDate>
		<dc:creator>Jan-Kees van Andel</dc:creator>
				<category><![CDATA[Java API]]></category>
		<category><![CDATA[performance]]></category>
		<category><![CDATA[reflection]]></category>

		<guid isPermaLink="false">http://blog.smart-java.nl/blog/?p=1065</guid>
		<description><![CDATA[In this article, I&#8217;ll show you some ways to turn slow reflective code into faster code.
Reasons to use reflection
As some of you may know, many frameworks and libraries use reflection to do their thing. Reflection can be a solution for many sorts of issues, like:

Configuration. Many frameworks use text-based configuration, like XML. Classes are often [...]]]></description>
			<content:encoded><![CDATA[<p>In this article, I&#8217;ll show you some ways to turn slow reflective code into faster code.</p>
<h3>Reasons to use reflection</h3>
<p>As some of you may know, many frameworks and libraries use reflection to do their thing. Reflection can be a solution for many sorts of issues, like:</p>
<ul>
<li>Configuration. Many frameworks use text-based configuration, like XML. Classes are often configured in text files and need to be instantiated at some point. Also, method names (like event handlers or callbacks) might be configured in text files.</li>
<li>Frameworks in general. Whether you configure your classes in an external text file, annotations or some kind of <a href="http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/new-in-3.html#new-java-configuration">Java config</a>, the framework can never know the classes it invokes. This framework therefore almost always needs to invoke <a href="http://java.sun.com/javase/6/docs/api/java/lang/Class.html#newInstance%28%29">Class.newInstance()</a> or something similar (<a href="http://java.sun.com/javase/6/docs/api/java/lang/reflect/Constructor.html#newInstance%28java.lang.Object...%29">Constructor.newInstance() is actually better</a>) to invoke the application classes. And, if you don&#8217;t want to put any restrictions on the application code, like requiring application classes to implement a predefined interface, you definitely need to use reflection to invoke methods and access fields.</li>
<li>Backwards compatibility. For example, the <a href="http://svn.apache.org/repos/asf/myfaces/core/trunk/api/src/main/java/javax/faces/validator/BeanValidator.java">BeanValidator in MyFaces</a> needs to behave in two different ways, depending on the available libraries. It uses the method <a href="http://java.sun.com/javaee/6/docs/api/javax/el/ValueExpression.html#getValueReference%28javax.el.ELContext%29">ValueExpression.getValueReference()</a>, but only if it is available (available since Unified EL 2.2). Otherwise, it uses a home-brewn mechanism. Reflection is needed, both for compile and at runtime. Otherwise, the code will throw a NoSuchMethodError when ValueExpression.getValueReference() is not available. Reflection is the way to determine method-existence on classes.</li>
<li>Tooling, or other kinds of code that need to inspect classes at runtime.</li>
<li>Simple class modifications, like making private methods accessible. OR-Mappers like Hibernate do this <a href="http://docs.jboss.org/hibernate/core/3.3/reference/en/html/mapping.html#mapping-declaration-property">for field access</a>, since fields are usually private.</li>
<li>Non-Java templating engines, like <a href="http://freemarker.sourceforge.net/">FreeMarker</a> or <a href="http://andyschwartz.wordpress.com/2009/07/31/whats-new-in-jsf-2/#facelets">Facelets</a>. Since templates are not Java bytecode, they rely on reflection to access Java stuff.</li>
</ul>
<h3>Reflection in JSF</h3>
<p>As you may know, JSF also uses reflection a lot. <a href="http://www.oracle.com/technology/tech/java/newsletter/articles/jsf_pojo/index.html">Managed Beans</a>, unlike i.e. <a href="http://struts.apache.org/1.x/struts-core/apidocs/org/apache/struts/action/Action.html">Struts Actions</a>, don&#8217;t have a specific interface, but (mostly) follow the JavaBean convention. This requires the framework to use reflection a lot, for example while resolving EL expressions to method calls.</p>
<p>Unfortunately, <a href="http://www.google.nl/search?q=java+reflection+is+slow">reflection is slow</a>. Note that I&#8217;m talking about nanoseconds per invocation here. Few reflective invocations in a single web request is nothing to be afraid about, especially compared to database and network latency. But, resolving expressions is a heavily used operation in any JSF request.</p>
<p>Profiling also shows that a significant portion of a JSF application is spent on reflection.</p>
<p>I say, time to improve this. But first, we need measurements to see what the problem is.</p>
<h3>Reflection performance, the test setup</h3>
<p>So, reflection is slow, right? What does slow really mean and how slow is it?</p>
<p>Let&#8217;s start with a simple, but typical, example of how reflection is used in most frameworks.</p>
<p>Consider a simple JavaBean:</p>
<pre><script type="syntaxhighlighter" class="brush: java">
public class JavaBean {
    private int value;

    public int getValue() {
        return value;
    }

    public void setValue(int value) {
        this.value = value;
    }
}
</script></pre>
<p>A simple JavaBean with a String property. This JavaBean&#8217;s methods are to be invoked by the framework.</p>
<p>Now, let&#8217;s first write a simple program to access it without reflection. Not a single framework invokes application code directly, since it&#8217;s not compiled against it, but this will be our baseline for comparison.</p>
<pre><script type="syntaxhighlighter" class="brush: java">
public class Runner {
    private static final int THREADS = 1000;
    private static final int ITERATIONS = 1000;

    private static final Random random = new Random();

    public static void main(String[] args) throws Exception {
        testConcurrent(NORMAL_ACCESS_TASK, "normal access WARMUP");
        testConcurrent(NORMAL_ACCESS_TASK, "normal access");
    }

    private static void testConcurrent(final Callable<Integer> task, final String name) throws InterruptedException {
        // Omitted for brevity, but this method starts <THREADS> threads
        // which concurrently access the object during <ITERATIONS> iterations.
    }

    private static Callable<Integer> NORMAL_ACCESS_TASK = new Callable<Integer>() {
        @Override
        public Integer call() throws Exception {
            int counter = 31;
            for (int j = 0; j < ITERATIONS; j++) {

// ################# Instantiate and invoke the bean START #################

                final JavaBean bean = new JavaBean();
                bean.setValue(j);
                final int value = bean.getValue();

// ################## Instantiate and invoke the bean END ##################

                counter = 37 * counter + value;
            }

            return counter;
        }
    };
}
</script></pre>
<p>A reliable concurrent test harness requires a lot of boilerplate code, but the essence is between the two comments. It invokes the bean methods in a plain Java way.</p>
<p>On my laptop, with 1000 threads and 1000 iterations, it takes 68ms to complete.</p>
<h3>Measuring reflection performance</h3>
<p>Now, let's try it out using reflection. After all, not a single framework is compiled against the application code, so the method above is the ideal, but impossible.</p>
<p>We add the following task to the test harness:</p>
<pre><script type="syntaxhighlighter" class="brush: java">
    private static Callable<Integer> REFLECTION_ACCESS_TASK = new Callable<Integer>() {
        @Override
        public Integer call() throws Exception {
            int counter = 31;
            for (int i = 0; i < ITERATIONS; i++) {
                final Class<JavaBean> clazz = (Class<JavaBean>) Class.forName("nl.jkva.asm.JavaBean");
                JavaBean bean = clazz.newInstance();
                clazz.getMethod("setValue", Integer.TYPE).invoke(bean, i);
                final int value = (Integer) clazz.getMethod("getValue").invoke(bean);
                counter = 31 * counter + value;
            }

            return counter;
        }
    };
</script></pre>
<p>This code should look pretty familiar. It loads a class, given its name, instantiates it and invokes its methods, all using the standard Reflection API.</p>
<p>Don't mind the arithmetic stuff. It's used to prevent the JIT from removing too much (dead) code, which would render the test case useless.</p>
<p>Let's include it in the test, so the main method looks like this:</p>
<pre><script type="syntaxhighlighter" class="brush: java">
    public static void main(String[] args) throws Exception {
        testConcurrent(NORMAL_ACCESS_TASK, "normal access WARMUP");
        testConcurrent(NORMAL_ACCESS_TASK, "normal access");

        testConcurrent(REFLECTION_ACCESS_TASK, "reflection access WARMUP");
        testConcurrent(REFLECTION_ACCESS_TASK, "reflection access");
    }
</script></pre>
<p>The results are obvious:</p>
<pre><script type="syntaxhighlighter" class="brush: plain">
  - normal access WARMUP: time = 72ms, counter = 218579914 
  - normal access: time = 68ms, counter = 218579458 
  - reflection access WARMUP: time = 4602ms, counter = 218579743 
  - reflection access: time = 3307ms, counter = 218579280 
</script></pre>
<p>So, full blown reflection is about 50 times slower. Not good, right? Let's try to improve this.</p>
<h3>Optimizing reflective code: Caching classes</h3>
<p>But, of course we can do better. Let's tune the reflective approach a bit.</p>
<p>The first optimization is caching the Class object. Classes are thread safe and can be cached and reused safely.</p>
<p>Caching a Class object saves a <a href="http://java.sun.com/javase/6/docs/api/java/lang/Class.html#forName%28java.lang.String%29">lot of repeated overhead</a>, like contacting the SecurityManager, ClassLoader, etc. So this should be a significant improvement.</p>
<p>The code looks like this:</p>
<pre><script type="syntaxhighlighter" class="brush: java">
    private static Callable<Integer> CACHED_CLASS_REFLECTION_ACCESS_TASK = new Callable<Integer>() {
        private final Class<JavaBean> classCache = loadClass();

        private Class<JavaBean> loadClass() {
            try {
                return (Class<JavaBean>) Class.forName("nl.jkva.asm.JavaBean");
            } catch (ClassNotFoundException e) {
                throw new RuntimeException("Cannot initialize JavaBean", e);
            }
        }

        @Override
        public Integer call() throws Exception {
            int counter = 31;
            for (int i = 0; i < ITERATIONS; i++) {
                JavaBean bean = classCache.newInstance();
                classCache.getMethod("setValue", Integer.TYPE).invoke(bean, i);
                final int value = (Integer) classCache.getMethod("getValue").invoke(bean);
                counter = 37 * counter + value;
            }

            return counter;
        }
    };
</script></pre>
<p>And we of course add the task to the test.<br />
Performance got better with about 40%</p>
<pre><script type="syntaxhighlighter" class="brush: plain">
  - normal access WARMUP: time = 72ms, counter = 218579914 
  - normal access: time = 68ms, counter = 218579458 
  - reflection access WARMUP: time = 4602ms, counter = 218579743 
  - reflection access: time = 3307ms, counter = 218579280 
  - reflection access (cached class) WARMUP: time = 1956ms, counter = 218579659 
  - reflection access (cached class): time = 1917ms, counter = 218579628 
</script></pre>
<p>So, we can safely conclude that in general, it's a good idea to cache Class instances if you plan to instantiate them a lot. Don't cache too much, because such loitering objects are the number one reason of Java memory leaks. But, a "Map&lt;String, Class&gt;" with a fixed amount of classes (like all your controllers) should do no harm here.</p>
<h3>Optimizing reflective code: Caching method handles</h3>
<p>There is more reflective code that can be optimized. The Method instances are also good candidates for caching. After all, you obtain the same <a href="http://java.sun.com/javase/6/docs/api/java/lang/reflect/Method.html#invoke%28java.lang.Object,%20java.lang.Object...%29">Method</a> handle every time and invoke it with an instance parameter. So, let's cache the getter and setter methods, like this:</p>
<pre><script type="syntaxhighlighter" class="brush: java">
    private static Callable<Integer> CACHED_CLASS_AND_METHODS_REFLECTION_ACCESS_TASK = new Callable<Integer>() {
        private final Class<JavaBean> classCache = loadClass();
        private final Method getterCache = loadGetter();
        private final Method setterCache = loadSetter();

        private Method loadGetter() {
            try {
                return classCache.getMethod("getValue");
            } catch (NoSuchMethodException e) {
                throw new RuntimeException("Cannot get getter method handle", e);
            }
        }

        private Method loadSetter() {
            try {
                return classCache.getMethod("setValue", Integer.TYPE);
            } catch (NoSuchMethodException e) {
                throw new RuntimeException("Cannot get setter method handle", e);
            }
        }

        private Class<JavaBean> loadClass() {
            try {
                return (Class<JavaBean>) Class.forName("nl.jkva.asm.JavaBean");
            } catch (ClassNotFoundException e) {
                throw new RuntimeException("Cannot initialize JavaBean", e);
            }
        }

        @Override
        public Integer call() throws Exception {
            int counter = 31;
            for (int i = 0; i < ITERATIONS; i++) {
                JavaBean bean = classCache.newInstance();
                setterCache.invoke(bean, i);
                final int value = (Integer) getterCache.invoke(bean);
                counter = 37 * counter + value;
            }

            return counter;
        }
    };
</script></pre>
<p>The code is getting a lot messier with every tweak, but don't worry. There are other, more concise ways to do this. I chose this approach because of testability (<a href="http://www.ibm.com/developerworks/java/library/j-jtp02225.html">writing a correct concurrent test is hard</a>).</p>
<p>The results, however, don't lie:</p>
<pre><script type="syntaxhighlighter" class="brush: plain">
  - normal access WARMUP: time = 123ms, counter = 218578998 
  - normal access: time = 63ms, counter = 218579569 
  - reflection access WARMUP: time = 4711ms, counter = 218579400 
  - reflection access: time = 3001ms, counter = 218579313 
  - reflection access (cached class) WARMUP: time = 2214ms, counter = 218579055 
  - reflection access (cached class): time = 2067ms, counter = 218579560 
  - reflection access (cached class+methods) WARMUP: time = 466ms, counter = 218579101 
  - reflection access (cached class+methods): time = 537ms, counter = 218579916 
</script></pre>
<p>Caching the two methods improves performance with about 400%. But we have two methods, so let's conclude a 200% improvement per method.</p>
<p>At this point, we've performance has improved about ten times, compared to the original reflection implementation. But, even this optimized version is still about 6 to 10 times slower than the original one.</p>
<p>Unfortunately, using standard reflection, we can't make much more improvements. The JIT simply has less ways to optimize reflective invocations than it has with normal bytecode (<a href="http://openjdk.java.net/projects/mlvm/subprojects.html#InvokeDynamic">invokedynamic in JDK 7 improves this</a>).</p>
<h3>Optimizing reflective code: Caching instances</h3>
<p><b>This optimization is only applicable to stateless objects! Using it on objects with state leads to correctness problems!</b></p>
<p>Let's assume that correctness is irrelevant so we can cache instances of the bean. The code would look like this:</p>
<pre><script type="syntaxhighlighter" class="brush: java">
    private static Callable<Integer> CACHED_CLASS_AND_METHODS_AND_INSTANCE_REFLECTION_ACCESS_TASK = new Callable<Integer>() {
        private final Class<JavaBean> classCache = loadClass();
        private final Method getterCache = loadGetter();
        private final Method setterCache = loadSetter();
        private final JavaBean instanceCache = loadInstance();

        private JavaBean loadInstance() {
            try {
                return classCache.newInstance();
            } catch (Exception e) {
                throw new RuntimeException("Cannot get instance", e);
            }
        }

        private Method loadGetter() {
            try {
                return classCache.getMethod("getValue");
            } catch (NoSuchMethodException e) {
                throw new RuntimeException("Cannot get getter method handle", e);
            }
        }

        private Method loadSetter() {
            try {
                return classCache.getMethod("setValue", Integer.TYPE);
            } catch (NoSuchMethodException e) {
                throw new RuntimeException("Cannot get setter method handle", e);
            }
        }

        private Class<JavaBean> loadClass() {
            try {
                return (Class<JavaBean>) Class.forName("nl.jkva.asm.JavaBean");
            } catch (ClassNotFoundException e) {
                throw new RuntimeException("Cannot initialize JavaBean", e);
            }
        }

        @Override
        public Integer call() throws Exception {
            int counter = 31;
            for (int i = 0; i < ITERATIONS; i++) {
                setterCache.invoke(instanceCache, i);
                final int value = (Integer) getterCache.invoke(instanceCache);
                counter = 37 * counter + value;
            }

            return counter;
        }
    };
</script></pre>
<p>And the results:</p>
<pre><script type="syntaxhighlighter" class="brush: plain">
  - normal access WARMUP: time = 120ms, counter = 218579735 
  - normal access: time = 70ms, counter = 218579495 
  - reflection access WARMUP: time = 3902ms, counter = 218579662 
  - reflection access: time = 3001ms, counter = 218579761 
  - reflection access (cached class) WARMUP: time = 1897ms, counter = 218579863 
  - reflection access (cached class): time = 1910ms, counter = 218579251 
  - reflection access (cached class+methods) WARMUP: time = 440ms, counter = 218579665 
  - reflection access (cached class+methods): time = 426ms, counter = 218578955 
  - reflection access (cached class+methods+instance) WARMUP: time = 370ms, counter = 1124350138 
  - reflection access (cached class+methods+instance): time = 247ms, counter = 1268925652 
</script></pre>
<p>So, we've won about 100-200ms by not invoking the newInstance method. But, since creating objects also affects garbage collection (in this test we create one million beans per test) and we've refactored the local variable to a static final variable the performance implications of the newInstance call itself are not obvious. But, it's a fact that we've improved performance by caching the instance.</p>
<p>But note, this approach only applies to stateless or immutable objects. Wherever there's state, you need new instances.</p>
<h3>Optimizing reflective code: Conclusion</h3>
<p>In this article, we've seen how the performance of reflection differs from 'normal' Java bytecode performance.</p>
<p>We've also seen how some simple tweaks like caching Class and Method objects make reflective code a lot faster.</p>
<p>But still, even when caching instances, the performance of reflection doesn't even come close to the performance of plain Java bytecode (where the instances weren't cached).</p>
<p>There are examples of high performance reflection, for example in the <a href="http://java.sun.com/javase/6/docs/api/java/util/concurrent/atomic/AtomicReferenceFieldUpdater.html">java.util.concurrent.atomic.AtomicReferenceFieldUpdater class</a>, but this kind of code should not be written by anyone except <a href="http://g.oswego.edu/">Doug Lea</a>. <img src='http://blog.smart-java.nl/blog/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  (and b.t.w., it hurts portability)</p>
<p>So, should you use reflection in your application? It depends. If you're writing high performance stuff that's invoked very, very often, I would say no. If you're writing a simple method dispatcher that gets invoked once per web request in a normal web application, I wouldn't care about the performance of the reflective invocation. After all, we're still talking about nano-/milliseconds here.</p>
<p>In the next entry, I'll show you how you can use <a href="http://asm.ow2.org/">bytecode enhancement</a> to get the same functionality as with reflection, but without a huge performance penalty.</p>
<p><b>Edit</b><br />
Note: I just heard that in some cases, HotSpot is able to inline through reflection calls, enabling it to apply all it's JIT tricks on it, effectively reducing the invocation cost to zero! But it only works if it can prove if the invoked method is always the same, which is not always true unfortunately.<br />
<a href="http://java.sun.com/products/hotspot/whitepaper.html#performance">http://java.sun.com/products/hotspot/whitepaper.html#performance</a></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.smart-java.nl/blog/index.php/2010/04/25/reflection-slow-well-it-depends/feed/</wfw:commentRss>
		<slash:comments>14</slash:comments>
		</item>
		<item>
		<title>Unit Testing a Bean Validation ConstraintValidator</title>
		<link>http://blog.smart-java.nl/blog/index.php/2010/03/12/unit-testing-a-bean-validation-constraintvalidator/</link>
		<comments>http://blog.smart-java.nl/blog/index.php/2010/03/12/unit-testing-a-bean-validation-constraintvalidator/#comments</comments>
		<pubDate>Fri, 12 Mar 2010 15:27:16 +0000</pubDate>
		<dc:creator>Jan-Kees van Andel</dc:creator>
				<category><![CDATA[Java API]]></category>
		<category><![CDATA[Java EE]]></category>
		<category><![CDATA[Java language]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[annotations]]></category>
		<category><![CDATA[bean validation]]></category>
		<category><![CDATA[ConstraintValidator]]></category>
		<category><![CDATA[Dynamic Proxies]]></category>
		<category><![CDATA[JUnit]]></category>
		<category><![CDATA[Mockito]]></category>
		<category><![CDATA[unit testing]]></category>

		<guid isPermaLink="false">http://blog.smart-java.nl/blog/?p=976</guid>
		<description><![CDATA[I&#8217;ve been playing a bit with Bean Validation and thought I found an issue: Unit testing a ConstraintValidator. Specifically, parametrized ConstraintValidators.
First, what&#8217;s a parametrized ConstraintValidator? Simple, a Validator that takes a parameter to do its job. A simple example is a length validator that takes the minimum and maximum length as parameters and validates if [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve been playing a bit with Bean Validation and thought I found an issue: Unit testing a ConstraintValidator. Specifically, parametrized ConstraintValidators.</p>
<p>First, what&#8217;s a parametrized ConstraintValidator? Simple, a Validator that takes a parameter to do its job. A simple example is a length validator that takes the minimum and maximum length as parameters and validates if the value is between those two.</p>
<p>Parametrized ConstraintValidators are everywhere, even Bean Validation itself contains them. For example: @Min(length) and @Max(length), but also normal ConstraintValidators, like @NotNull where you can customize the error message. However, this error message parameter is not very interesting with regards to unit testing individual ConstraintValidators, because the message is generated by the Bean Validation framework.</p>
<p>For example, consider this ConstraintValidator, incl. corresponding annotation:</p>
<pre><script type="syntaxhighlighter" class="brush: java">
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Constraint(validatedBy = CreditCardExpiryYearValidator.class)
public @interface CreditCardExpiryYear {
    int expirationInYears() default 10;
    String message() default "{validation.CreditCardExpiryYear.message}";
}

public class CreditCardExpiryYearValidator implements ConstraintValidator&lt;CreditCardExpiryYear, Integer&gt; {
    private volatile int expirationInYears;
    public void initialize(CreditCardExpiryYear constraint) {
        this.expirationInYears = constraint.expirationInYears();
    }

    public boolean isValid(Integer year, ConstraintValidatorContext context) {
        final int nowYear = Calendar.getInstance().get(Calendar.YEAR);
        return year != null
            &amp;&amp; year &lt; nowYear + expirationInYears;
    }
}
</script></pre>
<p>In the future, Bean Validation may become the core mechanism for ensuring correctness in your system. For example, JPA 2.0 leverages Bean Validation annotations to generate additional DDL statements and JSF 2.0 automatically uses Bean Validation when it&#8217;s available. Note: JSF 2.0 uses a new concept, called &#8220;default validators&#8221; to implement this. A default validator is invoked on every input component on a postback.</p>
<p>But, how do we test this stuff? After all, you can&#8217;t instantiate an annotation.</p>
<p>I currently have 4 options:</p>
<ul>
<li><a href="#reflection">Using reflection to use a declared annotation</a></li>
<li><a href="#implementation">Custom annotation implementation</a></li>
<li><a href="#dynamic_proxies">Dynamic proxies</a></li>
<li><a href="#mockito">Mocking, for example using Mockito</a></li>
</ul>
<p><b><a name="reflection">Using a declared annotation</a></b><br />
The first attempt is shown below. Here, I simply declare the annotation in my test case on a dummy instance field (an annotation doesn&#8217;t live on its own) and look it up using reflection. This way, Java takes care of instantiating and initializing the annotation.</p>
<pre><script type="syntaxhighlighter" class="brush: java">
public class CreditCardExpiryYearValidatorTest {

    @CreditCardExpiryYear(expirationInYears = 5)
    int expiryAfter5Years;

    @CreditCardExpiryYear
    int expiryAfter10Years;

    private int currentYear;

    @Before
    public void setUp() throws Exception {
        currentYear = Calendar.getInstance().get(Calendar.YEAR);
    }

    @Test
    public void testIsValid_DefaultExpiration() throws Exception {
        CreditCardExpiryYearValidator val = new CreditCardExpiryYearValidator();
        val.initialize(getFieldAnnotation(this, "expiryAfter10Years", CreditCardExpiryYear.class));

        boolean b = val.isValid(currentYear + 5, null);

        assertTrue(b);
    }

    @Test
    public void testIsValid_Configure5Years() throws Exception {
        CreditCardExpiryYearValidator val = new CreditCardExpiryYearValidator();
        val.initialize(getFieldAnnotation(this, "expiryAfter5Years", CreditCardExpiryYear.class));

        boolean b = val.isValid(currentYear + 6, null);

        assertFalse(b);
    }
}
</script></pre>
<p>I personally quite like this approach. The test data is inside the test case. Unfortunately not in the test method, that would be better, but since you can&#8217;t put annotations everywhere in your code, it&#8217;s not easy to implement this decently.</p>
<p>So let&#8217;s look at the next one&#8230;</p>
<p><b><a name="implementation">Custom annotation implementation</a></b><br />
Since Java annotations are just a special case of interfaces, they should be fairly straightforward to implement. However, for some reason, I didn&#8217;t know this until recently. But it&#8217;s actually not different from any other interface implementation. See for yourself.</p>
<pre><script type="syntaxhighlighter" class="brush: java">
public class CreditCardExpiryYearValidatorTest {

    private int currentYear;

    @Before
    public void setUp() throws Exception {
        currentYear = Calendar.getInstance().get(Calendar.YEAR);
    }

    @Test
    public void testIsValid_CustomAnnotationImpl() throws Exception {
        CreditCardExpiryYearValidator val = new CreditCardExpiryYearValidator();
        val.initialize(new CreditCardExpiryYearImpl());

        boolean b = val.isValid(currentYear + 6, null);

        assertFalse(b);
    }
}
class CreditCardExpiryYearImpl implements CreditCardExpiryYear {
    public int expirationInYears() { return 5; }
    public String message() { return "hello"; }
    public Class&lt;? extends Annotation&gt; annotationType() { return CreditCardExpiryYear.class; }
}
</script></pre>
<p>Nothing special, right? But I don&#8217;t really like it. I could have also written it inline, but I don&#8217;t like that either:</p>
<pre><script type="syntaxhighlighter" class="brush: java">
@Test
public void testIsValid_CustomAnnotationImplInline() throws Exception {
    CreditCardExpiryYearValidator val = new CreditCardExpiryYearValidator();
    val.initialize(new CreditCardExpiryYear() {
        public Class&lt;? extends Annotation&gt; annotationType() { return CreditCardExpiryYear.class; }
        public String message() { return ""; }
        public int expirationInYears() { return 5; }
    });

    boolean b = val.isValid(currentYear + 6, null);

    assertFalse(b);
}
</script></pre>
<p>I think the above one looks like garbage. So this is also a no-go.</p>
<p><b><a name="dynamic_proxies">Dynamic proxies</a></b><br />
Java itself uses dynamic proxies at runtime to instantiate annotations. So why not also use a Proxy to mock the annotation? See for yourself. </p>
<pre><script type="syntaxhighlighter" class="brush: java">
@Test
public void testIsValid_DynamicProxy() throws Exception {
    CreditCardExpiryYearValidator val = new CreditCardExpiryYearValidator();
    CreditCardExpiryYear annotation = (CreditCardExpiryYear)
            Proxy.newProxyInstance(
                    this.getClass().getClassLoader(),
                    new Class&lt;?&gt;[] { CreditCardExpiryYear.class },
                    new InvocationHandler() {
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            return 5;
        }
    });
    val.initialize(new CreditCardExpiryYearImpl());
    boolean b = val.isValid(currentYear + 6, null);

    assertFalse(b);
}
</script></pre>
<p>However inline, the implementation looks very clumsy. Unfortunately this is probably as simple as it can get, since you DO need to define the inner class.</p>
<p>And it will become even worse when there are multiple parameters on the bean, since you need to check which method is invoked. This will make the implementation even worse.</p>
<p><b><a name="mockito">Mocking using Mockito</a></b><br />
But, creating and configuring proxies, isn&#8217;t this what mocking libraries do? Exactly, let&#8217;s try.</p>
<pre><script type="syntaxhighlighter" class="brush: java">
@Test
public void testIsValid_Mockito() throws Exception {
    CreditCardExpiryYearValidator val = new CreditCardExpiryYearValidator();
    CreditCardExpiryYear annotation = mock(CreditCardExpiryYear.class);
    when(annotation.expirationInYears()).thenReturn(5);

    val.initialize(annotation);
    boolean b = val.isValid(currentYear + 6, null);

    assertFalse(b);
}
</script></pre>
<p>This looks pretty nice. And it scales well with multiple attributes.</p>
<p>I only doubt it will be the nicest solution when the annotations become more complex. I really don&#8217;t like annotations that contain annotation parameters. Or even worse, arrays of annotation parameters. But reality is, they exist. And if they exist, they also need to be tested. But, OTOH, people who nest annotations probably don&#8217;t mind unreadable unit tests. <img src='http://blog.smart-java.nl/blog/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://blog.smart-java.nl/blog/index.php/2010/03/12/unit-testing-a-bean-validation-constraintvalidator/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Hibernate, lazy loading and inheritance</title>
		<link>http://blog.smart-java.nl/blog/index.php/2010/03/08/hibernate-lazy-loading-and-inheritance/</link>
		<comments>http://blog.smart-java.nl/blog/index.php/2010/03/08/hibernate-lazy-loading-and-inheritance/#comments</comments>
		<pubDate>Mon, 08 Mar 2010 12:35:15 +0000</pubDate>
		<dc:creator>gnoij</dc:creator>
				<category><![CDATA[Algemeen]]></category>
		<category><![CDATA[Java API]]></category>
		<category><![CDATA[Object Relational Mapping]]></category>
		<category><![CDATA[ClassCastException]]></category>
		<category><![CDATA[Hibernate]]></category>
		<category><![CDATA[lazy loading]]></category>

		<guid isPermaLink="false">http://blog.smart-java.nl/blog/?p=956</guid>
		<description><![CDATA[A common problem with typecasting a lazy loaded entity to its child is a ClassCastException. This exception occurs because the dynamic created proxy implements the baseclass and has no knowledge about its subclasses.
Suppose we have a class B which extends A and a class C which has class A as a member as shown below.

public [...]]]></description>
			<content:encoded><![CDATA[<p>A common problem with typecasting a lazy loaded entity to its child is a <em>ClassCastException</em>. This exception occurs because the dynamic created proxy implements the baseclass and has no knowledge about its subclasses.</p>
<p>Suppose we have a class <em>B</em> which extends <em>A</em> and a class <em>C</em> which has class <em>A</em> as a member as shown below.</p>
<pre><script type="syntaxhighlighter" class="brush: java">
public class A {

    private Long id;

    private String name;

    public String getName() { return name; }

    public void setName(String name) { this.name = name; }

    public Long getId() { return id; }
}

public class B extends A {

    private String somethingElse;

    public String getSomethingElse() { return somethingElse; }

    public void setSomethingElse(String something) { this.somethingElse = something; }

}

public class C {

    private Long id;

    private A a;

    public A getA() { return a; }

    public void setA(A a) { this.a = a; }

    public Long getId() { return id; }
}
</script></pre>
<p>The following test will fail with a<em> ClassCastException</em> on the last line.</p>
<pre><script type="syntaxhighlighter" class="brush: java">public void testClassCastException() {

	B b = new B();
	b.setName("B");
	b.setSomethingElse("test");

	C c = new C();
	c.setA(b);

	save(c);
	// just for testing purposes we clear the session, so
	// c is actually loaded from the database
	clearSession(); 

	c = retrieve(C.class, c.getId());
	b = (B) c.getA();
}
</script></pre>
<p><em> The methods save(), clearSession() and retrieve() are just helper methods which implement the Hibernate session methods save(), clear() and get().</em></p>
<p>A search on the Internet shows a couple of solutions for this problem.</p>
<ol>
<li><a href="http://sysin.wordpress.com/2009/02/27/hibernate-inheritance-classcastexception-part-1/">Using interfaces as a proxy in the hibernate mappings</a>. This will result in accessing the object through its interface only so all methods must be exposed in the interface. I don&#8217;t want to expose every public or protected method in the interface which are not intended for use by external parties.</li>
<li><a href="https://www.hibernate.org/280.html">Using the Visitor Pattern to access the correct childclass</a>. This means that users of these objects must write a lot of code just to use some getters. I don&#8217;t want to burden someone else with a local Hibernate problem.</li>
<li>Using <em>((HibernateProxy)object).getHibernateLazyInitializer().getImplementation()</em> whenever a typecast of an object to its child class is needed.</li>
</ol>
<p>All of the solutions mentioned above are not suitable for me so I decided on another solution which is a variant of solution 3.</p>
<p>With a slight modification of the method <em>getA()</em> in class <em>C</em>, exposing the <em>HibernateProxy</em> is avoided.</p>
<pre><script type="syntaxhighlighter" class="brush: java">
    public A getA() { return deProxy(a); }

    protected  <T extends Object> T deProxy(T object) {
        if (object instanceof HibernateProxy) {
            return (T)((HibernateProxy)object).getHibernateLazyInitializer().getImplementation();
        }
        return object;
    }
</script></pre>
<p>Now the test completes without failure.</p>
<p>This has to be done for every getter which can return a lazy loaded proxy.</p>
<p>And if you (like me) don&#8217;t want Hibernate code in your domain model, you can move this code to the persistence layer and use dependency injection to use it.</p>
<p>It&#8217;s still not an elegant solution (IMHO there isn&#8217;t one), but its the best usable for me.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.smart-java.nl/blog/index.php/2010/03/08/hibernate-lazy-loading-and-inheritance/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>java.util.Calendar.getActualMaximum returns strange results</title>
		<link>http://blog.smart-java.nl/blog/index.php/2010/01/20/java-util-calendar-getactualmaximum-returns-strange-results/</link>
		<comments>http://blog.smart-java.nl/blog/index.php/2010/01/20/java-util-calendar-getactualmaximum-returns-strange-results/#comments</comments>
		<pubDate>Wed, 20 Jan 2010 15:55:15 +0000</pubDate>
		<dc:creator>Peter Schuler</dc:creator>
				<category><![CDATA[Java API]]></category>
		<category><![CDATA[Java language]]></category>
		<category><![CDATA[Bug]]></category>
		<category><![CDATA[Calendar]]></category>

		<guid isPermaLink="false">http://blog.smart-java.nl/blog/?p=643</guid>
		<description><![CDATA[At the end of last year I encountered something odd in the java.util.Calendar. Now is odd behavior nothing to be surprised of in the Java Calendar but this particular oddness was really hard to spot.
I will therefore share it with you.
The code
Let&#8217;s first look a some code dealing with getting the last day of the [...]]]></description>
			<content:encoded><![CDATA[<p>At the end of last year I encountered something odd in the java.util.Calendar. Now is odd behavior nothing to be surprised of in the Java Calendar but this particular oddness was really hard to spot.</p>
<p>I will therefore share it with you.</p>
<p><strong>The code</strong></p>
<p>Let&#8217;s first look a some code dealing with getting the last day of the month:</p>
<pre class="brush:java">public class CalendarTest {
  public static void main(String[] args) {
    Calendar c = Calendar.getInstance();
    c.set(Calendar.MONTH, Calendar.FEBRUARY);
    int maxDayOfMonth = c.getActualMaximum(Calendar.DAY_OF_MONTH);

    System.out.println("last day of month = " + maxDayOfMonth);
  }
}</pre>
<p>Please read the java doc for <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/util/Calendar.html#getActualMaximum(int)">Calendar.getActualMaximum()</a>:</p>
<blockquote><p>Returns the maximum value that the specified calendar field could have, given the time value of this Calendar. For example, the actual maximum value of the MONTH field is 12 in some years, and 13 in other years in the Hebrew calendar system.</p></blockquote>
<p>So the code above can print two different values right &#8230;? 28 or 29 depending on the whether this year is a leap year. As you could have guessed that is another unexpected possibility. I can also print 31. Yes&#8230; really.</p>
<p>I all depends on the date on which this code is executed.</p>
<p>The problem is that Calendar.getInstance() will return a Calendar filled with the current date/time. Let&#8217;s assume the above code runs on the last day of January. The call to getInstance() will return 31-01-2009. The next step puts the month to February. This will result in a overflow as 31-02-2009 is invalid. Because of this Calendar will move the date to 3-03-2000. And March has 31 days.</p>
<p>There is a <a href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4452473">bug report (status: Closed, Not a Defect</a>) in the SDN which told me that the observed behavior was correct. I was not the <a href="http://forums.sun.com/thread.jspa?threadID=5422080">first</a> person surprised by this and I&#8217;m guessing I will not be the last.</p>
<p>I was &#8230;</p>
<ol>
<li>&#8230; lucky I wrote a decent unit test.</li>
<li>&#8230; lucky to be running said unit test om 31 December.</li>
<li>&#8230; unlucky for having to work on the last day of the year.</li>
</ol>
<p>Otherwise the bug I created would properly have slipped through the QA cycles and would have ended up in production. There it would only be visible on the last three days of every month if someone would specify a date in February.</p>
<p><strong>What about lenient?</strong><br />
The Calendar.setLenient function does protect against invalid input. Let&#8217;s quote the the <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/util/Calendar.html#setLenient(boolean)">Calendar java doc</a> about Leniency:</p>
<blockquote><p><strong>Leniency</strong><br />
Calendar has two modes for interpreting the calendar fields, lenient and non-lenient. When a Calendar is in lenient mode, it accepts a wider range of calendar field values than it produces. When a Calendar recomputes calendar field values for return by get(), all of the calendar fields are normalized. For example, a lenient GregorianCalendar interprets MONTH == JANUARY, DAY_OF_MONTH == 32 as February 1.</p>
<p>When a Calendar is in non-lenient mode, it throws an exception if there is any inconsistency in its calendar fields. For example, a GregorianCalendar always produces DAY_OF_MONTH values between 1 and the length of the month. A non-lenient GregorianCalendar throws an exception upon calculating its time or calendar field values if any out-of-range field value has been set.</p></blockquote>
<p>So lenient does protect against the programmer/user creating a invalid date in a way that the following code will result in an exception:</p>
<pre class="brush:java">    Calendar c = Calendar.getInstance();
    c.setLenient(false);
    c.set(Calendar.MONTH, Calendar.FEBRUARY);
    c.set(Calendar.DAY_OF_MONTH, 31);
    System.out.println(c.getTime());</pre>
<p>But the exception is only thrown when c.getTime() is called. Calls to getActualMaximum() still work and return 31. So lenient is not useful here.</p>
<p><strong>Lessons learned</strong></p>
<p>The quick fix for this problem is to set the DAY_OF_MONTH to 1 (or any number between 1 and 28) <strong>before</strong> setting the month.</p>
<p>I also learned that Calendar.setLenient() will not protect you from this error. It will only stop you from getting an invalid Date. It does not protect against overflows.</p>
<p><strong>Sould I use JODA time?</strong></p>
<p>At the end of this post I have a question for you. I have no experience with JODA time always preferring to use the standard Date/Time API unless there was a problem. But perhaps I should reverse my views and use JODA time unless I&#8217;m not allowed too? What do you think &#8230; is it time to stop  using the default Calendar API and use JODA time instead? Or should I wait for Java 7 with <a href="http://jcp.org/en/jsr/detail?id=310">JSR 310</a>?</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.smart-java.nl/blog/index.php/2010/01/20/java-util-calendar-getactualmaximum-returns-strange-results/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>JPA Optimisitic locking versus Pessimistic locking</title>
		<link>http://blog.smart-java.nl/blog/index.php/2010/01/14/jpa-optimisitic-locking-versus-pessimitic-locking/</link>
		<comments>http://blog.smart-java.nl/blog/index.php/2010/01/14/jpa-optimisitic-locking-versus-pessimitic-locking/#comments</comments>
		<pubDate>Thu, 14 Jan 2010 16:18:36 +0000</pubDate>
		<dc:creator>Peter Schuler</dc:creator>
				<category><![CDATA[Algemeen]]></category>
		<category><![CDATA[Java API]]></category>
		<category><![CDATA[Object Relational Mapping]]></category>
		<category><![CDATA[JPA 2.0]]></category>
		<category><![CDATA[ORM]]></category>
		<category><![CDATA[Pessimitic Locking]]></category>
		<category><![CDATA[Versioning]]></category>

		<guid isPermaLink="false">http://blog.smart-java.nl/blog/?p=629</guid>
		<description><![CDATA[As promised in my previous post I will blog some more about JPA and how to use it. In this post I will go into the locking features of JPA 2.0 including the new pessimistic lock options.
This post will:

introduce the new locking features of the JPA;
introduce both pessimistic locking and optimitic locking concepts;
give a quick [...]]]></description>
			<content:encoded><![CDATA[<p>As promised in my <a href="http://blog.smart-java.nl/blog/index.php/2009/12/11/jpa-2-0-finally-final/">previous post</a> I will blog some more about JPA and how to use it. In this post I will go into the locking features of JPA 2.0 including the new pessimistic lock options.</p>
<p>This post will:</p>
<ul>
<li>introduce the new locking features of the JPA;</li>
<li>introduce both pessimistic locking and optimitic locking concepts;</li>
<li>give a quick recap about JPA versioning;</li>
<li>talk about the connection between locking and design;</li>
<li>and finally compare both locking strategies.</li>
</ul>
<p><strong>JPA 2.0 now supports Pessimistic Locking:<br />
</strong></p>
<p>A great omission of JPA 1.0 was the lack of pessimistic locking. Therefore it was necessary to fall back on the support of the underlying implementation to use the JPA is situation where pessimistic locking was required. This can happen when JPA shares a database with another process which does not know or supports versioning based optimistic locking.</p>
<p>JPA 2.0 now supports the following locking modes:</p>
<ul>
<li>OPTIMISTIC                                    (==READ in JPA 1.0)</li>
<li>OPTIMISTIC_FORCE_INCREMENT         (==WRITE in JPA 1.0)</li>
<li>PESSIMISTIC_READ</li>
<li>PESSIMISTIC_WRITE</li>
<li>PESSIMISTIC_FORCE_INCREMENT       (A hybrid of both strategies)</li>
<li>READ                                               (kept around for backward compatibility)</li>
<li>WRITE                                             (kept around for compatibility)</li>
</ul>
<p>Object can be locked by using the find() or refresh() operation of the EntityManager. For example:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">Order order <span style="color: #339933;">=</span> entityManager.<span style="color: #006633;">find</span><span style="color: #009900;">&#40;</span>Order.<span style="color: #000000; font-weight: bold;">class</span>, <span style="color: #cc66cc;">10</span>, LockModeType.<span style="color: #006633;">PESSIMISTIC_READ</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
SELECT ID, PRODUCT, AANTAL, VERSION, orderId FROM ORDER_TABLE WHERE <span style="color: #009900;">&#40;</span>orderId <span style="color: #339933;">=</span> <span style="color: #339933;">?</span><span style="color: #009900;">&#41;</span> <span style="color: #000000; font-weight: bold;">FOR</span> UPDATE.</pre></div></div>

<p>As you can see the FOR UPDATE is added to the select query telling the database to get an exclusive lock on this selected row.</p>
<p>You can also use the lock() method on the entityManager and specify a Lock Mode on Queries (JPQL / Named and Criteria).</p>
<p>Now that we know how to unleash the power of pessimistic locking we need to learn how to use it well.</p>
<p><strong>Locking Strategies: a quick recap….</strong></p>
<p>Locking is a means to prevent data form becoming corrupted because two different processes are editing the same data. If we use locking correctly no two processes can edit (or if required) access the same data. Thus data can never be inconsistent.</p>
<p>As already mentioned there are two locking strategies: optimistic locking and pessimistic locking. I will describe both strategies and give an overview of their pro’s and con’s.</p>
<p><strong>Pessimistic locking</strong></p>
<p>This strategy is the standard locking provided by the database. It will protect data by limiting access to a single process. This is achieved by keeping track of all the currently active locks. If another process wants to access locked data it will have to wait until the other process releases the lock. Of course this introduces a whole range of potential errors like lock timeouts and deadlocks.</p>
<p>This locking strategy is called pessimistic because of the assumption that locking is always necessary to avoid corruption. Based on that assumption it introduces significant overhead in order to keep track of which process is assessing which data. Compare pessimistic locking to a traffic light. It will only allow vehicles to pass when it knows for sure that no one will be in the way.</p>
<p>Using pessimistic locking has some pro’s:</p>
<ul>
<li>The database is in charge and protects your data. Independent from application logic.</li>
<li>A process or thread can only proceed if it has the right locks. Thus it is guaranteed that there will be no conflicts once the lock is acquired.</li>
<li>Processes are put on hold until they can acquire the lock. (This blessing can also be a curse because a process can overwrite data the moment the lock is released. This feels like a missing update but is technically the correct behaviour. But as long as you read and write in the same transction you&#8217;re data is never stale.)</li>
</ul>
<p>No pro’s without con’s:</p>
<ul>
<li>Keeping track of all those locks introduces significant overhead. Even if there is no data being accessed simultaneous the database still locks.</li>
<li>The locking can lead to deadlocks and lock time out. These errors are hard to recover from and take a long time before the calling process is informed.</li>
<li>Must be supported by the database.</li>
</ul>
<p>So pessimistic locking depends on the database restricting access to data. But this comes at high overhead and hard-to-recover errors.</p>
<p><strong>Optimistic locking</strong></p>
<p>As pessimistic locking is embedded in the DBMS, optimistic locking is a strategy that by-passes the database. It will detect conflicts only when they occur. This is done introducing a version number to every table you want to protect. If you read data you will get the version number. If you alter the data you first check the version number again, and when holding the previous read value, update the record and increment the version number. If some one has “changed the data right from under you” you will see a different version number and know that there is a conflict. I will refer to the optimistic lock procedure as check&amp;update.</p>
<p>This strategy is called optimistic because it never bothers to lock. It assumes that process will not bother each other until they do.</p>
<p>Using optimistic locking has some big pro’s:</p>
<ul>
<li>There is no (at least very little) overhead involved in locking.</li>
<li>Optimistic locking is fast and easy to use, especially because it works implicitly. If you specify a @Version the upate&amp;check will be performed automatically.</li>
<li>It’s very efficient.</li>
<li>It is database independent. No special features are required.</li>
</ul>
<p>There are also some drawbacks:</p>
<ul>
<li>It will only detect conflicts, not prevent them. When it occurs it’s the application that must resolve the conflict. For example by showing the user a diff or an option to override the current version in the database.</li>
<li>If a conflict occurs only one process is allowed to proceed. The others have their database transaction rolled back. This is far more expensive than waiting until you get the database lock.</li>
<li>It will only work if everyone accessing the database plays by the versioning rules. The database does not enforce it.</li>
<li>It can be considered ‘unfair’ as the process that writes the data first wins, opposed to the process that first acquired the lock.</li>
<li>Sometimes optimistic locking is not sufficient. Locking a complete table to protect against insert for example.</li>
</ul>
<p>So optimistic locking depends on the calling processes to respect the versioning rules. This makes it possible to detect conflicts and eliminates the need to keep of all the locks and gives Optimistic locking a huge advantage.</p>
<p>However when conflicts occurs it is up to the application to patch things up.</p>
<p><strong>JPA support for optimistic locking</strong></p>
<p>JPA supports optimistic locking based on versioning right from the first release. All you need to do is declare an attribute of your class with a @Version annotation.</p>
<p>For example:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">  @<span style="color: #003399;">Entity</span>
  <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> Order <span style="color: #009900;">&#123;</span>
&nbsp;
      @id @GeneratedValue
      <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #003399;">Integer</span> id<span style="color: #339933;">;</span>
&nbsp;
      @Version
      <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #003399;">Integer</span> version<span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>The above code will result in a Order table with a primary key and version column. JPA will check and update the version after every change to Order.</p>
<p>More on JPA versioning can be found <a href="http://wiki.eclipse.org/EclipseLink/Examples/JPA/Locking">here</a>.</p>
<p><strong>Lock scope.</strong></p>
<p>At first glance versioning seems to be the preferred strategy. It’s easy to use and with little overhead. However there is one more aspect to take into account when dealing with locking. That is what I call ‘the lock scope’.</p>
<p>Versioning will only lock (check&amp;update) records that were changed. Databases will only lock records you tell it to lock by doing a SELECT … FOR UPDATE. Both procedures prevent processes from corrupting the database. But it will not prevent breaking business rules!<br />
Let’s look at the following example:<br />
<a href="http://blog.smart-java.nl/blog/wp-content/uploads/2010/01/Order_OrderLine.png"><img class="size-full wp-image-662 alignnone" title="The order model" src="http://blog.smart-java.nl/blog/wp-content/uploads/2010/01/Order_OrderLine.png" alt="" /></a><br />
This is a typical Order-&gt;OrderLine example. Order has a set of OrderLines which keep a price and quantity for every single item in Order. Let’s assume that there is a business rule that the total amount of money of an Order must stay below $10.000. This is easily achieved by adding a check on order to make sure that every addition/alteration of OrderLines will not break this rule.<br />
A problem occurs when another process comes in and adds OrderLines to an Order at the same time. No single process knows all OrderLines. To make the check work in a concurrent environment you need to make the OrderLine updates in a serial order. In other words: the Order needs to be locked before any additions can be made to OrderLines. This ensures that the business rule can be enforced.</p>
<p>The JPA can achieve this by using one of the two lock levels: OPTIMISTC_FORCE_INCREMENT or PESSIMITC_WRITE. Both will give you a exclusive lock to make sure no other process can edit the same data.</p>
<p>This example illustrates that there are situations in which you need to think ahead about locking. Both versioning and database locks won’t help you out-of-the-box . You need to determine the right lock scope. Determining the lock scope is a business question and needs to be defined based on the functional design and then translated to technical requirements.</p>
<p><strong>Choosing a locking Strategy.</strong></p>
<p>Ok .. now you know about the pro’s and con’s of both locking strategies. You know how to use them technically and you know you need to think about the lock scope. So which strategy is for winners?</p>
<p>As you probably have guessed there is no straightforward answer.</p>
<p>Optimistic locking has little overhead and is easy to use, especially because it works implicitly in JPA. But you need to make sure that everyone using the database uses the same versioning approach. It’s also more expensive in terms of conflict resolving.</p>
<p>Optimistic locking is the preferred strategy if:</p>
<ul>
<li>You’re application has a private database.</li>
<li>All the applications using the database know and use versioning.</li>
<li>It is unlikely that there will be a lot of conflicts. (eg. Users editing the same data.)</li>
</ul>
<p>Pessimistic locking will protect data on the database level. It will prevent conflicts by putting the process in a queue to wait for the lock. If there are a lot of collisions this gives a better change of more processes making it through. However having to keep a large lock administration involves a lot of overhead even if there a no conflicts.</p>
<p>So pessimistic locking it the preferred strategy if:</p>
<ul>
<li>Other non-versionized processes will edit the data you need to lock.</li>
<li>You predict / see that there will be a lot of colissions.</li>
</ul>
<p>For those among us unable to choose, JPA offers a hybrid solution. If you use the lock option PESSIMISTIC_FORCE_INCREMENT both Pessimitic and Optimisic locks are acquired at the same time. Offcourse you&#8217;re cutting of both your hands when using this option for every database call&#8230;. &#8220;Just to be sure .. &#8220;. You&#8217;ll end up with the bad from both locking strategies. But this hybird option can be a life saver when a particular table or operation must be protected at a database level and still has to participate in versionized transactions.</p>
<p><strong>More information on locking</strong></p>
<ul>
<li><a href="http://weblogs.java.net/blog/caroljmcdonald/archive/2009/07/jpa_20_concurre.html">JPA 2.0 Concurrency and locking</a> &#8211; Shows transcipts of most lokcing possibilities.</li>
<li><a href="http://www.avaje.org/occ.html">Explanation of Optimistic Concurrency Checking</a> &#8211; Talks some more about optimisitic locking.</li>
</ul>
<p>And don’t forget to think about the lock scope!</p>
<p>This is the second installment of my blogs about the JPA. Next time we’ll go into the new Criteria API of JPA 2.0.</p>
<ul>
<li><span style="font-size: 10px;">Special thanks to Martijn Blankestijn for the Order example and Jouke Stoel for test reading.</span></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://blog.smart-java.nl/blog/index.php/2010/01/14/jpa-optimisitic-locking-versus-pessimitic-locking/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>JPA 2.0 &#8230; finally final</title>
		<link>http://blog.smart-java.nl/blog/index.php/2009/12/11/jpa-2-0-finally-final/</link>
		<comments>http://blog.smart-java.nl/blog/index.php/2009/12/11/jpa-2-0-finally-final/#comments</comments>
		<pubDate>Fri, 11 Dec 2009 10:29:49 +0000</pubDate>
		<dc:creator>Peter Schuler</dc:creator>
				<category><![CDATA[Java API]]></category>
		<category><![CDATA[Object Relational Mapping]]></category>
		<category><![CDATA[Tools/Frameworks]]></category>
		<category><![CDATA[EclipseLink]]></category>
		<category><![CDATA[JPA 2.0]]></category>
		<category><![CDATA[ORM]]></category>
		<category><![CDATA[release]]></category>

		<guid isPermaLink="false">http://blog.smart-java.nl/blog/?p=556</guid>
		<description><![CDATA[Thursday 10 December the people from EclipseLink release version 2.0 of their Object Relation Mapping framework. Besides other improvements this release includes the reference implementation of JPA 2.0.  This means that the JPA 2.0 and JSR-317 are now final!
The second release of the Jave Persistence API adds a lot of new features to the JPA [...]]]></description>
			<content:encoded><![CDATA[<p>Thursday 10 December the people from EclipseLink release version 2.0 of their <em>Object Relation Mapping</em> framework. Besides other improvements this release includes the reference implementation of JPA 2.0.  This means that the JPA 2.0 and JSR-317 are now final!</p>
<p>The second release of the <em>Jave Persistence API</em> adds a lot of new features to the JPA framework. The team responsible for this release now claims to serve 95% of the persistence needs of Java programmers. You can get the final version of <a href="http://jcp.org/en/jsr/detail?id=317" target="_blank">JSR-317 </a>or download the reference implementation on the <a href="http://www.eclipse.org/eclipselink/downloads/index.php#2.0.0" target="_blank">eclipselink website</a>. Two older blogs by Mike Keith introduces all the new features <a href="http://java.dzone.com/articles/looking-forward-jpa-20">here </a>and <a href="http://java.dzone.com/articles/looking-forward-to-jpa-20-part">here</a>.</p>
<p>Version 2.0 now has (among others) support for:</p>
<ul>
<li><a href="http://blog.smart-java.nl/blog/index.php/2010/01/14/jpa-optimisitic-locking-versus-pessimitic-locking/">Increased locking possibilities;</a></li>
<li>Support for Criteria Queries and a MetaModel;</li>
<li>(A little) support for second level caching;</li>
<li>Basic Element and embeddable collections;</li>
<li>Orphan removals for sets;</li>
<li>Derived Identifiers (using @ManyToOne as past of your primary key);</li>
<li>Ordered list.</li>
</ul>
<p>With these new features the Java Persistence API becomes even more useful. In the next  few weeks I will blog some more about the new features and go deeper into some of the new features and how to use them to your advantange.</p>
<p>So stay tuned.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.smart-java.nl/blog/index.php/2009/12/11/jpa-2-0-finally-final/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>JDK 7 language changes: DeVoxx poll</title>
		<link>http://blog.smart-java.nl/blog/index.php/2009/03/08/jdk-7-language-changes-devoxx-poll/</link>
		<comments>http://blog.smart-java.nl/blog/index.php/2009/03/08/jdk-7-language-changes-devoxx-poll/#comments</comments>
		<pubDate>Sun, 08 Mar 2009 16:07:45 +0000</pubDate>
		<dc:creator>Jan-Kees van Andel</dc:creator>
				<category><![CDATA[Java API]]></category>
		<category><![CDATA[Java language]]></category>
		<category><![CDATA[JDK 7]]></category>

		<guid isPermaLink="false">http://blog.smart-java.nl/blog/?p=325</guid>
		<description><![CDATA[Afgelopen DeVoxx is een stemming geweest waar de bezoekers konden stemmen op hun favoriete nieuwe JDK 7 features.
De grote wijzigingen zijn natuurlijk allang bepaald, zoals !closures (niet dus), JVM optimalisaties voor scripttalen (JSR 292) en Java Module System (JSR 294), maar voor JDK 7 willen ze ook een aantal kleinere wijzigingen faciliteren.
Stephen Colebourne heeft op [...]]]></description>
			<content:encoded><![CDATA[<p>Afgelopen DeVoxx is een stemming geweest waar de bezoekers konden stemmen op hun favoriete nieuwe JDK 7 features.<br />
De grote wijzigingen zijn natuurlijk allang bepaald, zoals !closures (niet dus), JVM optimalisaties voor scripttalen (<a href="http://jcp.org/en/jsr/detail?id=292">JSR 292</a>) en Java Module System (<a href="http://jcp.org/en/jsr/detail?id=294">JSR 294</a>), maar voor JDK 7 willen ze ook een aantal kleinere wijzigingen faciliteren.<br />
Stephen Colebourne heeft op zijn blog een mooie <a href="http://www.jroller.com/scolebourne/entry/jdk_7_language_changes_devoxx">samenvatting</a> van de poll geplaatst.<br />
Zoals je kunt zien, zitten er 3 populaire tussen:</p>
<ol>
<li>Null handling</li>
<li>Infer generics</li>
<li>Multi catch</li>
</ol>
<p>Properties is ook populair, maar deze komt sowieso niet in JDK 7.<br />
Deze 3 populaire features zal ik even kort laten zien:</p>
<p><b>Null handling</b><br />
Iedereen heeft weleens dergelijke code gezien:</p>

<div class="wp_syntax"><div class="code"><pre class="java5" style="font-family:monospace;"><span style="color: #000000;  font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>myObject <span style="color: #339933;">!</span>= <span style="color: #006600; font-weight: bold;">null</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #000000;  font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>myObject.<span style="color: #006633;">getProp</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">!</span>= <span style="color: #006600; font-weight: bold;">null</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000000;  font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>myObject.<span style="color: #006633;">getProp</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">getProp</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">!</span>= <span style="color: #006600; font-weight: bold;">null</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
            <span style="color: #000000; font-weight: bold;">return</span> myObject.<span style="color: #006633;">getProp</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">getProp</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">getString</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span>
    <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>Zou het niet relaxed zijn als je het zo kunt schrijven?</p>

<div class="wp_syntax"><div class="code"><pre class="java5" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">return</span> myObject<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">?</span>.<span style="color: #006633;">getProp</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">?</span>.<span style="color: #006633;">getProp</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">?</span>.<span style="color: #006633;">getString</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>Er zitten nog wat vergelijkbare constructies aan vast, zoals een aanpassing aan de ternary operator, zie <a href="http://tech.puredanger.com/java7/#null">Alex Millers blog</a>.</p>
<p><b>Infer generics</b><br />
Waarschijnlijk hebben jullie deze constructie ook weleens gezien? Zo nee, dan heb je waarschijnlijk nog geen JDK 5+ collections gebruikt. <img src='http://blog.smart-java.nl/blog/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>

<div class="wp_syntax"><div class="code"><pre class="java5" style="font-family:monospace;">List<span style="color: #339933;">&lt;</span>String<span style="color: #339933;">&gt;</span> list = <span style="color: #000000; font-weight: bold;">new</span> ArrayList<span style="color: #339933;">&lt;</span>String<span style="color: #339933;">&gt;</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>Dit is nog niet zo vervelend, maar wat dacht je van deze variant?</p>

<div class="wp_syntax"><div class="code"><pre class="java5" style="font-family:monospace;">Map<span style="color: #339933;">&lt;</span>String, AtomicReference<span style="color: #339933;">&lt;</span>SoftReference<span style="color: #339933;">&lt;</span>SomeObject<span style="color: #339933;">&gt;&gt;&gt;</span> list = <span style="color: #000000; font-weight: bold;">new</span> ConcurrentHashMap<span style="color: #339933;">&lt;</span>String, AtomicReference<span style="color: #339933;">&lt;</span>SoftReference<span style="color: #339933;">&lt;</span>SomeObject<span style="color: #339933;">&gt;&gt;&gt;</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>Vrij lelijk als je het aan mij vraagt. En in de meeste gevallen is het niet eens nuttig, aangezien links en rechts van de assignment hetzelfde staat.<br />
Wat dacht je hiervan?</p>

<div class="wp_syntax"><div class="code"><pre class="java5" style="font-family:monospace;">Map<span style="color: #339933;">&lt;</span>AtomicReference<span style="color: #339933;">&lt;</span>SoftReference<span style="color: #339933;">&lt;</span>SomeObject<span style="color: #339933;">&gt;&gt;&gt;</span> list = <span style="color: #000000; font-weight: bold;">new</span> ConcurrentHashMap<span style="color: #339933;">&lt;&gt;</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>De haken aan de rechterkant geven aan dat de compiler de typespecificatie links van de assignment naar de rechterkant gekopieerd moet worden.<br />
Zie wederom <a href="http://tech.puredanger.com/java7/#typeinference">Alex Millers blog</a> voor de details.</p>
<p><b>Ten slotte de Multi catch</b><br />
Jullie hebben ook vast weleens dergelijke catch clausules gehad neem ik aan.</p>

<div class="wp_syntax"><div class="code"><pre class="java5" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">try</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #666666; font-style: italic;">// Do something</span>
<span style="color: #009900;">&#125;</span> <span style="color: #000000; font-weight: bold;">catch</span> <span style="color: #009900;">&#40;</span>Exception1 e<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    LOG.<span style="color: #006633;">error</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Something horrible happened&quot;</span>, e<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span> <span style="color: #000000; font-weight: bold;">catch</span> <span style="color: #009900;">&#40;</span>Exception2 e<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    LOG.<span style="color: #006633;">error</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Something horrible happened&quot;</span>, e<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span> <span style="color: #000000; font-weight: bold;">catch</span> <span style="color: #009900;">&#40;</span>Exception3 e<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    LOG.<span style="color: #006633;">error</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Something horrible happened&quot;</span>, e<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span> <span style="color: #000000; font-weight: bold;">catch</span> <span style="color: #009900;">&#40;</span>Exception4 e<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    LOG.<span style="color: #006633;">error</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Something horrible happened&quot;</span>, e<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>&#8220;catch (Exception)&#8221; is niet netjes, hebben we allemaal geleerd. Voor je het weet, vang je onterecht een fout af. Maar al die code duplicatie zit je toch niet lekker. Vandaar een nieuw alternatief:</p>

<div class="wp_syntax"><div class="code"><pre class="java5" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">try</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #666666; font-style: italic;">// Do something</span>
<span style="color: #009900;">&#125;</span> <span style="color: #000000; font-weight: bold;">catch</span> <span style="color: #009900;">&#40;</span>Exception1 | Exception2 | Exception3 | Exception4 e<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    LOG.<span style="color: #006633;">error</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Something horrible happened&quot;</span>, e<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>Dat is een stuk beter he? Vooral in combinatie met Safe Rethrow kan dit erg krachtig zijn.<br />
Ik ben nog wel benieuwd naar de details, want wat is het type van &#8220;e&#8221;? Gaan ze op zoek naar een common supertype, of wordt het <a href="http://en.wikipedia.org/wiki/Duck_typing">duck typing</a>?<br />
En weer een linkje naar <a href="http://tech.puredanger.com/java7/#catch">Alex Miller</a>.</p>
<p><b>Dusss&#8230;</b><br />
Dit zijn maar een paar van de toevoegingen waar momenteel aan gewerkt wordt. Meer info over <a href="http://blogs.sun.com/darcy/entry/project_coin">&#8220;Project Coin&#8221; op Joe Darcy&#8217;s blog</a>.<br />
En natuurlijk weer <a href="http://tech.puredanger.com/java7/">Alex Miller</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.smart-java.nl/blog/index.php/2009/03/08/jdk-7-language-changes-devoxx-poll/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Spelen met Java Bluetooth</title>
		<link>http://blog.smart-java.nl/blog/index.php/2009/02/21/spelen-met-java-bluetooth/</link>
		<comments>http://blog.smart-java.nl/blog/index.php/2009/02/21/spelen-met-java-bluetooth/#comments</comments>
		<pubDate>Sat, 21 Feb 2009 17:27:20 +0000</pubDate>
		<dc:creator>Hedzer Westra</dc:creator>
				<category><![CDATA[Algemeen]]></category>
		<category><![CDATA[Java API]]></category>
		<category><![CDATA[bluetooth]]></category>

		<guid isPermaLink="false">http://blog.smart-java.nl/blog/?p=315</guid>
		<description><![CDATA[
De Bluetooth JSR-82 en de API daarbij zijn al enkele jaren oud (v1.1: 2002), maar voor mij was het een nieuwe. Hiermee kun je vanuit Java met bluetooth apparaten communiceren. Het leek me wel leuk om, al forenzend in de trein een eBook te lezen en tegelijkertijd te zien wie er allemaal elke dag met [...]]]></description>
			<content:encoded><![CDATA[<p><img class="size-medium wp-image-322" title="bluetooth-logo" src="http://blog.smart-java.nl/blog/wp-content/uploads/2009/02/bluetooth-logo.png" alt="Bluetooth logo" width="300" height="73" /></p>
<p>De <a title="Bluetooth" href="http://en.wikipedia.org/wiki/Bluetooth" target="_blank">Bluetooth</a> <a title="JSR-82" href="http://www.jcp.org/en/jsr/detail?id=82" target="_blank">JSR-82</a> en de <a title="API" href="http://java.sun.com/javame/reference/apis/jsr082" target="_blank">API</a> daarbij zijn al enkele jaren oud (v1.1: 2002), maar voor mij was het een nieuwe. Hiermee kun je vanuit Java met bluetooth apparaten communiceren. Het leek me wel leuk om, al forenzend in de trein een eBook te lezen en tegelijkertijd te zien wie er allemaal elke dag met me meereist. Deze zelfde exercitie is natuurlijk ook uitstekend in de file of op <a title="vaste locaties" href="http://bluetoothtracking.org" target="_blank">vaste locaties</a> uit te voeren…</p>
<p>Inmiddels hebben heel veel apparaten een bluetooth (‘bt’) module: GPS ontvangers, <a title="WiiMote" href="http://www.wiili.org/index.php/Wiimote" target="_blank">WiiMotes</a>, smartphones, billboards, verkeerslichten, you name it. Elk ingeschakeld apparaat adverteert zijn nummer en meestal een (door de fabrikant of eigenaar ingestelde) naam. De leukste tot nu toe vond ik “smartföhn”, maar voornamelijk zie je de naam van de eigenaar, of het merk &amp; type van het apparaat verschijnen. O, en laat ik vooral ‘Dennis Ordina’ niet ongenoemd laten! Welke collega met Nokia telefoon met bt adres 001A165A1686 zat op 4 februari om kwart voor zes in de intercity van Amsterdam Bijlmer naar Utrecht CS? <img src='http://blog.smart-java.nl/blog/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' />  Als laatste vermelding: één telefoon had als naam het 06-nummer. Lijkt me niet handig, behalve als je wilt dat Jan en alleman je belt…</p>
<p>De naam Bluetooth komt overigens van de 10e-Eeuwse koning van Denemarken en Noorwegen: Harald Blåtand (niet te verwarren met Blauwbaard!). Het logo is afgeleid van de runentekens van zijn initialen.<br />
De laatste bluetoothversie (uit 2007) is 2.1+EDR (3Mbps), en er wordt gewerkt aan een high speed variant die moderne WiFi-snelheden haalt. De radius is afhankelijk van de ‘class’ 100, 10 of 1 meter.</p>
<p><strong>Begrippen</strong></p>
<p>Eerst vuur ik enkele begrippen op je af uit de ‘bt’ wereld, waarna wat codevoorbeelden langskomen.</p>
<p>•	<em>Protocol </em>bluetooth is opgebouwd als OSI network stack van protocollen, waarvan de interessantste L2CAP (Logical Link Control and Adaptation Protocol), RFCOMM (Radio Frequency Communications) en <a title="OBEX" href="http://www.irda.org" target="_blank">OBEX</a> (OBject EXchange) zijn. Het zijn op elkaar gestapelde transportprotocollen net zoals TCP en IP op elkaar gestapeld zijn. L2CAP is packet oriented en RFCOMM stream oriented. OBEX is session oriented.<br />
•	<em>Profiel </em>interfacespecificatie; ruwweg een netwerkprotocol op applicatieniveau. Er zijn er zo’n 25 gedefinieerd; voorbeelden zijn FTP (file transfer), HID (muis/keyboard), OPP (vCards), BIP (plaatjes) en PAN (piconet). JSR-82 omvat alleen de basisprofielen GAP, SPP, SDAP, GOEP en de daarbij horende protocollen SDP (GAP+SDAP), OBEX (GOEP), RFCOMM (SPP) en L2CAP. Andere profielen moet je zelf uitprogrammeren!<br />
•	<em>Bt adres</em> vergelijkbaar aan een Ethernet MAC-adres. Bestaat uit 12 hex digits, waarvan de eerste 6 verdeeld zijn onder de fabrikanten. Aan het adres kun je dus al zien of het bijvoorbeeld een Nokia of Motorola apparaat betreft!<br />
•	<em>Master</em> net zoals er bij TCP/IP-verbindingen servers (daemons) zich registeren op een bekende poort en clients hiernaar connecten, is bt ook client/server georiënteerd; de server heet ‘master’ en registreert (publiceert) services. Dit vind je terug in bt UUIDs en URLs.<br />
•	<em>UUID</em> uniek nummer om een service (gedefinieerd in een profiel) te identificeren, vergelijkbaar aan een server IP port number. In 3 lengtes: 4, 8 of 32 hex digits. Er bestaat een simpele conversie om 4/8-digit UUID’s naar volledige lengte te converteren: concateneren met het vaste nummer 00001000800000805F9B34FB. Enkele voorbeeldwaarden: OBEX File Transfer = 0&#215;1106, Human Interface Device Profile (WiiMote!) = 0&#215;1124.<br />
•	<em>BCC</em> Bluetooth Control Centre; een GUI om je device, services &amp; security te configureren, en te zoeken naar &amp; pairen met andere devices. Meegeleverd met je bt driver.<br />
•	<em>URLs</em> je maakt connecties met behulp van URLs in het bekende formaat. Server URLs bevatten altijd “localhost”, de service UUID en eventueel parameters zoals een naam. Client URLs bevatten het remote bt adres, het kanaal- of PSM [Protocol Service Multiplexer] nummer &#8211; vergelijkbaar met een client IP port number; is niet hetzelfde als een service UUID &#8211; en eventueel (security) parameters. Enkele voorbeelden:<br />
o	<em>OBEX/GOEP<br />
</em>	<em>Server </em>btgoep://localhost:ed495afe28ed11da94d900e08161165f<br />
	<em>Client </em>btgoep://00A3920B2C22:12<br />
o	<em>RFCOMM/SPP<br />
</em>	<em>Server </em> btspp://localhost:;name=Sample SPP Server<br />
	<em>Client </em>btspp://0050CD00321B:3;authenticate={true|false}; authorize={true|false};encrypt={true|false}<br />
o	<em>L2CAP<br />
</em>	<em>Client </em>btl2cap://0050CD00321B:1003; ReceiveMTU=512;TransmitMTU=512<br />
•	<em>Piconet </em>mininetwerk van maximaal 8 bt devices – meer verbindingen ondersteunt bluetooth niet. Een netwerk van meerdere aan elkaar gekoppelde piconets heet een scatternet.<br />
•	<em>Service class</em> elk bt device kan met zijn service class aangeven welke service types hij ondersteunt (bijv. positioning, networking of audio) en van welk (sub)type hij is (bijv. Computer/Laptop of Peripheral/Joystick).<br />
•	<em>Discovery </em>scannen naar devices en/of services. Na discovery levert JSR-82 je URLs zodat je die niet zelf hoeft op te bouwen. Een bt device kan altijd (‘global’/’general’) discoverable zijn (GIAC), een beperkte tijd (‘limited’ &#8211; LIAC) of helemaal niet. Dit poor-mans beveiligingsmechanisme is bekend van WiFi routers. Ook daar is de fabrieksinstelling meestal niet de veiligste… Discovery is niet erg snel; een complete sweep van devices &amp; hun services duurt afhankelijk van het aantal devices in bereik één tot meerdere minuten, dit onder andere omdat er geen parallelle service discoveries kunnen draaien.<br />
•	<em>Service record</em> bij discovery van een service ontvang je een lijst van attributen met onder anderen een leesbare naam en kanaal (RFCOMM&amp;OBEX)- of PSM (L2CAP) nummer. Helaas vullen niet alle bt devices dit service record exact volgens de specs.<br />
•	<em>Pairing </em>pas nadat apparaten aan elkaar bekend zijn gemaakt middels een PIN-code (meestal 0000…) kan communicatie gestart worden. Helaas voor mijn tagger kan dit alleen via de BCC; de JSR-82 API voorziet er niet in om een PIN-code door te geven. Bij pairing wordt overigens ook een gedeelde 128b sleutel afgesproken, die daarna gebruikt wordt als autorisatie en/of encryptie aangezet worden. Dat laatste kan dan wel weer vanuit Java. Discovery is overigens wel mogelijk zonder te pairen; mijn tagger kan van elk device dat in bereik is en in bluetooth discovery mode staat (hetgeen bijna elke telefoon is, vanuit de winkel) de volgende attributen uitvragen: bt adres, naam, service class, services inclusief naam, UUID en URL. Als een pairing wel bestaat (in JSR-82 termen: het device is ‘trusted’), is het mogelijk om een connectie op te bouwen, bijv. simpelweg om de pingtijd te meten.</p>
<p><strong>Codevoorbeelden</strong></p>
<p>De betrokken Java packages zijn: javax.bluetooth, javax.obex en javax.microedition.io.<br />
Wat betreft dat laatste package: JSR-82 heeft veel raakvlakken met J2ME (termen in het verlengde hiervan: MIDP, CLDC en CDC), wat logisch is omdat bluetooth in 1998 door Nokia bedacht is als draadloze communicatie van mobieltjes naar andere apparaten. Mocht je iets met J2ME &amp; bt willen doen (laat me je resultaten weten!): telefoons kunnen zelf ook JSR-82 implementeren, maar niet alle telefoons met bt &amp; Java doen dat! Zie de <a title="bluecove Wiki" href="http://code.google.com/p/bluecove/w/list" target="_blank">bluecove Wiki</a> voor een lijst.</p>
<p>De API is vrij klein. De belangrijkste klassen zijn DiscoveryAgent, LocalDevice en RemoteDevice.</p>
<p>Twee problemen die ik ben tegengekomen met deze API:<br />
1.	Een afgrijselijke klasse is DataElement. Dit is een wrapper voor diverse soorten datatypes. Je zult er helaas mee moeten leven.<br />
2.	Als je alleen het bt adres van een device weet, dan moet je eerst discoveren. Je kunt namelijk niet op basis van dit adres een RemoteDevice (laten) instantiëren. Maar als je een URL kent kun je wel meteen connecten! Vreemd…</p>
<p>Nu volgen enkele zeer kleine &amp; korte codevoorbeelden – check voor enkele compleet werkende applicaties de Eclipse workspace op de <a title="Ordina Wiki" href="https://wiki.ordina.nl/confluence/display/JAVA/Java+Bluetooth" target="_blank">Ordina Wiki</a>. (Helaas zijn de syntax highlighting &amp; tabs verloren gegaan bij kopiëren vanuit Word naar WordPress&#8230;)</p>
<p>// setup: get local device &amp; discovery agent<br />
LocalDevice localDevice = LocalDevice.getLocalDevice();<br />
DiscoveryAgent discoveryAgent = localDevice.getDiscoveryAgent();</p>
<p>// start global device inquiry<br />
MyDiscoveryListener discoveryListener = new MyDiscoveryListener();<br />
boolean limited = false;<br />
boolean started = discoveryAgent.startInquiry(<br />
limited ? DiscoveryAgent.LIAC : DiscoveryAgent.GIAC,<br />
discoveryListener);</p>
<p>// retrieve name of first remote device in list<br />
RemoteDevice remoteDevice = discoveryListener.getDiscoveredDevices().get(0).getRemoteDevice();<br />
String deviceName = remoteDevice.getFriendlyName(true);</p>
<p>// search for services using RFCOMM on the first remote device<br />
UUID[] uuids = new UUID[]{new UUID(BluetoothConstants.PROTOCOL_RFCOMM)};<br />
int transId = discoveryAgent.searchServices(null, uuids, remoteDevice,<br />
discoveryListener);</p>
<p>// retrieve a connection URL using the first service record<br />
ServiceRecord record = discoveryListener.getServiceRecords().get(transId)[0];<br />
String url = record.getConnectionURL(ServiceRecord.NOAUTHENTICATE_NOENCRYPT, false);</p>
<p>// open L2CAP, RFCOMM &amp; OBEX connections<br />
L2CAPConnection l2capConnection = (L2CAPConnection) Connector.open(url);</p>
<p>StreamConnection rfcommConnection = (StreamConnection) Connector.open(url);</p>
<p>ClientSession obexConnection = (ClientSession) Connector.open(url);<br />
HeaderSet hsConnectReply = obexConnection.connect(null);<br />
if (hsConnectReply.getResponseCode() != ResponseCodes.OBEX_HTTP_OK) {<br />
// 196 = not found, 204 = precon failed, 160 = ok<br />
LOG.error(&#8220;expected OBEX_HTTP_OK but got &#8221; + hsConnectReply.getResponseCode());<br />
}</p>
<p>Hoe service registratie werkt (dit is: opzetten van een server connectie die wacht op clients) kun je terugvinden in de Eclipse workspace.</p>
<p><strong>OBEX – OBject EXchange</strong></p>
<p>OBEX is ‘geleend’ van de IrDa (infrarood) wereld, vandaar dat de API een eigen package javax.obex heeft. Binnen bt werkt OBEX bovenop RFCOMM, maar OBEX ondersteunt ook IrDa en TCP/IP als transportlaag.</p>
<p>Ondersteunde diensten zijn o.a. FTP (phone2PC), Object Push (phone2phone – zogezegd gebruikt bij <a title="toothing" href="http://en.wikipedia.org/wiki/Toothing" target="_blank">toothing</a>, Sync, basic imaging en basic printing.</p>
<p>Het protocol doet denken aan HTTP. Herkenbare concepten zijn:<br />
•	Headers	12 gedefinieerde parameters, o.a. name, type en length<br />
•	Sessions	op basis van connectie ID<br />
•	Content types	text/vcard, x-obex/folder-listing, etc.<br />
•	Commands	CONNECT, PUT, GET, SETPATH, ABORT, CREATE-EMPTY, PUT-DELETE en DISCONNECT<br />
•	Error codes	OBEX_HTTP_OK, OBEX_HTTP_NOT_FOUND, etc.</p>
<p>Voorbeelden van uit te wisselen data zijn: vCard, vCalendar, vMessage, vNotes en platte bestanden.</p>
<p>De belangrijkste 4 klassen/interfaces en hun supertypes zijn:<br />
•	ClientSession &gt; Connection<br />
•	HeaderSet<br />
•	Operation &gt; ContentConnection &gt; StreamConnection &gt; OutputConnection &amp; InputConnection &gt; Connection<br />
•	SessionNotifier &gt; Connection</p>
<p><strong>JSR-82 implementaties &amp; bt stacks</strong></p>
<p><a title="Bluecove" href="http://code.google.com/p/bluecove/" target="_blank">Bluecove</a> is momenteel de enige actief onderhouden, bruikbare en gratis JSR-82 implementatie, maar werkt gelukkig redelijk goed. Bluecove heeft wel een bluetooth stack nodig. Voor Windows wordt widcomm aangeraden en BlueSoleil ten zeerste afgeraden – dit kan ik beamen! De bluetooth stack wordt meegeleverd met je chipset, dus kiezen kun je niet. Gelukkig bevat mijn Ordina laptop (HP Compaq 6910p) een widcomm ingebouwd. Wel eerst even een <a title="service pack" href="http://h20000.www2.hp.com/bizsupport/TechSupport/SoftwareDescription.jsp?lang=en&amp;cc=us&amp;prodTypeId=321957&amp;prodSeriesId=3357377&amp;swItem=ob-57457-1&amp;prodNameId=3357378&amp;swEnvOID=1093&amp;swLang=8&amp;taskId=135&amp;mode=4&amp;idx=0 " target="_blank">service pack</a> van <a title="100MB" href="ftp://ftp.hp.com/pub/softpaq/sp38001-38500/sp38145.exe" target="_blank">100MB</a> installeren! Voordat ik dat deed werd de widcomm niet herkend en ben ik met een USB bt stikkie van cygnet aan het klooien geweest. Helaas zat daar BlueSoleil bij en dat ging niet erg lekker.</p>
<p>Op Linux kun je gebruik maken van de BlueZ stack. Ik heb ‘m niet geprobeerd – laat me je ervaringen weten!</p>
<p>Een mogelijk client programma is <a title="Nokia PC Suite" href="http://www.nokia.nl/A4393234" target="_blank">Nokia PC Suite</a>, die bijvoorbeeld. een remote file browser biedt. Helaas installeert Nokia zoveel dingen achter je rug om (koppelt onder andere de JAR extensie aan een Nokia application installer!) dat ik deze afraad.</p>
<p>Overigens werkt ook de combinatie widcomm &amp; bluecove niet vlekkeloos. Enkele keren heb ik een JVM crash gehad, een vastlopende BT stack (een volledige herstart helpt, maar soms is killen van BTStackServer.exe voldoende), een BCC die mijn connecties afpakte (alleen een unpair/pair-actie verhelpt dit), et cetera. Als je de documentatie van bluecove mag geloven, ligt dit eerder aan de slechte staat van bluetooth stacks, danwel aan een mismatch tussen stacks en JSR-82, dan aan bluecove zelf. Toch krijg ik een beetje een déjà-vu met JMF en Java Serial: ook dit zijn Java extensies waarvoor eigenlijk nooit een goede (reference) implementatie is gekomen, en door Sun een beetje aan hun lot lijken te zijn overgelaten.</p>
<p><strong>Documentatie</strong></p>
<p>Er bestaat een <a title="bluetooth" href="www.bluetooth.org" target="_blank">bluetooth</a> <a title="SIG" href="www.bluetooth.com" target="_blank">SIG</a> die alle <a title="specs publiceert" href="http://www.bluetooth.com/Bluetooth/Technology/Building/Specifications/" target="_blank">specs publiceert</a>; onder andere die van alle profielen. Helaas moet je voor de meest informatie lid zijn, en dat kunnen alleen betalende bedrijven of universiteiten. Ik heb ze gecontacteerd voor een simpele lijst met standaard UUID nummers, en kreeg pas na lang aandringen antwoord – natuurlijk pas nadat ik mijn code af had. De online documentatie &amp; tutorials die ik wél gevonden heb is helaas vaak slecht, oud, weinig diepgaand en lastig te vinden – ik heb hier en daar door open source code moeten snuffelen voor ontbrekende informatie (zoals voornoemde UUID nummers).</p>
<p>Voor mijn source code, verwijzingen naar boeken, meer technische informatie, een lijst van geregistreerde UUIDs, attributen en service classes, en extra URLs verwijs ik je naar de <a title="Ordina Wiki pagina" href="https://wiki.ordina.nl/confluence/display/JAVA/Java+Bluetooth" target="_blank">Ordina Wiki pagina</a> die ik hiervoor opgezet heb.</p>
<p>Mocht je zelf ook aan de gang gaan met Java bluetooth, dan hoor ik graag van je terug wat je resultaten zijn. Codebijdragen zijn natuurlijk welkom op de Wiki!</p>
<div id="attachment_321" class="wp-caption alignnone" style="width: 103px"><a href="http://blog.smart-java.nl/blog/wp-content/uploads/2009/02/hedzerwestra_93x1231.jpg"><img class="size-medium wp-image-321" title="hedzerwestra_93x1231" src="http://blog.smart-java.nl/blog/wp-content/uploads/2009/02/hedzerwestra_93x1231.jpg" alt="Hedzer Westra" width="93" height="123" /></a><p class="wp-caption-text">Hedzer Westra</p></div>
]]></content:encoded>
			<wfw:commentRss>http://blog.smart-java.nl/blog/index.php/2009/02/21/spelen-met-java-bluetooth/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Java 6 undocumented change: @Override</title>
		<link>http://blog.smart-java.nl/blog/index.php/2008/10/15/java-6-undocumented-change-override/</link>
		<comments>http://blog.smart-java.nl/blog/index.php/2008/10/15/java-6-undocumented-change-override/#comments</comments>
		<pubDate>Wed, 15 Oct 2008 14:40:43 +0000</pubDate>
		<dc:creator>Jan-Kees van Andel</dc:creator>
				<category><![CDATA[Algemeen]]></category>
		<category><![CDATA[Java API]]></category>
		<category><![CDATA[compiler compliance level]]></category>
		<category><![CDATA[eclipse]]></category>
		<category><![CDATA[java 5]]></category>
		<category><![CDATA[java 6]]></category>
		<category><![CDATA[override]]></category>

		<guid isPermaLink="false">http://blog.smart-java.nl/blog/?p=218</guid>
		<description><![CDATA[Het valt me op projecten al een tijdje op dat collega&#8217;s compilatiefouten krijgen op @Override. Deze fouten kreeg ik zelf nooit. Gisteren tijdens de JSF cursus gebeurde het weer. Weer twee mensen die tegen deze fout aan liepen. Bij de rest van de groep ging het goed, maar bij deze twee niet, ondanks dat ze [...]]]></description>
			<content:encoded><![CDATA[<p>Het valt me op projecten al een tijdje op dat collega&#8217;s compilatiefouten krijgen op @Override. Deze fouten kreeg ik zelf nooit. Gisteren tijdens de JSF cursus gebeurde het weer. Weer twee mensen die tegen deze fout aan liepen. Bij de rest van de groep ging het goed, maar bij deze twee niet, ondanks dat ze dezelfde stappen doorliepen als de rest.</p>
<p>In de code kwamen een stuk of 20 compile errors naar voren, allemaal gerelateerd aan @Override. De melding was:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">The method <span style="color: #009900;">&#91;</span>METHODNAME<span style="color: #009900;">&#93;</span> of type <span style="color: #009900;">&#91;</span>CLASSNAME<span style="color: #009900;">&#93;</span> must override a superclass method</pre></div></div>

<p>Het probleem is een aanpassing die in Java 6 is gemaakt. In Java 5 mag deze annotation alleen op een method staan die een method uit een klasse override. Of de method in de superclass abstract is en of de superclass zelf abstract is, maakt niet uit. Wat wel uitmaakt in Java 5, is dat een method die een interface method implementeert, niet met @Override geannoteerd mag zijn.</p>
<p>Dit mag dus niet in Java 5.</p>

<div class="wp_syntax"><div class="code"><pre class="java5" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">interface</span> MyInterface <span style="color: #009900;">&#123;</span>
    <span style="color: #006600; font-weight: bold;">void</span> doSomething<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">class</span> MyImplementation <span style="color: #000000; font-weight: bold;">implements</span> MyInterface <span style="color: #009900;">&#123;</span>
    <span style="color: #666666; font-style: italic;">// Error in Java 5: The method doSomething() of type MyImplementation must override a superclass method</span>
    @<span style="color: #003399; font-weight: bold;">Override</span>
    <span style="color: #006600; font-weight: bold;">void</span> doSomething<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span><span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>Het vervelende was dat Eclipse die annotaties neer had gezet omdat mijn Compiler Compliance Level op 6 stond en ik een Java 6 compiler gebruikte, maar niet iedere cursist gebruikte Java 6.</p>
<p>Leuk detail: We hebben het hier over een (per ongeluk) niet gedocumenteerde feature van Java 6. Zie Peter Ahé&#8217;s weblog.<br />
<a href="http://blogs.sun.com/ahe/entry/override">http://blogs.sun.com/ahe/entry/override</a><br />
<a href="http://blogs.sun.com/ahe/entry/override_snafu">http://blogs.sun.com/ahe/entry/override_snafu</a></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.smart-java.nl/blog/index.php/2008/10/15/java-6-undocumented-change-override/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
	</channel>
</rss>
