<?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>Codng &#187; Java</title>
	<atom:link href="http://codng.com/category/java/feed" rel="self" type="application/rss+xml" />
	<link>http://codng.com</link>
	<description>Nerd is the new cool.</description>
	<lastBuildDate>Wed, 02 Dec 2009 21:39:46 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.2</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Naive Brainf**k to Java compiler</title>
		<link>http://codng.com/naive-brainfk-to-java-compiler</link>
		<comments>http://codng.com/naive-brainfk-to-java-compiler#comments</comments>
		<pubDate>Wed, 02 Dec 2009 20:02:03 +0000</pubDate>
		<dc:creator>juancn</dc:creator>
				<category><![CDATA[Compilers]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Miscellaneous]]></category>

		<guid isPermaLink="false">http://codng.com/?p=19</guid>
		<description><![CDATA[Some time ago the brainf**k language caught my eye (I still don&#8217;t feel comfortable spelling it right).
It&#8217;s a turing tarpit, but one not very complicated at that (for something more esoteric see Malbolge or Whitespace).
The language is very simple, it has eight instructions. So I had to write a compiler for it. It turns out [...]]]></description>
			<content:encoded><![CDATA[<p>Some time ago the <a href="http://en.wikipedia.org/wiki/Brainfuck">brainf**k</a> language caught my eye (I still don&#8217;t feel comfortable spelling it right).</p>
<p>It&#8217;s a <a href="http://en.wikipedia.org/wiki/Turing_tarpit">turing tarpit</a>, but one not very complicated at that (for something more esoteric see <a href="http://en.wikipedia.org/wiki/Malbolge">Malbolge</a> or <a href="http://en.wikipedia.org/wiki/Whitespace_(programming_language)">Whitespace</a>).</p>
<p>The language is very simple, it has eight instructions. So I had to write a compiler for it. It turns out to be quite easy to do:</p>
<pre class="brush: java;">
import static java.lang.System.out;

public class BrainFk
{
    public static void main(String[] args) {
        out.println(&quot;public class &quot; + args[0] + &quot;{&quot;);
        out.println(&quot;public static void main(String args[]) throws Throwable {&quot;);
        out.println(&quot;int[] memory = new int[30000];&quot;);
        out.println(&quot;int data = 0;&quot;);
        final String code = args[1];
        for(int i = 0; i &lt; code.length(); i++) {
            char c = code.charAt(i);
            switch(c) {
                case '&gt;':
                    out.println(&quot;++data;&quot;);
                    break;
                case '&lt;':
                    out.println(&quot;--data;&quot;);
                    break;
                case '+':
                    out.println(&quot;++memory[data];&quot;);
                    break;
                case '-':
                    out.println(&quot;--memory[data];&quot;);
                    break;
                case '.':
                    out.println(&quot;System.out.print((char)(0xFF &amp; memory[data]));&quot;);
                    break;
                case ',':
                    out.println(&quot;memory[data] = System.in.read();&quot;);
                    break;
                case '[':
                    out.println(&quot;while(memory[data] != 0) {&quot;);
                    break;
                case ']':
                    out.println(&quot;}&quot;);
                    break;
            }
        }
        out.println(&quot;}}&quot;);
    }
}
</pre>
<p>You can use it to compile the hello world sample from the Wikipedia page:</p>
<pre class="brush: plain; light: true;">
~&gt;java BrainFk Hello &quot;++++++++++[&gt;+++++++&gt;++++++++++&gt;+++&gt;+&lt;&lt;&lt;&lt;-]&gt;++.&gt;+.+++++++..+++.&gt;++.&lt;&lt;+++++++++++++++.&gt;.+++.------.--------.&gt;+.&gt;.&quot; &gt; Hello.java
~&gt;javac Hello.java
~&gt;java Hello
Hello World!
</pre>
<p>Sometime I&#8217;ll have to post the Forth interpreter in Java I wrote (I know some might consider sacrilege to use both languages in the same sentence, but you can&#8217;t please everyone!).</p>
]]></content:encoded>
			<wfw:commentRss>http://codng.com/naive-brainfk-to-java-compiler/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Image Downscaling</title>
		<link>http://codng.com/image-downscaling</link>
		<comments>http://codng.com/image-downscaling#comments</comments>
		<pubDate>Fri, 02 Oct 2009 15:59:55 +0000</pubDate>
		<dc:creator>juancn</dc:creator>
				<category><![CDATA[Image Processing]]></category>
		<category><![CDATA[Java]]></category>

		<guid isPermaLink="false">http://codng.com/image-downscaling</guid>
		<description><![CDATA[A few days ago, a friend contacted me because he needed good image downscaling for a project he&#8217;s working on.
I remebered reading an article about the types of issues when downsampling an image (and specifically a difficult one). After a few tests, I settled for a gaussian pre-blur.
I think I got pretty good results:

Go to [...]]]></description>
			<content:encoded><![CDATA[<p>A few days ago, a friend contacted me because he needed good image downscaling for a project he&#8217;s working on.</p>
<p>I remebered reading <a href="http://www.xs4all.nl/~bvdwolf/main/foto/down_sample/down_sample.htm">an article</a> about the types of issues when downsampling an image (and specifically a difficult one). After a few tests, I settled for a gaussian pre-blur.</p>
<p>I think I got pretty good results:</p>
<p><a href='http://codng.com/wp-content/uploads/2009/10/downsampled.png' title='Downscaled image'><img src='http://codng.com/wp-content/uploads/2009/10/downsampled.png' alt='Downscaled image' /></a></p>
<p>Go to the <a href="http://www.xs4all.nl/~bvdwolf/main/foto/down_sample/down_sample.htm">original article</a> to get the source image.</p>
<p>The code also tries to fit and center the image in the target. That means it will return an image with the exact size you request. It will center and rescale the source image and leav transparent background for filler space.</p>
<pre class="brush: java;">
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.AffineTransform;
import java.awt.image.*;
import java.io.File;
import java.io.IOException;

public class FitImage {

    public static BufferedImage fitImage(final BufferedImage input, final int width, final int height) {
        final int inputWidth = input.getWidth();
        final int inputHeight = input.getHeight();

        final double hScale = width/(double)inputWidth;
        final double vScale = height/(double)inputHeight;

        final double scaleFactor = Math.min(hScale, vScale);

        //Create a temp image
        final BufferedImage temp = new BufferedImage(inputWidth,inputHeight, BufferedImage.TYPE_INT_ARGB);

        if(scaleFactor &lt; 1) {
            //Create a gaussian kernel with a raduis proportional to the scale factor and convolve it with the image
            final Kernel kernel = make2DKernel((float) (1 / scaleFactor));
            final BufferedImageOp op = new ConvolveOp(kernel);
            op.filter(input, temp);
        } else {
            temp.createGraphics().drawImage(input, null, 0,0);
        }

        final BufferedImage output = new BufferedImage(width,height, BufferedImage.TYPE_INT_ARGB);
        final Graphics2D g = output.createGraphics();
        g.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION, RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY);
        g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
        g.setRenderingHint(RenderingHints.KEY_DITHERING, RenderingHints.VALUE_DITHER_ENABLE);
        g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

        final int xOffset = (int) Math.max(0, (width - inputWidth * scaleFactor) / 2);
        final int yOffset = (int) Math.max(0, (height - inputHeight * scaleFactor) / 2);
        final AffineTransform scaleInstance = AffineTransform.getScaleInstance(scaleFactor, scaleFactor);
        final AffineTransformOp transformOp = new AffineTransformOp(scaleInstance, AffineTransformOp.TYPE_BICUBIC);
        g.drawImage(temp, transformOp, xOffset, yOffset);
        return output;
    }

    public static Kernel make2DKernel(float radius) {
        final int r = (int)Math.ceil(radius);
        final int size = r*2+1;
        float standardDeviation = radius/3; //Guess a standard dev from the radius

        final float center = (float) (size/2);
        float sigmaSquared = standardDeviation * standardDeviation;

        final float[] coeffs = new float[size*size];

        for(int x = 0; x &lt; size; x++ ) {
            for(int y = 0; y &lt; size; y++ ) {
                double distFromCenterSquared = ( x - center ) * (x - center ) + ( y - center ) * ( y - center );
                double baseEexponential = Math.pow( Math.E, -distFromCenterSquared / ( 2.0f * sigmaSquared ) );
                coeffs[y*size+x]= (float) (baseEexponential / (2.0f*Math.PI*sigmaSquared ));
            }
        }

        return new Kernel(size, size, coeffs);
    }

    public static void main(String[] args)
            throws IOException
    {
        BufferedImage out = fitImage(ImageIO.read(new File(&quot;Rings1.gif&quot;)), 200, 200);
        ImageIO.write(out, &quot;png&quot;, new File(&quot;test.png&quot;));
    }

}
</pre>
]]></content:encoded>
			<wfw:commentRss>http://codng.com/image-downscaling/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Juggling Chainsaws</title>
		<link>http://codng.com/juggling-chainsaws</link>
		<comments>http://codng.com/juggling-chainsaws#comments</comments>
		<pubDate>Wed, 06 Feb 2008 23:34:24 +0000</pubDate>
		<dc:creator>juancn</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Miscellaneous]]></category>

		<guid isPermaLink="false">http://codng.com/juggling-chainsaws</guid>
		<description><![CDATA[Andrew writes probably one of the funniest and most elocuent articles I&#8217;ve read about thread programming. His opening line:
 Writing multithreaded code is like juggling chainsaws; amazing when it works and truly sucky when it doesn&#8217;t.
Truly summarizes the feeling when you&#8217;ve had to deal with a multithreaded system. He argues that probably one of the most difficult thing to achieve is &#8220;avoiding doing nothing&#8221;. I agree with his [...]]]></description>
			<content:encoded><![CDATA[<p><a HREF="http://thecodist.com/fiche/thecodist/article/writing-multithreaded-code-is-like-juggling-chainsaws">Andrew writes</a> probably one of the funniest and most elocuent articles I&#8217;ve read about thread programming. His opening line:</p>
<blockquote><p> <em>Writing multithreaded code is like juggling chainsaws; amazing when it works and truly sucky when it doesn&#8217;t.</em></p></blockquote>
<p>Truly summarizes the feeling when you&#8217;ve had to deal with a multithreaded system. He argues that probably one of the most difficult thing to achieve is &#8220;avoiding doing nothing&#8221;. I agree with his thoughts in the sense that if you are even considering multithreading something, you are trying to achieve maximum utilization (i.e. not wasting resources). But I&#8217;m not sure that getting maximum utilization is the hardest part by itself.</p>
<p>Besides the usual problems, like avoiding deadlocks or protecting shared data, I always found that the hardest part was, to paraphrase <a HREF="http://thecodist.com/fiche/thecodist/article/writing-multithreaded-code-is-like-juggling-chainsaws">Andrew</a>, &#8220;avoid doing something&#8221;.</p>
<p>What I mean is that in multithreaded applications (it also applies to distributed applications), probably the hardest part is coming up with ways to avoid needing synchronization.</p>
<p>At least in my experience, figuring out ways to make the system exhibit consistent and predictable behavior without relying on atomicity, has always been the part that most of the design effort is invested in, and if done properly, where the greatest gains in scalability is achieved.</p>
<p>Take for example the <a HREF="http://labs.google.com/papers/gfs.html">Google File System</a>, a massive, multi-petabyte storage filesystem. It is designed to work on clusters of several thousand machines, distibuted across several datacenters (even on different countries).</p>
<p>To achieve the expected performance, they had to throw away the usual file semantics, and think completely out-of-the box. But don&#8217;t take my word for it, go, <a HREF="http://labs.google.com/papers/gfs-sosp2003.pdf">fetch the paper</a> (if you haven&#8217;t already done so), and read it yourself.</p>
]]></content:encoded>
			<wfw:commentRss>http://codng.com/juggling-chainsaws/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>A better way to do concurrent programming (Part 1)</title>
		<link>http://codng.com/a-better-way-to-do-concurrent-programming-part-1</link>
		<comments>http://codng.com/a-better-way-to-do-concurrent-programming-part-1#comments</comments>
		<pubDate>Mon, 05 Nov 2007 22:44:38 +0000</pubDate>
		<dc:creator>juancn</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Miscellaneous]]></category>

		<guid isPermaLink="false">http://codng.com/a-better-way-to-do-concurrent-programming-part-1</guid>
		<description><![CDATA[A while ago (I think round 2005), some guys from Microsoft Research published a paper about Composable Memory Transactions.
After reading it, I began doing a small implementation in Java (quite ugly, btw), and I was astonished by the possibilities. So quite naturally (being the geek I am), I started toying with the idea of implementing a set of extensions for Java.
In this and other posts, I&#8217;ll try to make an introduction [...]]]></description>
			<content:encoded><![CDATA[<p>A while ago (I think round 2005), some guys from Microsoft Research <a HREF="http://research.microsoft.com/~simonpj/papers/stm/">published a paper</a> about Composable Memory Transactions.</p>
<p>After reading it, I began doing a small implementation in Java (quite ugly, btw), and I was astonished by the possibilities. So quite naturally (being the geek I am), I started toying with the idea of implementing a set of extensions for Java.</p>
<p>In this and other posts, I&#8217;ll try to make an introduction to the basic idea. Note that I will probably change existing posts quite often to correct mistakes or ommissions. In this post I&#8217;ll focus on an overview of the basic idea, in a future post I&#8217;ll address composition of transactions (the <em>C</em> in <em>CMT</em>), static checking for side effects, and alternatives to implement the runtime part of this. If you&#8217;re really curious, I recommend reading the original paper.</p>
<p>The gist of the idea is to replace common locking based semantics with in-memory transactions, so instead of writing complex locking semantics, you rely on optimistic locking handled by the runtime.</p>
<p>The following example shows how a producer-consumer problem can be solved with a queue of fixed size using Java with CMT:</p>
<pre>
<strong>public</strong> class BufferedQueue {
    <strong>private</strong> LinkedList list;
    <strong>public</strong> BufferedQueue() {
        list = new LinkedList();
    }
    <strong>public</strong> Object consume() {
        Object value;
        <strong>atomic</strong> {
            <strong>if</strong>(list.isEmpty()) {
                <strong>retry</strong>;
            }
            value = list.removeFirst();
        }
        <strong>return</strong> value;
    }
    <strong>public</strong> <strong>void</strong> produce(Object value) {
        <strong>atomic</strong> {
            <strong>if</strong>(list.size() &gt; 10) {
                <strong>retry</strong>;
            }
            list.add(value);
        }
    }
    <strong>public</strong> Object peek() {
        Object value;
        <strong>atomic</strong> {
            <strong>if</strong>(list.isEmpty()) {
                <strong>retry</strong>;
            }
            value = list.getFirst();
        } <strong>else</strong> {
            value = null;
        }
        <strong>return</strong> value;
    }
}</pre>
<p>Take a look at two keywords: <strong>atomic</strong> and <strong>retry</strong></p>
<p>The <strong>atomic</strong> keyword demarcates a transaction. That means that this block is all-or-nothing (well get to the <strong>else</strong> later). For example let&#8217;s take a closer look at the <code>consume</code> method.</p>
<pre>
<strong>public</strong> Object consume() {
    Object value;
    <strong>atomic</strong> {
        if(list.isEmpty()) {
            <strong>retry</strong>;
        }
        value = list.removeFirst();
    }
    <strong>return</strong> value;
}</pre>
<p>The <strong>atomic</strong> statement starts a transaction. In this transaction we first check to see if the list is empty. If it is, we issue a <strong>retry</strong> statement.<br />
The <strong>retry</strong> statement, rolls-back all changes and suspends the transaction until at least one of the fields used in the block (either directly or indirectly) is modified by another transaction committing. When this happens, the execution is restarted in a new transaction at the beginning of the enclosing atomic block.<br />
If this time the list is not empty, the first element is removed from the list, and the transaction is committed. If at the time of the commit there is a conflict with another transaction, the execution is rolled back and retried.</p>
<p>Note that it is very important that the atomic blocks do not have side-effects (such as creating files, etc.) outside of the control of the transaction manager.</p>
<p>(to be continued&#8230;)</p>
]]></content:encoded>
			<wfw:commentRss>http://codng.com/a-better-way-to-do-concurrent-programming-part-1/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>13949712720901ForOSX &#8211; Java for OSX</title>
		<link>http://codng.com/13949712720901forosx-java-for-osx</link>
		<comments>http://codng.com/13949712720901forosx-java-for-osx#comments</comments>
		<pubDate>Mon, 05 Nov 2007 21:26:56 +0000</pubDate>
		<dc:creator>juancn</dc:creator>
				<category><![CDATA[Java]]></category>

		<guid isPermaLink="false">http://codng.com/13949712720901forosx-java-for-osx</guid>
		<description><![CDATA[In a blog post henry resumes the sad state of affairs of Java in OSX.
So here I am, joining this campaign by posting this entry in protest! Apple, please don&#8217;t let us down!
]]></description>
			<content:encoded><![CDATA[<p>In a <a HREF="http://blogs.sun.com/bblfish/entry/vote_for_java6_on_leopard">blog post</a> henry resumes the sad state of affairs of Java in OSX.</p>
<p>So here I am, joining this campaign by posting this entry in protest! Apple, please don&#8217;t let us down!</p>
]]></content:encoded>
			<wfw:commentRss>http://codng.com/13949712720901forosx-java-for-osx/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
