<?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"
	>

<channel>
	<title>hemju’s code {}</title>
	<atom:link href="http://juskewycz.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://juskewycz.com</link>
	<description></description>
	<pubDate>Fri, 21 Nov 2008 23:41:37 +0000</pubDate>
	<generator>http://wordpress.org/?v=2.6.3</generator>
	<language>en</language>
			<item>
		<title>Ruby on Rails 2.2</title>
		<link>http://juskewycz.com/2008/11/ruby-on-rails-22/</link>
		<comments>http://juskewycz.com/2008/11/ruby-on-rails-22/#comments</comments>
		<pubDate>Fri, 21 Nov 2008 23:37:01 +0000</pubDate>
		<dc:creator>heli</dc:creator>
		
		<category><![CDATA[heli's blog]]></category>

		<category><![CDATA[JRuby]]></category>

		<category><![CDATA[RoR]]></category>

		<category><![CDATA[Web Development]]></category>

		<guid isPermaLink="false">http://juskewycz.com/?p=132</guid>
		<description><![CDATA[What a week, first NetBeans 6.5 came out and now Rails 2.2 is out. The new version has a couple of interesting new things like internationalization out-of-the-box, thread-safe!, and JRuby becomes more and more a serious platform for Rails. Just great news, I guess I will spend the weekend Rails diggin &#8230; Read more about [...]]]></description>
			<content:encoded><![CDATA[<p>What a week, first <a href="http://juskewycz.com/2008/11/netbeans-65-final/">NetBeans 6.5</a> came out and now Rails 2.2 is out. The new version has a couple of interesting new things like internationalization out-of-the-box, thread-safe!, and JRuby becomes more and more a serious platform for Rails. Just great news, I guess I will spend the weekend Rails diggin &#8230; Read more about the new features <a href="http://weblog.rubyonrails.org/2008/11/18/new-rails-2-2-i18n-defaults">here</a>.</p>
<p><a href="http://guides.rubyonrails.org/">Ruby on Rails guides</a></p>
<p><a href="http://rails-i18n.org/wiki">Rails i18n</a> and <a href="http://groups.google.com/group/rails-i18n">Google Group</a></p>
]]></content:encoded>
			<wfw:commentRss>http://juskewycz.com/2008/11/ruby-on-rails-22/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Smush.it! Use it!</title>
		<link>http://juskewycz.com/2008/11/smushit-use-it/</link>
		<comments>http://juskewycz.com/2008/11/smushit-use-it/#comments</comments>
		<pubDate>Fri, 21 Nov 2008 17:51:49 +0000</pubDate>
		<dc:creator>heli</dc:creator>
		
		<category><![CDATA[heli's blog]]></category>

		<category><![CDATA[Performance]]></category>

		<category><![CDATA[RoR]]></category>

		<category><![CDATA[Web Development]]></category>

		<guid isPermaLink="false">http://juskewycz.com/?p=127</guid>
		<description><![CDATA[I am kind of a performance geek, I like it lean and fast. Although I have to admit that in many cases optimization is not useful or not relevant (I learned a couple of lessons in this area), it is always interesting. As my focus more and more shifts to Web development, I am constantly [...]]]></description>
			<content:encoded><![CDATA[<p>I am kind of a performance geek, I like it lean and fast. Although I have to admit that in many cases optimization is not useful or not relevant (I learned a couple of lessons in this area), it is always interesting. As my focus more and more shifts to Web development, I am constantly looking for ways to speed up things. In fact I think Web development is one of the software areas where performance optimization is constantly neglected.</p>
<p>Images are a great portion of a website, they help to make it fancy and good looking. They also have great potential for optimization, to speed up your website and minimize you traffic. There are several ways to improve image size and , you don&#8217;t have to know them at all, just use <a href="http://smushit.com/">smush.it</a>! Smush.it is a tool from Yahoo performance team members that let you optimize your images on the fly. Normally I would now explain how to use the tool and so forth, but not smush.it. It is as simple as it can be. Just go to the website and get a free overhaul for your images. Oh and btw plans are to make the tool open source <img src='http://juskewycz.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> Love it</p>
]]></content:encoded>
			<wfw:commentRss>http://juskewycz.com/2008/11/smushit-use-it/feed/</wfw:commentRss>
		</item>
		<item>
		<title>NetBeans 6.5 final</title>
		<link>http://juskewycz.com/2008/11/netbeans-65-final/</link>
		<comments>http://juskewycz.com/2008/11/netbeans-65-final/#comments</comments>
		<pubDate>Fri, 21 Nov 2008 08:44:04 +0000</pubDate>
		<dc:creator>heli</dc:creator>
		
		<category><![CDATA[heli's blog]]></category>

		<category><![CDATA[NetBeans]]></category>

		<guid isPermaLink="false">http://juskewycz.com/?p=125</guid>
		<description><![CDATA[NetBeans 6.5 is available! I use 6.5 for 3 months now (beta testing &#8230;) and I have to say that 6.5 is quite a good release. Here is the official announcment with all the new stuff. There is also an introduction video online.
]]></description>
			<content:encoded><![CDATA[<p>NetBeans 6.5 is available! I use 6.5 for 3 months now (beta testing &#8230;) and I have to say that 6.5 is quite a good release. Here is the <a href="http://www.netbeans.org/servlets/NewsItemView?newsItemID=1313">official announcment</a> with all the new stuff. There is also an <a href="http://www.netbeans.org/kb/docs/ide/nb65-intro-screencast.html">introduction video</a> online.</p>
]]></content:encoded>
			<wfw:commentRss>http://juskewycz.com/2008/11/netbeans-65-final/feed/</wfw:commentRss>
		</item>
		<item>
		<title>TimeWhale Beta Registration</title>
		<link>http://juskewycz.com/2008/11/timewhale-beta-registration/</link>
		<comments>http://juskewycz.com/2008/11/timewhale-beta-registration/#comments</comments>
		<pubDate>Tue, 18 Nov 2008 14:29:21 +0000</pubDate>
		<dc:creator>heli</dc:creator>
		
		<category><![CDATA[heli's blog]]></category>

		<category><![CDATA[TimeWhale]]></category>

		<guid isPermaLink="false">http://juskewycz.com/?p=121</guid>
		<description><![CDATA[I am currently working on a product called TimeWhale. TimeWhale is an online time tracking service. Of course it (will) supports all kinds of devices (usual suspects like Mobile Devices, Web, Desktop, &#8230;). TimeWhale will be different to competitor services, e.g Basecamp, because its focus is only on time tracking without project management, collaboration, and [...]]]></description>
			<content:encoded><![CDATA[<p>I am currently working on a product called TimeWhale. TimeWhale is an online time tracking service. Of course it (will) supports all kinds of devices (usual suspects like Mobile Devices, Web, Desktop, &#8230;). TimeWhale will be different to competitor services, e.g <a href="http://www.basecamphq.com/" target="_blank">Basecamp</a>, because its focus is only on time tracking without project management, collaboration, and so forth. I think this clear focus allows TimeWhale to be a specialized and powerful tool, and yet have a lean and easy-to-use user interface. For user which need more, it will have an API to work with other products.</p>
<p>For those who are interested know, just visit <a href="http://www.timewhale.com">www.timewhale.com</a> and register for the launch announcement. Your email will be used to send you <strong>one email</strong> for the launch announcement and after that it is deleted, so no obligations and no spamming.</p>
]]></content:encoded>
			<wfw:commentRss>http://juskewycz.com/2008/11/timewhale-beta-registration/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Java Sources and Documentation under Mac for Eclipse/NetBeans</title>
		<link>http://juskewycz.com/2008/11/java-sources-and-documentation-under-mac-for-eclipsenetbeans/</link>
		<comments>http://juskewycz.com/2008/11/java-sources-and-documentation-under-mac-for-eclipsenetbeans/#comments</comments>
		<pubDate>Sun, 16 Nov 2008 13:36:26 +0000</pubDate>
		<dc:creator>heli</dc:creator>
		
		<category><![CDATA[heli's blog]]></category>

		<category><![CDATA[Eclipse]]></category>

		<category><![CDATA[Java]]></category>

		<category><![CDATA[Mac]]></category>

		<category><![CDATA[NetBeans]]></category>

		<guid isPermaLink="false">http://juskewycz.com/?p=106</guid>
		<description><![CDATA[A couple of days ago I received my new MacBook Pro! After some first struggles with Mac OS X and shortcuts, I am now starting to feel comfortable and I learn more and more each day. I was a 60 % Windows and 40 % Linux user and my forecast is that in one year [...]]]></description>
			<content:encoded><![CDATA[<p style="text-align: left;">A couple of days ago I received my <a href="http://juskewycz.com/wp-content/uploads/2008/11/mac_pro.jpg">new MacBook Pro</a>! After some first struggles with Mac OS X and shortcuts, I am now starting to feel comfortable and I learn more and more each day. I was a 60 % Windows and 40 % Linux user and my forecast is that in one year I will be 70 % Mac, 15 % Windows, and 15 % user. However, there are some bumps on the road to Mac-land.</p>
<p style="text-align: left;">
<p style="text-align: left;">Mac ships with Java 1.5 and <a href="http://apple.com/java">1.6</a> is available too. The problem is that only binaries are installed and as a serious developer you need also sources and documentation. So to get them, you have to join the <a href="http://developer.apple.com/">Apple Developer Connection</a> (the free version does it) and download the  Java for Mac OS X 10.5 Update 2 Developer Documentation (or probably a higher version in the future). The download is around 130 MB and includes sources/documentation for Java 1.5 and 1.6. Probably you have to set the src.jar and docs.jar manually to existing JVMs or just delete and add the existing ones.</p>
<p style="text-align: center;"><strong>Eclipse</strong>: Preferences - Java - Installed JREs - Select Installed JRE and click Edit</p>
<div class="mceTemp mceIEcenter" style="text-align: center;">
<dl id="attachment_108" class="wp-caption aligncenter" style="width: 160px;">
<dt class="wp-caption-dt" style="text-align: center;"><a href="http://juskewycz.com/wp-content/uploads/2008/11/eclipse_set_jvm.png"><img class="size-thumbnail wp-image-108" title="eclipse_set_jvm" src="http://juskewycz.com/wp-content/uploads/2008/11/eclipse_set_jvm-150x150.png" alt="Eclipse set JVM" width="150" height="150" /></a></dt>
<dd class="wp-caption-dd">Eclipse set JVM</dd>
</dl>
</div>
<p style="text-align: center;"><strong>NetBeans</strong>: Tools - Java Platform - Add or select the right Tab</p>
<div class="mceTemp mceIEcenter" style="text-align: center;">
<dl id="attachment_113" class="wp-caption aligncenter" style="width: 160px;">
<dt class="wp-caption-dt"><a href="http://juskewycz.com/wp-content/uploads/2008/11/netbeans_set_jvm.png"><img class="size-thumbnail wp-image-113" title="netbeans_set_jvm" src="http://juskewycz.com/wp-content/uploads/2008/11/netbeans_set_jvm-150x150.png" alt="NetBeans set JVM" width="150" height="150" /></a></dt>
<dd class="wp-caption-dd">NetBeans set JVM</dd>
</dl>
</div>
]]></content:encoded>
			<wfw:commentRss>http://juskewycz.com/2008/11/java-sources-and-documentation-under-mac-for-eclipsenetbeans/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Beware the ClassCastException (a tale of a native Memory Leak)</title>
		<link>http://juskewycz.com/2008/11/beware-the-classcastexception-a-tale-of-a-native-memory-leak/</link>
		<comments>http://juskewycz.com/2008/11/beware-the-classcastexception-a-tale-of-a-native-memory-leak/#comments</comments>
		<pubDate>Mon, 10 Nov 2008 17:27:15 +0000</pubDate>
		<dc:creator>heli</dc:creator>
		
		<category><![CDATA[heli's blog]]></category>

		<category><![CDATA[Bugs]]></category>

		<category><![CDATA[Java]]></category>

		<guid isPermaLink="false">http://juskewycz.com/?p=98</guid>
		<description><![CDATA[I had quite an interesting bug hunting last week in one of our extern engagements. In summer a memory leak was discovered in a new used third party library. Back then, we started with testing using Java profilers (Java SDK ships a good enough profiler - visual vm). Surprisingly, we found nothing; the heap didn&#8217;t [...]]]></description>
			<content:encoded><![CDATA[<p>I had quite an interesting bug hunting last week in one of our extern engagements. In summer a memory leak was discovered in a new used third party library. Back then, we started with testing using Java profilers (Java SDK ships a good enough profiler - visual vm). Surprisingly, we found nothing; the heap didn&#8217;t grow, number of threads remained the same, &#8230; in short, the usual suspects seemed innocent. Due to some other projects, we hadn&#8217;t enough time to do more testing, and so we just informed the company that sells the library about the issue. After some weeks, the company&#8217;s response was a we-dont-have-a-memory-leak-your-testing-is-wrong response (they suggested memory consumption is probably because of a different virtual machine and I have to admit that the task manager was also used to view the memory growth, which isn&#8217;t the tool to convince any real developer that there is a memory leak). However, the problem became urgent (like software problems tend to do) when the application was stress tested in real environment for a real customer. This project will be the first shipping with the new library. The application failed after approximately 6 hours due to a <a href="http://java.sun.com/javase/6/webnotes/trouble/TSG-VM/html/gbywc.html" target="_self">java.lang.OutOfMemoryError &#8230; Out of swap space?</a>.</p>
<p><span id="more-98"></span></p>
<p>In short this error means that the jvm cannot get more memory from the operating system. For us this meant there has to be native memory leak in the jvm or in the OS side. Since the library is for communication and uses heavily sockets, our first guess was a socket problem. Investigating the code of the library (gladly we have the source files) brought no results. During my research (what a fancy word for googling) I stumbled across this <a href="http://forums.java.net/jive/message.jspa?messageID=286153" target="_self">forum thread</a>. It describes a native memory leak that occurs when a ClassCastException is thrown! Further, the bug is still not fixed. I remembered that there are a lot of casts in the third party library, so I started testing how fast the memory grows. The following code pushes the memory usage to 340 MB:</p>
<pre name="code" class="java">
package com.hemju;

/**
* Example of the {@link ClassCastException} memory leak.
*
* @author Helmut Juskewycz, hjuskewycz - at - hemju.com
*/
public class CEMemoryLeak {

public static void main(String argv[]) throws Exception {
Object sObject = new String(&quot;Hello Leak&quot;);
Integer intObject = new Integer(&quot;5&quot;);

for (int i = 0; i &lt; 5000000; i++) {
try {
intObject = (Integer) sObject;
} catch (ClassCastException ex) {
}
}
Thread.sleep(60000);
}
}
</pre>
<p>Our application crashed with about 600-800 MB memory, hence, over 10 000 000 Class Cast Exceptions have to be thrown and caught! A lot of exceptions, nevertheless it was possible because we tested the application under heavy load. Phaser, äähh debugger set on thrown Exceptions with a hitcount of 1000 and start the engines. Under a minute Eclipse&#8217;s excellent debugger lead us to a code fragement which does basically this:</p>
<pre name="code" class="java">
...

Date date = null;

try {

date = (Date)obj;

} catch(Exception e) {}

if(date==null) new Date();

...
</pre>
<p>This fragement is bad in several ways, so never ever do that! Never catch silently an exception, never catch more than needed, and never ever use an exception to control the code flow! Until I discovered this fragment I had a good impression of the library&#8217;s code quality. So why would someone do that? I believe there has to be reason for doing it. Is it faster than a simple instanceof? If you know, please drop a comment.</p>
<p>My conclusion: Granted, throwing so much ClassCastExceptions is rare. That is good so. In my opinion casting should be avoided when possible, it often comes with a not-so-good design. When you can&#8217;t avoid it, handle it correctly! And be aware that a ClassCastException can lead to a native Memory Leak in java up to version 6, it should be fixed in Java 7.</p>
]]></content:encoded>
			<wfw:commentRss>http://juskewycz.com/2008/11/beware-the-classcastexception-a-tale-of-a-native-memory-leak/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Sometimes HashMaps are enough, part three</title>
		<link>http://juskewycz.com/2008/10/sometimes-hashmaps-are-enough-part-three/</link>
		<comments>http://juskewycz.com/2008/10/sometimes-hashmaps-are-enough-part-three/#comments</comments>
		<pubDate>Tue, 07 Oct 2008 17:39:09 +0000</pubDate>
		<dc:creator>heli</dc:creator>
		
		<category><![CDATA[heli's blog]]></category>

		<category><![CDATA[Dependency Injection]]></category>

		<category><![CDATA[Guice]]></category>

		<category><![CDATA[Java]]></category>

		<category><![CDATA[Spring]]></category>

		<category><![CDATA[Tutorial]]></category>

		<guid isPermaLink="false">http://juskewycz.com/?p=71</guid>
		<description><![CDATA[This part will be a short one because I have to pack for my vacation. Yes, I will leave this cold and miserable weather, heading south to fill up my energy again (I am running on solar power).
Last time we switched from a static approach to an instance based one and introduced a register-method to [...]]]></description>
			<content:encoded><![CDATA[<p>This part will be a short one because I have to pack for my vacation. Yes, I will leave this cold and miserable weather, heading south to fill up my energy again (I am running on solar power).</p>
<p>Last time we switched from a static approach to an instance based one and introduced a register-method to allow adding Singletons from everywhere. There are several issues with this approach:</p>
<ul>
<li>doesn&#8217;t support lazy initialization, so far only eager initialization was done</li>
<li>sometimes not all necessary information is available at register time to actually create the Singleton instance</li>
<li>maybe you want to track, creation, requesting, and so forth of the Singleton.</li>
</ul>
<p>Sounds complicated and scary? It isn&#8217;t, delegation is our friend again. Another way would be the observer (listener) pattern to address the above mentioned issues, however, delegation is more elegant and appropriate for this task.</p>
<p><span id="more-71"></span></p>
<p>Actually, the solution is as simple as it could be. We outsource (outsourcing in IT is a big thing!) the creation of Singletons to our new SingletonCreator interface. A SingletonCreator creates, like the name suggests, Singletons.</p>
<pre name="code" class="java">
public interface SingletonCreator&lt;T&gt; {

T getInstance();

}
</pre>
<p>The neat thing is that it is up to the implementor how and when everything is done. E.g. eager/lazy initialization is defined by the implementation. But you don&#8217;t have to stop here. What about a time based Singleton? Only available through 8:00 to 17:00 from Monday to Friday (the unions are killing us)? Not a problem. You can also track Singleton instance requests or persist (serialize) them. Everything possible with SingletonCreator. So let us make the necessary changes to S and SingletonHashMap:</p>
<p><strong>S.java</strong></p>
<pre name="code" class="java">
public abstract &lt;T&gt;&lt;T, E extends T&gt; void register(Class&lt;T&gt; clazz, SingletonCreator&lt;E&gt; creator);
</pre>
<p><strong>SingletonHashMap.java</strong></p>
<pre name="code" class="java">
private final HashMap&lt;Class&lt;?&gt;, SingletonCreator&lt;?&gt;&gt; singletons =
new HashMap&lt;Class&lt;?&gt;, SingletonCreator&lt;?&gt;&gt;();

HashMapSingleton() {
super();
// register as Singleton
register(S.class, new SingletonCreator&lt;S&gt;() {
@Override
public S getInstance() {
return HashMapSingleton.this;
}
});
}

@SuppressWarnings(&quot;unchecked&quot;)
// checked via register!
@Override
&lt;t&gt; T _get(Class&lt;T&gt; clazz) {
// TODO check for null values
return (T) singletons.get(clazz).getInstance();
}

@Override
public &lt;T&gt;&lt;T , E extends T&gt; void register(Class&lt;T&gt; clazz,
SingletonCreator&lt;E&gt; creator) {
// TODO check for null values
singletons.put(clazz, creator);
}
</pre>
<p>SingletonHashMap already reveals how the new solution works, but isn&#8217;t the best example with all that clumpy syntax. Here is a better one, the Main class which registers our System.out and System.err printer:</p>
<pre name="code" class="java">
package com.hemju;

public class Main {

public static void main(String[] args) {
// S.get(S.class).register(MyPrinter.class, new SerrPrinterCreator());
S.get(S.class).register(MyPrinter.class, new SoutPrinterCreator());
MyPrinter printer = S.get(MyPrinter.class);
printer.print(&quot;Hallo aus Linz&quot;);
}

private static class SerrPrinterCreator implements SingletonCreator&lt;MyPrinter&gt; {
// eager init
private final MyPrinter printer = new MySerrPrinter();

@Override
public MyPrinter getInstance() {
return printer;
}
}

private static class SoutPrinterCreator implements SingletonCreator&lt;MyPrinter&gt; {

private MyPrinter printer;

@Override
public MyPrinter getInstance() {
// lazy init
if (printer == null) {
printer = new MySoutPrinter();
}
return printer;
}
}
}
</pre>
<p>I am pretty satisfied with the solution by now.  So what do you think about my Singleton solution? I attached the <a href="http://juskewycz.com/wp-content/uploads/2008/10/singleton.zip">source code</a>, so you can easily investigate the code.<br />
One last word of cautions. Like most things in life nothing comes for free. Our new introduced flexibility holds certain pitfalls, or as we all know: With great power comes great responsibility. You don&#8217;t know what a SingletonCreator returns (null, a new instance every time, &#8230;). I will think about this possible problem, but until that I guess you have to trust your fellow programmers and of course yourself. <img src='http://juskewycz.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /></p>
]]></content:encoded>
			<wfw:commentRss>http://juskewycz.com/2008/10/sometimes-hashmaps-are-enough-part-three/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Sometimes HashMaps are enough, part two</title>
		<link>http://juskewycz.com/2008/10/sometimes-hashmaps-are-enough-part-two/</link>
		<comments>http://juskewycz.com/2008/10/sometimes-hashmaps-are-enough-part-two/#comments</comments>
		<pubDate>Mon, 06 Oct 2008 15:47:38 +0000</pubDate>
		<dc:creator>heli</dc:creator>
		
		<category><![CDATA[heli's blog]]></category>

		<category><![CDATA[Dependency Injection]]></category>

		<category><![CDATA[Guice]]></category>

		<category><![CDATA[Java]]></category>

		<category><![CDATA[Spring]]></category>

		<category><![CDATA[Tutorial]]></category>

		<guid isPermaLink="false">http://juskewycz.com/?p=64</guid>
		<description><![CDATA[The previous post shows how to implement a very simple and static approach to create Singletons using a static &#8220;Singleton&#8221; class. Now it is time to refactor our solution and make it more flexible.
First, I want to get rid of the static context. Static is very simple but also restrictive and we want and need [...]]]></description>
			<content:encoded><![CDATA[<p>The previous post shows how to implement a very simple and static approach to create Singletons using a static &#8220;Singleton&#8221; class. Now it is time to refactor our solution and make it more flexible.</p>
<p>First, I want to get rid of the static context. Static is very simple but also restrictive and we want and need flexibility later on. So instead of using static variables the get-method should delegate to the real implementation of the Singleton. How does this change our code?</p>
<p><span id="more-64"></span></p>
<pre name="code" class="java">
public abstract class S {

private static final S SINGLETON; //???

@SuppressWarnings(&quot;unchecked&quot;)
public static &lt;T&gt; T get(Class&lt;T&gt; clazz) {
return SINGLETON._get(clazz);
}

S() {
// make Singleton accessible only through static references
}

abstract &lt;T&gt; T _get(Class&lt;T&gt; clazz);

}
</pre>
<p>Instead of static, the Singleton class (I renamed it to just &#8220;S&#8221; because of shortness) is now abstract. It is still the entry point for getting an instance, but now delegates it to an implementation of S. So it is possible to use different types of S. For now this gives us no real advantage, but in the next parts of the tutorial you will see how this helps us. Please also note the use of Java&#8217;s default visibility. When S has its own package, rest of the application isn&#8217;t aware of the _get-method. To use S, we need an implementation of it:</p>
<pre name="code" class="java">
public class HashMapSingleton extends S {

private final HashMap&lt;Class&lt;?&gt;, Object&gt; singletons =
new HashMap&lt;Class&lt;?&gt;, Object&gt;();

HashMapSingleton() {
super();
singletons.put(MyPrinter.class, new MySoutPrinter());
}

@Override
&lt;T&gt; T _get(Class&lt;T&gt; clazz) {
// TODO check for null values
return (T) singletons.get(clazz);
}

}
</pre>
<p>S now could just create an instance of HashMapSingleton and then delegate the requests to it. But we want a more flexible solution. I personally see no need for supporting runtime exchange, (too flexible, although it is possible) and since another goal is simplicity, the easiest way is deciding at startup which Singleton implementation to use. I am not a mind reader, but I guess the chance that you think &#8216;Here comes the configuration file!&#8217; is pretty big. Not so fast, simple also means no configuration files. Therefore, we are using plain, oldschool Java System properties to determine which implementation to use. Adding the following lines should do the trick.</p>
<pre name="code" class="java">
static {
String singletonClassName = System.getProperty(&quot;com.hemju.S&quot;);
S singleton = null;
try {
singleton = (S) Class.forName(singletonClassName).newInstance();
} catch (Exception e) {
e.printStackTrace();
}
SINGLETON = singleton;
}
</pre>
<p>When we start our program with the VM argument <em>-Dcom.hemju.S=com.hemju.HashMapSingleton</em>, everything should just work fine. One more thing bothers me. Can you recall why we did introduce S in the first place? Exactly, because a class should do only serve one purpose. HashMapSingleton does managing and creating the Singletons and latter is clearly not its responsibility. Therefore, we introduce another method in S that allows registering Singleton instances.</p>
<p><strong>S</strong></p>
<pre name="code" class="java">
public abstract &lt;T&gt;&lt;T, E extends T&gt; void register(Class&lt;T&gt; clazz, E impl);
</pre>
<p><strong>HashMapSingleton</strong></p>
<pre name="code" class="java">
@Override
public &lt;T&gt;&lt;T, E extends T&gt; void register(Class&lt;T&gt; clazz, E impl) {
// TODO check for null values
singletons.put(clazz, impl);
}
</pre>
<p>Now it is possible for other classes to register Singletons. Wait, no static register? We don&#8217;t need one, we just register HashMapSingleton as a Singleton for S and S.get(S.class) gives us exactly what we want.</p>
<p>I think this solution is already better than the previous one, but there are still issues to be addressed which we will do in the next part.</p>
]]></content:encoded>
			<wfw:commentRss>http://juskewycz.com/2008/10/sometimes-hashmaps-are-enough-part-two/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Sometimes HashMaps are enough, part one</title>
		<link>http://juskewycz.com/2008/10/sometimes-hashmaps-are-enough-part-one/</link>
		<comments>http://juskewycz.com/2008/10/sometimes-hashmaps-are-enough-part-one/#comments</comments>
		<pubDate>Thu, 02 Oct 2008 09:32:00 +0000</pubDate>
		<dc:creator>heli</dc:creator>
		
		<category><![CDATA[heli's blog]]></category>

		<category><![CDATA[Dependency Injection]]></category>

		<category><![CDATA[Guice]]></category>

		<category><![CDATA[Java]]></category>

		<category><![CDATA[Spring]]></category>

		<category><![CDATA[Tutorial]]></category>

		<guid isPermaLink="false">http://juskewycz.com/?p=51</guid>
		<description><![CDATA[I guess we have all heard about how bad static Singletons are and how Dependency Injection (DI) helps to make our application flexible beyond crazy. One common thing to do with DI is creating and using Singletons. I have been working a lot with DI frameworks in the past, mostly Spring and Google Guice. Although [...]]]></description>
			<content:encoded><![CDATA[<p>I guess we have all heard about how bad static Singletons are and how Dependency Injection (DI) helps to make our application flexible beyond crazy. One common thing to do with DI is creating and using Singletons. I have been working a lot with DI frameworks in the past, mostly <a href="http://www.springsource.com/" target="_blank">Spring</a> and <a href="http://code.google.com/p/google-guice/" target="_blank">Google Guice</a>. Although both do a great job, I have been wondering lately if my applications always need this great flexibility. Don&#8217;t forget using them comes with a lot of baggage,  e.g. new third party dependencies or XML configuration files. In a big project this is probably not a problem, but in small projects it is just unnecessary. Note, I don&#8217;t state that Spring or Guice are bad, but sometimes the whole DI stack is just too much for small projects.</p>
<p>Singletons are a great example. They are simple to understand and to use. Like I mentioned, DI frameworks are often used to provide a &#8220;better&#8221; way to create Singletons, sometimes as their main purpose. I will present a simple , yet powerful enough, solution creating and instrumenting Singletons using a plain HashMap with no dependencies and configuration files.<span id="more-51"></span>Why are Singleton considered bad? We all use them, we all need them. I think the problem is not using Singletons, it is to create them. We all have seen code like this:</p>
<pre name="code" class="java">
public static final Application APPLICATION = new ApplicationImpl();
</pre>
<p>This code creates a Singleton of the interface Application. Through the public static modifier it is available for all other classes. Our problem solved! Not yet, where should we place this code? We could make Application an abstract class and place the static variable in it. But I don&#8217;t like this solution much. Why? Because <strong>a class should only do one thing</strong>. Application already has a purpose (some application related things), but creating a Singleton is clearly not Application&#8217;s job. Hence, we are creating a Singleton class that creates a Singleton for us. Instead of doing this with a public static variable we will provide a generic static method for it. Something like Singleton.get(???). Our get method needs a parameter to identify which class should be returned. We could create an enum Key, but then we also need to create a Key instance for every interface we want to register. <strong>A key already exists, the class of the interface</strong>. What about calling Singleton.get(Application.class)? That will do it. A HashMap then can hold the Singletons and get() returns the corresponding instance to the interface. Further, generics helps us to avoid casting.</p>
<p><strong>Singleton.java</strong></p>
<pre name="code" class="java">
package com.hemju;
import java.util.HashMap;

public class Singleton {

private static final HashMap&lt;Class&lt;?&gt;, Object&gt; SINGLETONS =
new HashMap&lt;Class&lt;?&gt;, Object&gt;();

static {
SINGLETONS.put(Application.class, new ApplicationImpl());
}

/**
* Returns a singleton which implements the given interface.
*
* @param
*          the interface which is implemented
* @param clazz
*          the class object of the interface
* @return a singleton instance of an implementing class or
*         &lt;code&gt;null&lt;/code&gt; when no implementation was found
*/
@SuppressWarnings(&quot;unchecked&quot;)
public static  T get(Class clazz) {
return (T) SINGLETONS.get(clazz);
}

private Singleton() {
// make Singleton accessible only through static references
}
}
</pre>
<p>Done! We already can use our simple Singleton solution. Have a look at the example at the end of this text. I am still not 100% satisfied with the solution, but we are going in the right direction.</p>
<p>Open issues are:</p>
<ul>
<li>not really flexible</li>
<li>no access control</li>
<li>no exception management (casting null values)</li>
<li>doesn&#8217;t work with Unit tests</li>
</ul>
<p>I will address this issues in the next part of this series. If you think I missed any issues, just drop a comment and let me know.</p>
<p><strong>Example</strong>:</p>
<pre name="code" class="java">
package com.hemju;

public interface MyPrinter {
void print(String s);
}
</pre>
<pre name="code" class="java">
package com.hemju;

public class MySoutPrinter implements MyPrinter {

@Override
public void print(String s) {
System.out.println(s);
}

}
</pre>
<pre name="code" class="java">
package com.hemju;

public class MySerrPrinter implements MyPrinter {

@Override
public void print(String s) {
System.err.println(s);
}

}
</pre>
<pre name="code" class="java">
package com.hemju;

public class Main {

public static void main(String[] args) {
// don&#039; forget to add
// SINGLETONS.put(MyPrinter.class, new MySoutPrinter());
// in the Singleton class
MyPrinter printer = Singleton.get(MyPrinter.class);
printer.print(&quot;Hallo aus Linz&quot;);
}

}
</pre>
<p></class></p>
]]></content:encoded>
			<wfw:commentRss>http://juskewycz.com/2008/10/sometimes-hashmaps-are-enough-part-one/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Nimbus is ready for prime time</title>
		<link>http://juskewycz.com/2008/08/nimbus-is-ready-for-prime-time/</link>
		<comments>http://juskewycz.com/2008/08/nimbus-is-ready-for-prime-time/#comments</comments>
		<pubDate>Wed, 20 Aug 2008 12:56:50 +0000</pubDate>
		<dc:creator>heli</dc:creator>
		
		<category><![CDATA[heli's blog]]></category>

		<category><![CDATA[Java 6 update 10]]></category>

		<category><![CDATA[Nimbus]]></category>

		<guid isPermaLink="false">http://juskewycz.com/?p=42</guid>
		<description><![CDATA[The great new look and feel for Swing applications, Nimbus, is according Jasper&#8217;s blog (the &#8216;father&#8217; of Nimbus) done. I haven&#8217;t tried the new version yet, but I am really looking forward to it.
Here a picture from the new look (screenshot is borrowed from Japser  ) Thank&#8217;s Jasper and Nimbus team

]]></description>
			<content:encoded><![CDATA[<p>The great new look and feel for Swing applications, Nimbus, is according <a href="http://www.jasperpotts.com/blog/2008/08/a-very-late-nimbus-is-done-blog/" target="_self">Jasper&#8217;s blog</a> (the &#8216;father&#8217; of Nimbus) done. I haven&#8217;t tried the new version yet, but I am really looking forward to it.</p>
<p>Here a picture from the new look (screenshot is borrowed from Japser <img src='http://juskewycz.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> ) Thank&#8217;s Jasper and Nimbus team</p>
<p><a href="http://juskewycz.com/wp-content/uploads/2008/08/swingset.png"><img class="aligncenter size-full wp-image-43" title="swingset" src="http://juskewycz.com/wp-content/uploads/2008/08/swingset.png" alt="" width="500" height="457" /></a></p>
]]></content:encoded>
			<wfw:commentRss>http://juskewycz.com/2008/08/nimbus-is-ready-for-prime-time/feed/</wfw:commentRss>
		</item>
	</channel>
</rss>
