<?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>Martin Ankerl &#187; java</title>
	<atom:link href="http://martin.ankerl.com/category/java/feed/" rel="self" type="application/rss+xml" />
	<link>http://martin.ankerl.com</link>
	<description>No movement is faster than no movement</description>
	<lastBuildDate>Tue, 13 Jul 2010 05:31:29 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=abc</generator>
		<item>
		<title>Java 1.5 Collections Hierarchy Graph</title>
		<link>http://martin.ankerl.com/2009/01/05/java-15-collections-hierarchy-graph/</link>
		<comments>http://martin.ankerl.com/2009/01/05/java-15-collections-hierarchy-graph/#comments</comments>
		<pubDate>Mon, 05 Jan 2009 12:13:26 +0000</pubDate>
		<dc:creator>Martin Ankerl</dc:creator>
				<category><![CDATA[java]]></category>
		<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://martin.ankerl.com/?p=116</guid>
		<description><![CDATA[Here is an inheritence graph of some of the more important Java collection classes of Java 1.5. Instantiateable classes are blue and rectangular, abstract classes are just rectangular, and interfaces are elliptic. Click on the image for a printable size: Java 1.5 Collections Hierarchy As a sidenote, have written this post almost a year ago [...]]]></description>
			<content:encoded><![CDATA[<p>Here is an inheritence graph of some of the more important Java collection classes of <a href="http://javadoc.ankerl.com/">Java 1.5</a>. Instantiateable classes are blue and rectangular, abstract classes are just rectangular, and interfaces are elliptic. Click on the image for a printable size:</p>
<p><center><a href='http://martin.ankerl.com/wp-content/uploads/2008/01/collections.png' title='Java Collections Hierarchy'><img src='http://martin.ankerl.com/wp-content/uploads/2008/01/collections-small.png' alt='Java Collections Hierarchy Small' /></a><br/><strong>Java 1.5 Collections Hierarchy</strong></center></p>
<p>As a sidenote, have written this post almost a year ago and just found it in my drafts. I have completely forgotten about it! So here it is anyways. And now I remember why I did not post it: becauseit contains only a minor subset of the collections! Thanks Artur Biesiadowski for reminding me about that&#8230;</p>
<div style='clear:both'></div><img src="http://martin.ankerl.com/?ak_action=api_record_view&id=116&type=feed" alt="" />]]></content:encoded>
			<wfw:commentRss>http://martin.ankerl.com/2009/01/05/java-15-collections-hierarchy-graph/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Approximation of sqrt(x) in Java</title>
		<link>http://martin.ankerl.com/2009/01/05/approximation-of-sqrtx-in-java/</link>
		<comments>http://martin.ankerl.com/2009/01/05/approximation-of-sqrtx-in-java/#comments</comments>
		<pubDate>Mon, 05 Jan 2009 11:51:50 +0000</pubDate>
		<dc:creator>Martin Ankerl</dc:creator>
				<category><![CDATA[coding]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[tricks]]></category>

		<guid isPermaLink="false">http://martin.ankerl.com/?p=195</guid>
		<description><![CDATA[Yesterday I have played a bit with reinventing a fast approximation for sqrt() in Java. This might be handy with J2ME. Wikipedia has a nice article about Approximations that depend on IEEE representation. My version works, and on my Intel Dual Core with an average error of 1.57%, maximum error 4.02% it is 3.5 times [...]]]></description>
			<content:encoded><![CDATA[<p>Yesterday I have played a bit with reinventing a fast approximation for <tt>sqrt()</tt> in Java. This might be handy with J2ME. Wikipedia has a nice article about <a href="http://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Approximations_that_depend_on_IEEE_representation">Approximations that depend on IEEE representation</a>.  My version works, and on my Intel Dual Core with an average error of 1.57%, maximum error 4.02% it is 3.5 times faster than the original sqrt. In addition, it is very simple to improve the precision to 0.000161% average error and 0.000775% maximum error which is then 1.56 times faster than <tt>Math.sqrt()</tt>.</p>
<h2>Sourcecode</h2>
<p>I use floating point tricks based on my <a href="http://martin.ankerl.com/2007/10/04/optimized-pow-approximation-for-java-and-c-c/">pow() approximation</a>. Basically I just took the pow() formula and for a^b I substitued <tt>b</tt> with <tt>0.5</tt>, then simplified this as much as possible. As it turns out the result is very simple and short. This initial approximation can be easily made more precise with <a href="http://en.wikipedia.org/wiki/Newton%27s_method">Newton&#8217;s method</a>:</p>
<pre class="brush: java;">
    public static double sqrt(final double a) {
        final long x = Double.doubleToLongBits(a) &gt;&gt; 32;
        double y = Double.longBitsToDouble((x + 1072632448) &lt;&lt; 31);

        // repeat the following line for more precision
        //y = (y + a / y) * 0.5;
        return y;
    }
</pre>
<p>Here is a comparison of the performance and accurancy versus the number of repetitions:</p>
<table width="100%">
<tr>
<th>Repetitions</th>
<th>Average<br/>error</th>
<th>Maximum<br/>error</th>
<th>Speedup</th>
</tr>
<tr>
<td>0</td>
<td>1.57%</td>
<td>4.02%</td>
<td>3.53</td>
</tr>
<tr>
<td>1</td>
<td>0.000161%</td>
<td>0.000775%</td>
<td>1.56</td>
</tr>
<tr>
<td>2</td>
<td>2.51e-8%</td>
<td>3.00e-7</td>
<td>0.838</td>
</tr>
</table>
<p>With 2 repetitions, the trouble is not worth the effort, as the approximation is already slower than the original Math.sqrt() which is more precise.</p>
<div style='clear:both'></div><img src="http://martin.ankerl.com/?ak_action=api_record_view&id=195&type=feed" alt="" />]]></content:encoded>
			<wfw:commentRss>http://martin.ankerl.com/2009/01/05/approximation-of-sqrtx-in-java/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Amazing Caching Proxy in Java</title>
		<link>http://martin.ankerl.com/2008/12/22/amazing-caching-proxy-in-java/</link>
		<comments>http://martin.ankerl.com/2008/12/22/amazing-caching-proxy-in-java/#comments</comments>
		<pubDate>Mon, 22 Dec 2008 21:53:59 +0000</pubDate>
		<dc:creator>Martin Ankerl</dc:creator>
				<category><![CDATA[java]]></category>
		<category><![CDATA[open source]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[tricks]]></category>
		<category><![CDATA[tutorial]]></category>

		<guid isPermaLink="false">http://martin.ankerl.com/?p=184</guid>
		<description><![CDATA[Use Case Imagine you have some Java code that does lots and lots of computation. All the time intensive calculations is performed by the class SlowCalculator which implements the interface Calculator: public static interface Calculator { public String calculate(int a, String b); } public static void main(String[] args) { Calculator c = new SlowCalculator(); // [...]]]></description>
			<content:encoded><![CDATA[<h2>Use Case</h2>
<p>Imagine you have some Java code that does lots and lots of computation. All the time intensive calculations is performed by the class <tt>SlowCalculator</tt> which implements the interface <tt>Calculator</tt>:</p>
<pre class="brush: java;">
public static interface Calculator {
    public String calculate(int a, String b);
}

public static void main(String[] args) {
    Calculator c = new SlowCalculator();
    // call c.calculate() a lot of times here...
}
</pre>
<p>You notice that <tt>calculate()</tt> is often called with the same parameters which lead to the exact same result (<tt>SlowCalculator</tt> is stateless). This means it is possible to cache values so there&#8217;s no need to recompute. Using the generic CachingProxy&trade; described below, you can create a cached proxy for any class with just one single line of code:</p>
<pre class="brush: java;">
// ...

public static void main(String[] args) {
    Calculator c = new SlowCalculator();
    c = CachedProxy.create(Calculator.class, c);
    // call c.calculate() a lot of times here...
}
</pre>
<p>That&#8217;s it, and the application is blazingly fast again.</p>
<p><strong>UPDATE</strong>: Support for <tt>null</tt> values, transparently handles exceptions, better hash, nullpointer-bugfix.</p>
<p><strong>UPDATE</strong>: Here is an article &#8220;<a href="http://www.onjava.com/pub/a/onjava/2003/08/20/memoization.html">Memoization in Java Using Dynamic Proxy Classes</a>&#8221; that does (almost) exactly the same as this code.</p>
<p><span id="more-184"></span></p>
<h2>How To Do This</h2>
<p>All this sounds nice, but can you do this in java? Turns out you can and it is not that difficult either. The feature that makes it all possible is <a href="http://java.sun.com/j2se/1.4.2/docs/guide/reflection/proxy.html">Dynamic Proxy</a>. With it you can implement interfaces <em>at runtime</em>. You take an interface, create a proxy for it with <tt><a href="http://java.sun.com/javase/6/docs/api/java/lang/reflect/Proxy.html">Proxy</a>.newProxyInstance(...)</tt>, supply an <a href="http://java.sun.com/javase/6/docs/api/java/lang/reflect/InvocationHandler.html">InvocationHandler</a> that implements the <tt><a href="http://java.sun.com/javase/6/docs/api/java/lang/reflect/InvocationHandler.html#invoke(java.lang.Object, java.lang.reflect.Method, java.lang.Object[])">invoke()</a></tt> method, and you are done.</p>
<p>The code for the <tt>CachedProxy.create()</tt> method is this:</p>
<pre class="brush: java;">
    /**
     * Creates an intermediate proxy object that uses cached results if
     * available, otherwise calls the given code.
     *
     * @param &lt;T&gt;
     *            Type of the class.
     * @param cl
     *            The interface for which the proxy should be created.
     * @param code
     *            The actual calculation code that should be cached.
     * @return The proxy.
     */
    @SuppressWarnings(&quot;unchecked&quot;)
    public static &lt;T&gt; T create(final Class&lt;T&gt; cl, final T code) {
        // create the cache
        final Map&lt;Args, Object&gt; argsToOutput = new HashMap&lt;Args, Object&gt;();

        // proxy for the interface T
        return (T) Proxy.newProxyInstance(cl.getClassLoader(), new Class&lt;?&gt;[] { cl }, new InvocationHandler() {

            @Override
            public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable {
                final Args input = new Args(method, args);
                Object result = argsToOutput.get(input);
                // check containsKey to support null values
                if (result == null &amp;&amp; !argsToOutput.containsKey(input)) {
                    // make sure exceptions are handled transparently
                    try {
                        result = method.invoke(code, args);
                        argsToOutput.put(input, result);
                    } catch (InvocationTargetException e) {
                        throw e.getTargetException();
                    }
                }
                return result;
            }
        });
    }
</pre>
<ol>
<li>First I create a <tt>HashMap</tt> that is the cache for the return values. I have written a class <tt>Args</tt> (omitted here) that is as the key to map from the method and the parameters to the cached output.
<li>A Proxy is created for the interface <tt>cl</tt>, with an InvocationHandler that does all the magic.
<li>The magic is actually very simple: If there is no cached result already available (line 25), perform the computation (line 26) and store the result in the map, then return the result.
</ol>
<h2>Download</h2>
<p>You can get the full code at my github repository:</p>
<ul>
<li>
<a href="http://github.com/martinus/java-playground/tree/master/src/java/com/ankerl/proxy/CachedProxy.java">CachedProxy</a>
</li>
</ul>
<h2>Benchmarks</h2>
<p>In my benchmark I can run about 8 million calls per secons via the cached proxy. That&#8217;s not too bad, given all the additional overhead with reflection and the HashMap.</p>
<p>Do you know of any way to improve this? Any ideas or suggestions are welcome!</p>
<div style='clear:both'></div><img src="http://martin.ankerl.com/?ak_action=api_record_view&id=184&type=feed" alt="" />]]></content:encoded>
			<wfw:commentRss>http://martin.ankerl.com/2008/12/22/amazing-caching-proxy-in-java/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>Optimized pow() approximation for Java, C / C++, and C#</title>
		<link>http://martin.ankerl.com/2007/10/04/optimized-pow-approximation-for-java-and-c-c/</link>
		<comments>http://martin.ankerl.com/2007/10/04/optimized-pow-approximation-for-java-and-c-c/#comments</comments>
		<pubDate>Thu, 04 Oct 2007 22:48:08 +0000</pubDate>
		<dc:creator>Martin Ankerl</dc:creator>
				<category><![CDATA[C++]]></category>
		<category><![CDATA[benchmark]]></category>
		<category><![CDATA[coding]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[linux]]></category>
		<category><![CDATA[news]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[science]]></category>
		<category><![CDATA[tricks]]></category>
		<category><![CDATA[floating point]]></category>
		<category><![CDATA[optimization]]></category>

		<guid isPermaLink="false">http://martin.ankerl.com/?p=96</guid>
		<description><![CDATA[I have already written about approximations of e^x, log(x) and pow(a, b) in my post Optimized Exponential Functions for Java. Now I have more In particular, the pow() function is now even faster, simpler, and more accurate. Without further ado, I proudly give you the brand new approximation: Approximation of pow() in Java public static [...]]]></description>
			<content:encoded><![CDATA[<p>I have already written about approximations of <tt>e^x</tt>, <tt>log(x)</tt> and <tt>pow(a, b)</tt> in my post <a href="http://martin.ankerl.com/2007/02/11/optimized-exponential-functions-for-java/">Optimized Exponential Functions for Java</a>. Now I have more <img src='http://martin.ankerl.com/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' />  In particular, the <tt>pow()</tt> function is now even faster, simpler, and more accurate. Without further ado, I proudly give you the brand new approximation:</p>
<h1>Approximation of pow() in Java</h1>
<pre class="brush: java;">public static double pow(final double a, final double b) {
    final int x = (int) (Double.doubleToLongBits(a) &gt;&gt; 32);
    final int y = (int) (b * (x - 1072632447) + 1072632447);
    return Double.longBitsToDouble(((long) y) &lt;&lt; 32);
}</pre>
<p>This is really very compact. The calculation only requires 2 shifts, 1 mul, 2 add, and 2 register operations. That&#8217;s it! In my tests it usually within an error margin of 5% to 12%, in extreme cases sometimes up to 25%. A careful analysis is left as an exercise for the reader. This is very usable for in e.g. <a href="http://en.wikipedia.org/wiki/Metaheuristic">metaheuristics</a> or <a href="http://en.wikipedia.org/wiki/Artificial_neural_network">neural nets</a>.</p>
<p>I use Linux, Java 1.6.0-b105 with the server VM, and execute the benchmark with this command:
<pre>sudo nice -n -20 java -cp . -server PowTest</pre>
<p> The approximation is <b>27 times faster</b> than Math.pow() on my Pentium-M. On a Pentium 4 it is <b>41 times faster</b>. Unfortunately, microbenchmarks are difficult to do in Java, so your mileage may vary. You can download the benchmark <a href="/files/PowTest.java">PowTest.java</a> and have a look, I have tried to prevent overoptimization while still having a low overhead.</p>
<h1>Approximation of pow() in C and C++</h1>
<pre class="brush: cpp;">double pow(double a, double b) {
    int tmp = (*(1 + (int *)&amp;a));
    int tmp2 = (int)(b * (tmp - 1072632447) + 1072632447);
    double p = 0.0;
    *(1 + (int * )&amp;p) = tmp2;
    return p;
}</pre>
<p>Compiled on my Pentium-M with gcc 4.1.2:
<pre>gcc -O3 -march=pentium-m -fomit-frame-pointer -fno-strict-aliasing</pre>
<p>This version is <b>7.8 times</b> faster than pow() from the standard library.</p>
<p><strong>WARNING</strong>! you HAVE to use the <tt>-fno-strict-aliasing</tt> option, or this does not work!</p>
<h1>Approximation of pow() in C#</h1>
<p>Jason Jung has posted a port of the this code to C#: </p>
<pre class="brush: csharp;">public static double PowerA(double a, double b) {
  int tmp = (int)(BitConverter.DoubleToInt64Bits(a) &gt;&gt; 32);
  int tmp2 = (int)(b * (tmp - 1072632447) + 1072632447);
  return BitConverter.Int64BitsToDouble(((long)tmp2) &lt;&lt; 32);
}</pre>
<h1>How the Approximation was Developed</h1>
<p>It is quite impossible to understand what is going on in this function, it just magically works. To shine a bit more light on it, here is a detailed description how I have developed this.</p>
<h2>Approximation of e^x</h2>
<p>As described <a href="http://martin.ankerl.com/2007/02/11/optimized-exponential-functions-for-java/">here</a>, the paper &#8220;<a href="http://citeseer.ist.psu.edu/schraudolph98fast.html">A Fast, Compact Approximation of the Exponential Function</a>&#8221; develops a C macro that does a good job at exploiting the IEEE 754 floating-point representation to calculate <tt>e^x</tt>. This macro can be transformed into Java code straightforward, which looks like this:</p>
<pre class="brush: java;">public static double exp(double val) {
    final long tmp = (long) (1512775 * val + (1072693248 - 60801));
    return Double.longBitsToDouble(tmp &lt;&lt; 32);
}</pre>
<h2>Use Exponential Functions for a^b</h2>
<p>Thanks to the power of math, we know that <tt>a^b</tt> can be transformed like this:</p>
<ol>
<li>Take exponential
<pre>a^b = e^(ln(a^b))</pre>
<li>Extract b
<pre>a^b = e^(ln(a)*b)</pre>
</ol>
<p>Now we have expressed the pow calculation with <tt>e^x</tt> and <tt>ln(x)</tt>. We already have the <tt>e^x</tt> approximation, but no good <tt>ln(x)</tt>. The <a href="http://martin.ankerl.com/2007/02/11/optimized-exponential-functions-for-java/">old approximation</a> is very bad, so we need a better one. So what now?</p>
<h2>Approximation of ln(x)</h2>
<p>Here comes the big trick: Rember that we have the nice <tt>e^x</tt> approximation? Well, <tt>ln(x)</tt> is exactly the inverse function! That means we just need to transform the above approximation so that the output of <tt>e^x</tt> is transformed back into the original input.</p>
<p>That&#8217;s not too difficult. Have a look at the above code, we now take the output and move backwards to undo the calculation. First reverse the shift:</p>
<pre>final double tmp = (Double.doubleToLongBits(val) >> 32);</pre>
<p>Now solve the equation
<pre>tmp = (1512775 * val + (1072693248 - 60801))</pre>
<p> for val:</p>
<ol>
<li>The original formula
<pre>tmp = (1512775 * val + (1072693248 - 60801))</pre>
<li>Perform subtraction
<pre>tmp = 1512775 * val + 1072632447</pre>
<li>Bring value to other side
<pre>tmp - 1072632447 = 1512775 * val</pre>
<li>Divide by factor
<pre>(tmp - 1072632447) / 1512775 = val</pre>
<li>Finally, val on the left side
<pre>val = (tmp - 1072632447) / 1512775</pre>
</ol>
<p>Voíla, now we have a nice approximation of <tt>ln(x)</tt>:</p>
<pre class="brush: java;">public double ln(double val) {
    final double x = (Double.doubleToLongBits(val) &gt;&gt; 32);
    return (x - 1072632447) / 1512775;
}</pre>
<h2>Combine Both Approximations</h2>
<p>Finally we can combine the two approximations into <tt>e^(ln(a) * b)</tt>:</p>
<pre class="brush: java;">public static double pow1(final double a, final double b) {
    // calculate ln(a)
    final double x = (Double.doubleToLongBits(a) &gt;&gt; 32);
    final double ln_a = (x - 1072632447) / 1512775;

    // ln(a) * b
    final double tmp1 = ln_a * b;

    // e^(ln(a) * b)
    final long tmp2 = (long) (1512775 * tmp1 + (1072693248 - 60801));
    return Double.longBitsToDouble(tmp2 &lt;&lt; 32);
}</pre>
<p>Between the two shifts, we can simply insert the <tt>tmp1</tt> calculation into the tmp2 calculation to get</p>
<pre class="brush: java;">public static double pow2(final double a, final double b) {
    final double x = (Double.doubleToLongBits(a) &gt;&gt; 32);
    final long tmp2 = (long) (1512775 * (x - 1072632447) / 1512775 * b + (1072693248 - 60801));
    return Double.longBitsToDouble(tmp2 &lt;&lt; 32);
}</pre>
<p>Now simplify <tt>tmp2</tt> calculation:</p>
<ol>
<li>The original formula
<pre>tmp2 = (1512775 * (x - 1072632447) / 1512775 * b + (1072693248 - 60801))</pre>
<li>We can drop the factor <tt>1512775</tt>
<pre>tmp2 = (x - 1072632447) * b + (1072693248 - 60801)</pre>
<li>And finally, calculate the substraction
<pre>tmp2 = b * (x - 1072632447) + 1072632447</pre>
</ol>
<h2>The Result</h2>
<p>That&#8217;s it! Add some casts, and the complete function is the same as above.</p>
<pre class="brush: java;">public static double pow(final double a, final double b) {
    final int tmp = (int) (Double.doubleToLongBits(a) &gt;&gt; 32);
    final int tmp2 = (int) (b * (tmp - 1072632447) + 1072632447);
    return Double.longBitsToDouble(((long) tmp2) &lt;&lt; 32);
}</pre>
<p>This concludes my little tutorial on microoptimization of the pow() function. If you have come this far, I congratulate your presistence <img src='http://martin.ankerl.com/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
<p><strong>UPDATE</strong> Recently there several other approximative <tt>pow</tt> calculation methods have been developed, here are some others that I have found through <a href="http://www.reddit.com/r/programming/comments/8kftl/fast_pow_approximation_in_java_and_c/">reddit</a>:</p>
<ul>
<li><a href="http://www.hxa.name/articles/content/fast-pow-adjustable_hxa7241_2007.html">Fast pow() With Adjustable Accuracy</a> &#8212; This looks quite a bit more sophisticated and precise than my approximation. Written in C and for float values. A Java port should not be too difficult.
</li>
<li><a href="http://jrfonseca.blogspot.com/2008/09/fast-sse2-pow-tables-or-polynomials.html">Fast SSE2 pow: tables or polynomials?</a> &#8212; Uses <a href="http://en.wikipedia.org/wiki/Streaming_SIMD_Extensions">SSE </a> operation and seems to be a bit faster than the table approach from the link above with the potential to scale better when due to less cache usage.
</li>
</ul>
<p>Please post what you think about this!</p>
<div style='clear:both'></div><img src="http://martin.ankerl.com/?ak_action=api_record_view&id=96&type=feed" alt="" />]]></content:encoded>
			<wfw:commentRss>http://martin.ankerl.com/2007/10/04/optimized-pow-approximation-for-java-and-c-c/feed/</wfw:commentRss>
		<slash:comments>26</slash:comments>
		</item>
		<item>
		<title>Javadoc Search Engine Updated</title>
		<link>http://martin.ankerl.com/2007/08/22/javadoc-search-engine-updated/</link>
		<comments>http://martin.ankerl.com/2007/08/22/javadoc-search-engine-updated/#comments</comments>
		<pubDate>Wed, 22 Aug 2007 09:01:03 +0000</pubDate>
		<dc:creator>Martin Ankerl</dc:creator>
				<category><![CDATA[coding]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[news]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[google]]></category>
		<category><![CDATA[jdk]]></category>
		<category><![CDATA[search engine]]></category>

		<guid isPermaLink="false">http://martin.ankerl.com/?p=93</guid>
		<description><![CDATA[The Javadoc Search Engine now searches JDK 7 too: Go here: javadoc.ankerl.com It&#8217;s still a draft, so the documentation is surely subject to change. You can also use the search directly from here: happy hacking!]]></description>
			<content:encoded><![CDATA[<p>The <a href="http://javadoc.ankerl.com/">Javadoc Search Engine</a> now searches <a href="https://jdk7.dev.java.net/">JDK 7</a> too:</p>
<ul>
<li>Go here: <a href="http://javadoc.ankerl.com/">javadoc.ankerl.com</a></li>
</ul>
<p>It&#8217;s still a draft, so the documentation is surely subject to change. You can also use the search directly from here:<br />
<!-- Google CSE Search Box Begins  --></p>
<form id="searchbox_006156709672261707051:trd_lbkwu2y" action="http://www.google.com/cse">
<input type="hidden" name="cx" value="006156709672261707051:trd_lbkwu2y" />
<input type="hidden" name="cof" value="FORID:1" />
<input name="q" type="text" size="40" />
<input type="submit" name="sa" value="Search" />
  </form>
<p>  <script type="text/javascript" src="http://www.google.com/coop/cse/brand?form=searchbox_006156709672261707051%3Atrd_lbkwu2y"></script><br />
<!-- Google CSE Search Box Ends --><br />
happy hacking!</p>
<div style='clear:both'></div><img src="http://martin.ankerl.com/?ak_action=api_record_view&id=93&type=feed" alt="" />]]></content:encoded>
			<wfw:commentRss>http://martin.ankerl.com/2007/08/22/javadoc-search-engine-updated/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Ajax Dojo Comet Tutorial</title>
		<link>http://martin.ankerl.com/2007/08/21/ajax-dojo-comet-tutorial/</link>
		<comments>http://martin.ankerl.com/2007/08/21/ajax-dojo-comet-tutorial/#comments</comments>
		<pubDate>Tue, 21 Aug 2007 12:41:22 +0000</pubDate>
		<dc:creator>Martin Ankerl</dc:creator>
				<category><![CDATA[ajax]]></category>
		<category><![CDATA[coding]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[tutorial]]></category>
		<category><![CDATA[videos]]></category>
		<category><![CDATA[comet]]></category>
		<category><![CDATA[dojo]]></category>
		<category><![CDATA[howto]]></category>

		<guid isPermaLink="false">http://martin.ankerl.com/?p=92</guid>
		<description><![CDATA[EDIT: This tutorial is for an old version of dojo / comet, and it will not work in a recent version! Markus Holzmann, an intern at Profactor of my fellow colleague Philipp Hartl, had the opportunity to experiment with Ajax during his job. He wrote a tutorial about how to push events from the server [...]]]></description>
			<content:encoded><![CDATA[<p><strong>EDIT</strong>: This tutorial is for an old version of dojo / comet, and it will not work in a recent version!</p>
<p>Markus Holzmann, an intern at <a href="http://www.profactor.at/">Profactor</a> of my fellow colleague <a href="http://leanaustria.net/">Philipp Hartl</a>, had the opportunity to experiment with <a href="http://en.wikipedia.org/wiki/Ajax_(programming)">Ajax</a> during his job. He wrote a tutorial about how to push events from the server to the client. For example, display popup messages on all browsers at the same time (see screencast in <a href="/files/hello_comet.html" target="_blank">full resolution here</a>):<br />
<center><br />
<a href="/files/hello_comet.html" target="_blank">  <object width="400" height="317"><param name="wmode" value="transparent"></param>
    <embed src="/files/Hello_Comet.swf" wmode="transparent" width="401" height="317" type="application/x-shockwave-flash"></embed></object><br />
</a><br />
</center><br />
Read on how Markus did this:</p>
<p><span id="more-92"></span></p>
<h1>Cometd Hello World</h1>
<p>
I&#8217;ve read Chris Bucchere&#8217;s <a href="http://thebdgway.blogspot.com/2006/11/say-hello-world-to-comet.html">Say Hello World to Comet</a> and built an application based on this using a more current version of <a href="http://www.mortbay.org/">Jetty</a> (version <a href="http://dist.codehaus.org/jetty/jetty-6.1.5/">6.1.5</a>) which I embedded into a <a href="http://tomcat.apache.org/">Tomcat</a> v5.5 Server. For the developing I used <a href="http://www.eclipse.org/">Eclipse</a> 3.2.</p>
<p><h1>Start your Engines</h1>
<p>At first you have to get the server running. As I mentioned I embedded Jetty into a Tomcat server. Therefore you have configure the libraries:</p>
<ol>
<li>Add the packages <tt>org.mortbay.cometd</tt> and <tt>dojox.cometd</tt> to your source folder and delete the <tt>client</tt> package in the <tt>org.mortbay.cometd</tt> package.</li>
<li>Add <tt>jetty-util-6.1.5.jar</tt>, <tt>jetty-6.1.5.jar</tt> and <tt>servlet-api-2.5-6.1.5.jar</tt> to your build path.</li>
<li>Copy the <tt>jetty-util-6.1.5.jar</tt> file into the <tt>/lib</tt> folder in the <tt>WEB-INF</tt> directory.</li>
</ol>
<p>Replace the existing servlets in your web.xml &#8211; file in the WEB-INF &#8211; folder with the following servlets:</p>
<pre>&lt;servlet&gt;
  &lt;servlet-name&gt;cometd&lt;/servlet-name&gt;
  &lt;servlet-class&gt;org.mortbay.cometd.continuation.ContinuationCometdServlet&lt;/servlet-class&gt;
  &lt;load-on-startup&gt;1&lt;/load-on-startup&gt;
&lt;/servlet&gt;
&lt;servlet-mapping&gt;
  &lt;servlet-name&gt;cometd&lt;/servlet-name&gt;
  &lt;url-pattern&gt;/cometd/*&lt;/url-pattern&gt;
 &lt;/servlet-mapping&gt;</pre>
<p>For the project I used the <a href="http://dojotoolkit.org/">dojo toolkit</a> (version 0.4.3) which has an integrated <a href="http://www.cometd.com/">COMETd</a> class that makes it easy to build comet projects. <a href="http://download.dojotoolkit.org/release-0.4.3/dojo-0.4.3-ajax.tar.gz">Download it</a> and add it to your <tt>WebContent</tt> folder.</p>
<p>
When you&#8217;ve done all this, the hardest piece of work for this program is already done.</p>
<h1>Hack the Code</h1>
<p>Now you can implement the code for the client side: You need a HTML file with a button on it. The code for this looks like this (<a href="/files/hello_comet_test.html">download</a>):</p>
<pre>&lt;html&gt;
  &lt;head&gt;
    &lt;script type=&quot;text/javascript&quot; src=&quot;../dojo.js&quot;&gt;&lt;/script&gt;
    &lt;script type=&quot;text/javascript&quot;&gt;<b>
      dojo.require(&quot;dojo.io.cometd&quot;);

      cometd.init({}, &quot;cometd&quot;);

      cometd.subscribe(&quot;/hello/world&quot;, false, &quot;publishHandler&quot;);

      publishHandler = function(msg) {
        alert(msg.data.test);
      }</b>
    &lt;/script&gt;
  &lt;/head&gt;
  &lt;body&gt;
    &lt;input type=&quot;button&quot;
       onclick=&quot;<b>cometd.publish('/hello/world', { test: 'hello world' } )</b>&quot;
       value=&quot;Click Me!&quot;&gt;
  &lt;/body&gt;
&lt;/html&gt;</pre>
<p>Line by line, the above bold code works like this:</p>
<ol>
<li>In the line
<pre>&lt;script type="text/javascript" src="../dojo.js"&gt;&lt;/script&gt;</pre>
<p> you integrate the dojo toolkit into the project.</p>
<li>To activate the cometd class of dojo:
<pre>dojo.require("dojo.io.cometd");</pre>
<li>Connect the server with the client:
<pre>cometd.init({}, "cometd");</pre>
<li>Here we say what to do when there is a subscribe event:
<pre>cometd.subscribe("/hello/world", false, "publishHandler");</pre>
<li>Last but not least, the <tt>publishHandler</tt> function serves as the callback function, which uses <tt>alert</tt> to show a simple message box:
<pre>publishHandler = function(msg) {
  alert(msg.data.test);
}</pre>
</ol>
<h1>Give it a Try</h1>
<p>When you load the HTML file now, you can click on the button and an alert box saying <i>hello world</i> will appear:</p>
<p>
<center><img src="/files/helloworld.png" width="324" height="124" /></center></p>
<p>
The reason for this is that when you click the code
<pre>cometd.publish('/hello/world', { test: 'hello world' } )</pre>
<p> is executed which publishes a text on the channel with the id <tt>/hello/world</tt>.</p>
<p>
The funny thing is that this is able to run on any number of browsers. Everytime when a client clicks the button, on <i>all</i> browsers that view this page the alert box is shown. (See screencast above).</p>
<h1>Pushing Data from Server to Client</h1>
<p>You can also add serverside code to trigger an event. I wrote a JSP file with the following code:</p>
<pre>&lt;%@page import="java.util.*"%&gt;
&lt;%@page import="dojox.cometd.*" %&gt;
&lt;%
Bayeux b = (Bayeux)getServletContext().getAttribute(Bayeux.DOJOX_COMETD_BAYEUX);
Channel c = b.getChannel("/hello/world",false);

Map&lt;String,Object&gt; message = new HashMap&lt;String,Object&gt;();
message.put("test", "jsp: hello world");

c.publish(b.newClient("server_user",null),message, "new server message");
%&gt;</pre>
<p>When this page is loaded, an alert popup appears at the page saying <i>jsp: hello world</i>.</p>
<p>That&#8217;s it. Happy hacking!</p>
<div style='clear:both'></div><img src="http://martin.ankerl.com/?ak_action=api_record_view&id=92&type=feed" alt="" />]]></content:encoded>
			<wfw:commentRss>http://martin.ankerl.com/2007/08/21/ajax-dojo-comet-tutorial/feed/</wfw:commentRss>
		<slash:comments>27</slash:comments>
		</item>
		<item>
		<title>Java Developer Kit (JDK) Search Engine</title>
		<link>http://martin.ankerl.com/2007/07/20/java-developer-kit-jdk-search-engine/</link>
		<comments>http://martin.ankerl.com/2007/07/20/java-developer-kit-jdk-search-engine/#comments</comments>
		<pubDate>Fri, 20 Jul 2007 19:31:06 +0000</pubDate>
		<dc:creator>Martin Ankerl</dc:creator>
				<category><![CDATA[java]]></category>
		<category><![CDATA[news]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[google]]></category>
		<category><![CDATA[jdk]]></category>
		<category><![CDATA[search engine]]></category>

		<guid isPermaLink="false">http://martin.ankerl.com/?p=91</guid>
		<description><![CDATA[Thanks to Google Co-op I have just created a new search engine that searches the JDK documentation. It is quite convenient because you can use the labels to choose which version you like to see: http://javadoc.ankerl.com/ Happy googling.]]></description>
			<content:encoded><![CDATA[<p>Thanks to <a href="http://www.google.com/coop/">Google Co-op</a> I have just created a new search engine that searches the JDK documentation. It is quite convenient because you can use the labels to choose which version you like to see:</p>
<ul>
<li><a href="http://javadoc.ankerl.com/">http://javadoc.ankerl.com/</a></li>
</ul>
<p>Happy googling.</p>
<div style='clear:both'></div><img src="http://martin.ankerl.com/?ak_action=api_record_view&id=91&type=feed" alt="" />]]></content:encoded>
			<wfw:commentRss>http://martin.ankerl.com/2007/07/20/java-developer-kit-jdk-search-engine/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Exponential Functions: Benchmarks, 8 Times Faster Math.pow()</title>
		<link>http://martin.ankerl.com/2007/02/12/exponential-functions-benchmarks-11-times-faster-mathpow/</link>
		<comments>http://martin.ankerl.com/2007/02/12/exponential-functions-benchmarks-11-times-faster-mathpow/#comments</comments>
		<pubDate>Mon, 12 Feb 2007 15:26:53 +0000</pubDate>
		<dc:creator>Martin Ankerl</dc:creator>
				<category><![CDATA[coding]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[news]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[tricks]]></category>
		<category><![CDATA[approximation]]></category>
		<category><![CDATA[benchmark]]></category>
		<category><![CDATA[math]]></category>
		<category><![CDATA[pow]]></category>

		<guid isPermaLink="false">http://martin.ankerl.com/?p=83</guid>
		<description><![CDATA[I have updated the code for the Math.pow() approximation, now it is 11 times faster on my Pentium IV. Read Optimized Exponential Functions for Java for more information. Now I can also give you some benchmarks: Benchmarks Math.log() &#8212; 11.7 times faster 6.233 sec, Math.log(x) 0.531 sec, 6*(x-1)/ (x + 1 + 4*(Math.sqrt(x))) Math.exp() &#8212; [...]]]></description>
			<content:encoded><![CDATA[<p>I have updated the code for the <tt>Math.pow()</tt> approximation, now it is 11 times faster on my Pentium IV. Read <a href="http://martin.ankerl.com/2007/02/11/optimized-exponential-functions-for-java/">Optimized Exponential Functions for Java  </a> for more information. Now I can also give you some benchmarks:<br />
<span id="more-83"></span></p>
<h1>Benchmarks</h1>
<h4>Math.log() &#8212; 11.7 times faster</h4>
<ul>
<li>6.233 sec, Math.log(x)</li>
<li>0.531 sec, 6*(x-1)/ (x + 1 + 4*(Math.sqrt(x)))</li>
</ul>
<h4>Math.exp() &#8212; 5.3 times faster</h4>
<ul>
<li>5.920 sec, Math.exp(x)</li>
<li>1.108 sec, exp optimized with IEEE 754 trick</li>
</ul>
<h4>Math.pow() &#8212; 8.7 times faster</h4>
<ul>
<li>15.967 sec, Math.pow(a, b)</li>
<li>11.014 sec, e^(b * log(a))</li>
<li>7.607 sec, e^(b * log(a)) + IEEE 754 trick</li>
<li>2.109 sec, e^(b * log(a)) + IEEE 754 trick + LOG approximation</li>
<li>1.827 sec, simplified everything, see <a href="http://martin.ankerl.com/2007/02/11/optimized-exponential-functions-for-java/">Optimized Exponential Functions for Java  </a></li>
</ul>
<p>For accurate measurements I have performed each calculation 20 million times and used a random number generator to prevent optimization. I have measured the overhead of iterating and random number generation (3.969 sec) and substracted this from each measurement so that only the pure functional code is measured.</p>
<div style='clear:both'></div><img src="http://martin.ankerl.com/?ak_action=api_record_view&id=83&type=feed" alt="" />]]></content:encoded>
			<wfw:commentRss>http://martin.ankerl.com/2007/02/12/exponential-functions-benchmarks-11-times-faster-mathpow/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Optimized Exponential Functions for Java</title>
		<link>http://martin.ankerl.com/2007/02/11/optimized-exponential-functions-for-java/</link>
		<comments>http://martin.ankerl.com/2007/02/11/optimized-exponential-functions-for-java/#comments</comments>
		<pubDate>Sun, 11 Feb 2007 22:20:14 +0000</pubDate>
		<dc:creator>Martin Ankerl</dc:creator>
				<category><![CDATA[coding]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[news]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[tricks]]></category>

		<guid isPermaLink="false">http://martin.ankerl.com/?p=82</guid>
		<description><![CDATA[Usually microoptimization is only done in C or C++, but it works quite well in Java too. For a project I needed very fast log() and exp() calculations, and Java&#8217;s Math.log() and Math.exp() just doesn&#8217;t cut it. After a bit of research I have found the following approximations that are good enough for me: UPDATE [...]]]></description>
			<content:encoded><![CDATA[<p>Usually microoptimization is only done in C or C++, but it works quite well in Java too. For a project I needed very fast <tt>log()</tt> and <tt>exp()</tt> calculations, and Java&#8217;s <tt>Math.log()</tt> and <tt>Math.exp()</tt> just doesn&#8217;t cut it. After a bit of research I have found the following approximations that are good enough for me:<br />
<span id="more-82"></span></p>
<p><strong>UPDATE</strong> This pow() approximation is obsolete. <a href="http://martin.ankerl.com/2007/10/04/optimized-pow-approximation-for-java-and-c-c/">I have a much faster and more accurate approximation version here</a>.</p>
<h1>Fast Exponential Function in Java</h1>
<p>The paper &#8220;<a href="http://citeseer.ist.psu.edu/schraudolph98fast.html">A Fast, Compact Approximation of the Exponential Function</a>&#8221; describes a C macro that does a good job at exploiting the IEEE 754 floating-point representation to calculate e^x. I have transformed the macro into Java code:</p>
<pre class="brush: java;">public static double exp(double val) {
    final long tmp = (long) (1512775 * val + 1072632447);
    return Double.longBitsToDouble(tmp &lt;&lt; 32);
}</pre>
<p>This code is <strong>5.3 times</strong> faster than <tt>Math.exp()</tt> on my computer. Beware that it is only an approximation, for a detailed analysis read <a href="http://citeseer.ist.psu.edu/schraudolph98fast.html">the  paper</a>.</p>
<h1>Fast Natural Logarithm in Java</h1>
<p>I have found the following approximation <a href="http://www.dattalo.com/technical/theory/logs.html">here</a>, and there is not much information about it except that it is called &#8220;Borchardt&#8217;s Algorithm&#8221; and it is from the book &#8220;Dead Reconing: Calculating without instruments&#8221;. The approximation is <strong>not very good</strong> (some might say very bad&#8230;), it gets worse the larger the values are. But the approximation is also a monotonic, slowly increasing function, which is good enough for my use case.</p>
<pre class="brush: java;">public static double log(double x) {
    return 6 * (x - 1) / (x + 1 + 4 * (Math.sqrt(x)));
}</pre>
<p>This approximation is <strong>11.7 times</strong> faster than <tt>Math.log()</tt>.</p>
<h1>Fast Power Calculation</h1>
<p>Equiped with these optimized functions, it is possible to do several other optimizations. For example you can replace</p>
<pre>Math.pow(a, b)</pre>
<p>with</p>
<pre>Math.exp(b * Math.log(a))</pre>
<p>And then use the approximation functions for a highly optimized pow calculation. You can even combine the calculations and simplify it into this:</p>
<pre class="brush: java;">public static double pow(double a, double b) {
    final long tmp = (long) (9076650 * (a - 1) / (a + 1 + 4 * (Math.sqrt(a))) * b + 1072632447);
    return Double.longBitsToDouble(tmp &lt;&lt; 32);
}</pre>
<p>This is <strong>8.7 times</strong> faster than the <tt>Math.pow(a, b)</tt>.</p>
<h1>Accuracy</h1>
<p>The above functions are very inaccurate, especially the log calculation. So before you use this code you have to test it if the approximation is good enough for you!</p>
<p>Have fun</p>
<div style='clear:both'></div><img src="http://martin.ankerl.com/?ak_action=api_record_view&id=82&type=feed" alt="" />]]></content:encoded>
			<wfw:commentRss>http://martin.ankerl.com/2007/02/11/optimized-exponential-functions-for-java/feed/</wfw:commentRss>
		<slash:comments>10</slash:comments>
		</item>
		<item>
		<title>Open Source Search Engine</title>
		<link>http://martin.ankerl.com/2007/02/08/open-source-search-engine/</link>
		<comments>http://martin.ankerl.com/2007/02/08/open-source-search-engine/#comments</comments>
		<pubDate>Thu, 08 Feb 2007 08:52:45 +0000</pubDate>
		<dc:creator>Martin Ankerl</dc:creator>
				<category><![CDATA[coding]]></category>
		<category><![CDATA[freeware]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[news]]></category>
		<category><![CDATA[open source]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[ruby]]></category>
		<category><![CDATA[coop]]></category>
		<category><![CDATA[google]]></category>
		<category><![CDATA[search engine]]></category>

		<guid isPermaLink="false">http://martin.ankerl.com/?p=81</guid>
		<description><![CDATA[Give it a try: http://opensource.ankerl.com/ Thanks to Google&#8217;s new co-op feature I was able to create a customized search engine for open source software. It contains a lot of hosting sites like sourceforge.net and rubyforge.org, but also lots of other sites like eclipse.org, kernel.org, apache.org and many many more. Click to add it to your [...]]]></description>
			<content:encoded><![CDATA[<p>Give it a try:</p>
<p><center><br />
<a href="http://opensource.ankerl.com/">http://opensource.ankerl.com/</a></p>
<form id="searchbox_006156709672261707051:fmqpupckn3m" action="http://www.google.com/cse">
<input type="hidden" name="cx" value="006156709672261707051:fmqpupckn3m" />
<input name="q" type="text" size="40" />
<input type="submit" name="sa" value="Search" />
<input type="hidden" name="cof" value="FORID:1" /></form>
<p><script type="text/javascript" src="http://www.google.com/coop/cse/brand?form=searchbox_006156709672261707051%3Afmqpupckn3m"></script><br />
</center></p>
<p>Thanks to Google&#8217;s new <a href="http://www.google.com/coop/">co-op</a> feature I was able to create a customized search engine for open source software. It contains a lot of hosting sites like <a href="http://sourceforge.net/">sourceforge.net</a> and <a href="http://rubyforge.org/">rubyforge.org</a>, but also lots of other sites like <a href="http://www.eclipse.org/">eclipse.org</a>, <a href="http://kernel.org/">kernel.org</a>, <a href="http://apache.org/">apache.org</a> and many many more.</p>
<p>Click <a href="http://fusion.google.com/add?moduleurl=http%3A%2F%2Fwww.google.com%2Fcoop/api/006156709672261707051/cse/fmqpupckn3m/gadget"><img src="http://buttons.googlesyndication.com/fusion/add.gif" width="104" height="17" border="0" alt="Add to Google" /></a> to add it to your customized Google homepage</p>
<div style='clear:both'></div><img src="http://martin.ankerl.com/?ak_action=api_record_view&id=81&type=feed" alt="" />]]></content:encoded>
			<wfw:commentRss>http://martin.ankerl.com/2007/02/08/open-source-search-engine/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
