<?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/"
	xmlns:georss="http://www.georss.org/georss" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:media="http://search.yahoo.com/mrss/"
	>

<channel>
	<title>Babloo80's Blog</title>
	<atom:link href="http://babloo80.wordpress.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://babloo80.wordpress.com</link>
	<description>Just another WordPress.com weblog</description>
	<lastBuildDate>Wed, 06 May 2009 21:32:00 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.com/</generator>
<cloud domain='babloo80.wordpress.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://s2.wp.com/i/buttonw-com.png</url>
		<title>Babloo80's Blog</title>
		<link>http://babloo80.wordpress.com</link>
	</image>
	<atom:link rel="search" type="application/opensearchdescription+xml" href="http://babloo80.wordpress.com/osd.xml" title="Babloo80&#039;s Blog" />
	<atom:link rel='hub' href='http://babloo80.wordpress.com/?pushpress=hub'/>
		<item>
		<title>Singleton Pattern</title>
		<link>http://babloo80.wordpress.com/2009/05/06/singleton-pattern/</link>
		<comments>http://babloo80.wordpress.com/2009/05/06/singleton-pattern/#comments</comments>
		<pubDate>Wed, 06 May 2009 21:32:00 +0000</pubDate>
		<dc:creator>babloo80</dc:creator>
				<category><![CDATA[Java Articles]]></category>

		<guid isPermaLink="false">http://babloo80.wordpress.com/2009/05/06/singleton-pattern/</guid>
		<description><![CDATA[Singleton pattern is a design pattern that is used to restrict instantiation of a class to one object instance. Possible Java Implementations Traditional simple way Notes: If laziness is not needed or the instance needs to be created early in the application&#8217;s execution, or your class has no other static members or methods that could [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=babloo80.wordpress.com&amp;blog=7614788&amp;post=6&amp;subd=babloo80&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p><span style="font-family:verdana;font-size:100%;"><br />
Singleton pattern is a design pattern that is used to restrict instantiation of a class to one object instance.<br />
</span></p>
<p>
<span style="font-family:verdana;font-size:130%;">Possible Java Implementations</span></p>
<p><span style="font-family:verdana;font-size:100%;"><b>Traditional simple way</b></span><br />
<pre class="brush: java;">
    public class Singleton {
        private static final Singleton INSTANCE = new Singleton();

        // Private constructor prevents instantiation from other classes
        private Singleton() {}

        public static Singleton getInstance() {
            return INSTANCE;
        }
    }
</pre><br />
<span style="font-family:verdana;font-size:100%;">Notes: If laziness is not needed or the instance needs to be created early in the application&#8217;s execution, or your class has no other static members or methods that could prompt early initialization (and thus creation of the instance), this solution can be used.</span></p>
<p><span style="font-family:verdana;font-size:100%;"><b>The solution of Bill Pugh</b></span><br />
<pre class="brush: java;">
    public class Singleton {
        // Private constructor prevents instantiation from other classes
        private Singleton() {}

        /**
        * SingletonHolder is loaded on the first execution of Singleton.getInstance() 
        * or the first access to SingletonHolder.INSTANCE, not before.
        */
        private static class SingletonHolder { 
            private static final Singleton INSTANCE = new Singleton();
        }

        public static Singleton getInstance() {
            return SingletonHolder.INSTANCE;
        }
    }    
</pre><br />
<span style="font-family:verdana;font-size:100%;">Notes: The technique is known as the initialization on demand holder idiom, is as lazy as possible, and works in all known versions of Java. The implementation relies on the well-specified initialization phase of execution within the JVM. The inner class (SingletonHolder) is referenced no earlier (and therefore loaded no earlier by the class loader) than the moment that getInstance() is called.</span></p>
<p><span style="font-family:verdana;font-size:100%;"><b>Java 5 Way! a.k.a Joshua Bloch way.</b></span><br />
<pre class="brush: java;">
    public enum Singleton {
        INSTANCE;
        public void myUsefulMethod1(){...}
        ...
    } 
    
    Usage: Singleton.INSTANCE.myUsefulMethod1();
</pre><br />
<span style="font-family:verdana;font-size:78%;">Credits: Effective Java 2nd Edn, <a title="Wikipedia - Singleton" href="http://en.wikipedia.org/wiki/Singleton_pattern">Wiki</a></span></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/babloo80.wordpress.com/6/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/babloo80.wordpress.com/6/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/babloo80.wordpress.com/6/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/babloo80.wordpress.com/6/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/babloo80.wordpress.com/6/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/babloo80.wordpress.com/6/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/babloo80.wordpress.com/6/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/babloo80.wordpress.com/6/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/babloo80.wordpress.com/6/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/babloo80.wordpress.com/6/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/babloo80.wordpress.com/6/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/babloo80.wordpress.com/6/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/babloo80.wordpress.com/6/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/babloo80.wordpress.com/6/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=babloo80.wordpress.com&amp;blog=7614788&amp;post=6&amp;subd=babloo80&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://babloo80.wordpress.com/2009/05/06/singleton-pattern/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/532782c081a9ab858cb7b1892d510163?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">babloo80</media:title>
		</media:content>
	</item>
		<item>
		<title>Double Checked Locking</title>
		<link>http://babloo80.wordpress.com/2009/05/05/double-checked-locking/</link>
		<comments>http://babloo80.wordpress.com/2009/05/05/double-checked-locking/#comments</comments>
		<pubDate>Tue, 05 May 2009 22:14:00 +0000</pubDate>
		<dc:creator>babloo80</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://babloo80.wordpress.com/2009/05/05/double-checked-locking/</guid>
		<description><![CDATA[This is a locking optimization pattern. This pattern is designed to reduce the overhead of acquiring a lock by first testing the locking criterion (the &#8216;lock hint&#8217;) in an unsafe manner; only if that succeeds does the actual lock proceed. Typical implementation // Correct but possibly expensive multithreaded version class Foo { private Helper helper [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=babloo80.wordpress.com&amp;blog=7614788&amp;post=7&amp;subd=babloo80&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p><span style="font-family:verdana;font-size:100%;"><br />This is a locking optimization pattern. This pattern is designed to reduce the overhead of acquiring a lock by first testing the locking criterion (the &#8216;lock hint&#8217;) in an unsafe manner; only if that succeeds does the actual lock proceed.<br /></span></p>
<p><span style="font-family:verdana;font-size:100%;"><b>Typical implementation</b></span>
<pre class="prettyprint">    // Correct but possibly expensive multithreaded version    class Foo {         private Helper helper = null;        public synchronized Helper getHelper() {            if (helper == null)                helper = new Helper();            return helper;        }

        // other functions and members...    }</pre>
<p><span style="font-family:verdana;font-size:100%;">Notes: The overhead of acquiring and releasing a lock every time this method is called seems unnecessary. Once the initialization has been completed, acquiring and releasing the locks would appear unnecessary.</span></p>
<p><span style="font-family:verdana;font-size:100%;"><b>DCL using Java 5 Memory Model </b></span>
<pre class="prettyprint">    // Works with acquire/release semantics for volatile    // Broken under Java 1.4 and earlier semantics for volatile    class Foo {        private volatile Helper helper = null;        public Helper getHelper() {            if (helper == null) {                synchronized(this) {                    if (helper == null)                        helper = new Helper();                }            }            return helper;        }

        // other functions and members...    }
</pre>
<p><span style="font-family:verdana;font-size:100%;">Notes: Java 5 and later extends the semantics for volatile so that the system will not allow a write of a volatile to be reordered with respect to any previous read or write, and a read of a volatile cannot be reordered with respect to any following read or write.</span></p>
<p><span style="font-family:verdana;font-size:100%;"><b>DCL using Thread Local Storage</b></span>
<pre class="prettyprint">    class Foo {        /**          *  If perThreadInstance.get() returns a non-null value, this thread         *  has done synchronization needed to see initialization         *  of helper          */        private final ThreadLocal perThreadInstance = new ThreadLocal();        private Helper helper = null;        public Helper getHelper() {            if (perThreadInstance.get() == null)                 createHelper();            return helper;        }        private final void createHelper() {            synchronized(this) {                if (helper == null)                    helper = new Helper();            }            // Any non-null value would do as the argument here            perThreadInstance.set(perThreadInstance);        }    }    </pre>
<p><span style="font-family:verdana;font-size:100%;">Notes: Each thread keeps a thread local flag to determine whether that thread has done the required synchronization.</span></p>
<p><span style="font-family:verdana;font-size:78%;">Credits: <a title="Wikipedia - Singleton" href="http://en.wikipedia.org/wiki/Singleton_pattern">Wiki</a></span></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/babloo80.wordpress.com/7/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/babloo80.wordpress.com/7/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/babloo80.wordpress.com/7/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/babloo80.wordpress.com/7/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/babloo80.wordpress.com/7/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/babloo80.wordpress.com/7/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/babloo80.wordpress.com/7/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/babloo80.wordpress.com/7/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/babloo80.wordpress.com/7/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/babloo80.wordpress.com/7/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/babloo80.wordpress.com/7/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/babloo80.wordpress.com/7/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/babloo80.wordpress.com/7/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/babloo80.wordpress.com/7/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=babloo80.wordpress.com&amp;blog=7614788&amp;post=7&amp;subd=babloo80&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://babloo80.wordpress.com/2009/05/05/double-checked-locking/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/532782c081a9ab858cb7b1892d510163?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">babloo80</media:title>
		</media:content>
	</item>
		<item>
		<title>Memory Allocation and Garbage Collection</title>
		<link>http://babloo80.wordpress.com/2009/05/04/memory-allocation-and-garbage-collection/</link>
		<comments>http://babloo80.wordpress.com/2009/05/04/memory-allocation-and-garbage-collection/#comments</comments>
		<pubDate>Mon, 04 May 2009 22:35:00 +0000</pubDate>
		<dc:creator>babloo80</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://babloo80.wordpress.com/2009/05/04/memory-allocation-and-garbage-collection/</guid>
		<description><![CDATA[One strength of the J2SE platform is that it shields the complexity of memory allocation and garbage collection from the developer. However, once garbage collection is the principal bottleneck, it is worth understanding some aspects of this hidden implementation. Garbage collectors make assumptions about the way applications use objects, and these are reflected in tunable [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=babloo80.wordpress.com&amp;blog=7614788&amp;post=8&amp;subd=babloo80&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p><span style="font-family:verdana;font-size:100%;">
<p>One strength of the J2SE platform is that it shields the complexity of memory allocation and garbage collection from the developer. However, once garbage collection is the principal bottleneck, it is worth understanding some aspects of this hidden implementation. Garbage collectors make assumptions about the way applications use objects, and these are reflected in tunable parameters that can be adjusted for improved performance without sacrificing the power of the abstraction.</p>
<p>
<p>An object is considered garbage when it can no longer be reached from any pointer in the running program. The most straightforward garbage collection algorithms simply iterate over every reachable object. Any objects left over are then considered garbage. The time this approach takes is proportional to the number of live objects, which is prohibitive for large applications maintaining lots of live data. </p>
<p>
<p>Beginning with the J2SE platform, version 1.2, the virtual machine incorporated a number of different garbage collection algorithms that are combined using generational collection. While naive garbage collection examines every live object in the heap, generational collection exploits several empirically observed properties of most applications to avoid extra work.</p>
<p><img style="width:600px;height:415px;" src="http://java.sun.com/docs/hotspot/gc1.4.2/fig2.gif">
<p>The most important of these observed properties is infant mortality. The blue area in the diagram below is a typical distribution for the lifetimes of objects. The X axis is object lifetimes measured in bytes allocated. The byte count on the Y axis is the total bytes in objects with the corresponding lifetime. The sharp peak at the left represents objects that can be reclaimed (i.e., have &#8220;died&#8221;) shortly after being allocated. Iterator objects, for example, are often alive for the duration of a single loop.</p>
<p>
<p>Some objects do live longer, and so the distribution stretches out to the the right. For instance, there are typically some objects allocated at initialization that live until the process exits. Between these two extremes are objects that live for the duration of some intermediate computation, seen here as the lump to the right of the infant mortality peak. Some applications have very different looking distributions, but a surprisingly large number possess this general shape. Efficient collection is made possible by focusing on the fact that a majority of objects &#8220;die young&#8221;.</p>
<p>
<p>To optimize for this scenario, memory is managed in generations, or memory pools holding objects of different ages. Garbage collection occurs in each generation when the generation fills up. Objects are allocated in a generation for younger objects or the young generation, and because of infant mortality most objects die there. When the young generation fills up it causes a minor collection. Minor collections can be optimized assuming a high infant mortality rate. The costs of such collections are, to the first order, proportional to the number of live objects being collected. A young generation full of dead objects is collected very quickly. Some surviving objects are moved to an tenured generation. When the tenured generation needs to be collected there is a major collection that is often much slower because it involves all live objects.</p>
<p>
<p>The diagram below shows minor collections occurring at intervals long enough to allow many of the objects to die between collections. It is well-tuned in the sense that the young generation is large enough (and thus the period between minor collections long enough) that the minor collection can take advantage of the high infant mortality rate. This situation can be upset by applications with unusual lifetime distributions, or by poorly sized generations that cause collections to occur before objects have had time to die.</p>
<p>
<p>The default arrangement of generations looks something like this.</p>
<p><img style="width:600px;height:333px;" src="http://java.sun.com/docs/hotspot/gc1.4.2/fig3.gif">
<ul> 
<li>At initialization, a maximum address space is virtually reserved but not allocated to physical memory unless it is needed. The complete address space reserved for object memory can be divided into the young and tenured generations.</li>
<p> 
<li>The young generation consists of eden plus two survivor spaces . Objects are initially allocated in eden. One survivor space is empty at any time, and serves as a destination of the next, copying collection of any live objects in eden and the other survivor space. Objects are copied between survivor spaces in this way until they old enough to be tenured, or copied to the tenured generation.</li>
<p> 
<li>One portion of the tenured generation called the permanent generation is special because it holds all the reflective data of the virtual machine itself, such as class and method objects.</li>
<p> 
<li></li>
<p></ul>
<p>
<p>The default garbage collector is meant to be used by applications large and small. Its default parameters were designed to be effective for most small applications. The default parameters aren&#8217;t optimal for many server applications.</p>
<p><b>Sizing the generation</b><br /><img style="width:600px;height:333px;" src="http://java.sun.com/docs/hotspot/gc1.4.2/fig4.gif"></p>
<p></span><br /><span style="font-family:verdana;font-size:78%;">Credits: <a title="Wikipedia - Singleton" href="http://java.sun.com/docs/hotspot/gc1.4.2/">Tuning Garbage Collection</a></span></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/babloo80.wordpress.com/8/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/babloo80.wordpress.com/8/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/babloo80.wordpress.com/8/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/babloo80.wordpress.com/8/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/babloo80.wordpress.com/8/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/babloo80.wordpress.com/8/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/babloo80.wordpress.com/8/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/babloo80.wordpress.com/8/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/babloo80.wordpress.com/8/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/babloo80.wordpress.com/8/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/babloo80.wordpress.com/8/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/babloo80.wordpress.com/8/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/babloo80.wordpress.com/8/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/babloo80.wordpress.com/8/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=babloo80.wordpress.com&amp;blog=7614788&amp;post=8&amp;subd=babloo80&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://babloo80.wordpress.com/2009/05/04/memory-allocation-and-garbage-collection/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/532782c081a9ab858cb7b1892d510163?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">babloo80</media:title>
		</media:content>

		<media:content url="http://java.sun.com/docs/hotspot/gc1.4.2/fig2.gif" medium="image" />

		<media:content url="http://java.sun.com/docs/hotspot/gc1.4.2/fig3.gif" medium="image" />

		<media:content url="http://java.sun.com/docs/hotspot/gc1.4.2/fig4.gif" medium="image" />
	</item>
		<item>
		<title>Guice: Dependency Injection Framework</title>
		<link>http://babloo80.wordpress.com/2009/05/03/guice-dependency-injection-framework/</link>
		<comments>http://babloo80.wordpress.com/2009/05/03/guice-dependency-injection-framework/#comments</comments>
		<pubDate>Sun, 03 May 2009 11:57:00 +0000</pubDate>
		<dc:creator>babloo80</dc:creator>
				<category><![CDATA[Java Articles]]></category>

		<guid isPermaLink="false">http://babloo80.wordpress.com/2009/05/03/guice-dependency-injection-framework/</guid>
		<description><![CDATA[Guice (pronounced &#8220;juice&#8221;) is an ultra-lightweight, next-generation dependency injection container for Java 5 and later. Guice alleviates the need for factories and the use of new in your Java code. Think of Guice&#8217;s @Inject as the new new. You will still need to write factories in some cases, but your code will not depend directly [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=babloo80.wordpress.com&amp;blog=7614788&amp;post=10&amp;subd=babloo80&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p><span style="font-family:verdana;font-size:100%;"><br />
Guice (pronounced &#8220;juice&#8221;) is an ultra-lightweight, next-generation dependency injection container for Java 5 and later.<br />
Guice alleviates the need for factories and the use of new in your Java code. Think of Guice&#8217;s @Inject as the new new. You will still need to write factories in some cases, but your code will not depend directly on them. Your code will be easier to change, unit test and reuse in other contexts. </span></p>
<p><span style="font-family:verdana;font-size:130%;">Creating a simple DI application</span></p>
<p><pre class="brush: java;">
//Service Receiver.
public class Chef {
    private final FortuneService fortuneService;

    @Inject
    public Chef(FortuneService fortuneService) {
        this.fortuneService = fortuneService;
    }

    public void makeFortuneCookie() {
        new FortuneCookie(fortuneService.randomFortune());
    }
}

//Service Provider -- Implementation 1
public class FortuneServiceImpl implements FortuneService {
    private static final List&lt;string&gt; MESSAGES =
        Arrays.asList(
         &quot;Today you will have some refreshing juice.&quot;,
         &quot;Larry just bought your company.&quot;
    );

    public String randomFortune() {
        return MESSAGES.get(new Random().nextInt(MESSAGES.size()));
    }
}

//Configuration Module
public class ChefModule implements Module {  //can 'implements Module' or 'extends AbstractModule'
    public void configure(Binder binder) {
        binder.bind(FortuneService.class)
        .to(FortuneServiceImpl.class)
        .in(Scopes.SINGLETON);
    }
}

//Bootstraping 
public class FortuneApplication {   
    public static void main(String[] args) {
        Injector i = Guice.createInjector(new ChefModule());   // Can also be Injector i = Guice.createInjector(Stage.PRODUCTION, new ChefModule(),...); i.e 1 or more modules
        Chef chef = i.getInstance(Chef.class); //which is same as i.getInstance(Key.get(Chef.class));
        chef.makeFortuneCookie();
    }
}
</pre></p>
<p><span style="font-family:verdana;font-size:100%;"><br />
Here is the sequence diagram of the above code snippet at runtime. <br />
<img src="http://docs.google.com/File?id=dd2fhx4z_29f8h7x7" alt="Sequence Diagram" /></p>
<table border="0" cellspacing="1" cellpadding="0" style="background-color:#757575;vertical-align:top;margin:0;">
<tr>
<td style="background-color:#FFFFFF;padding:2px;">Main</td>
<td style="background-color:#FFFFFF;padding:2px;">FortuneApplication</td>
</tr>
<tr>
<td style="background-color:#FFFFFF;padding:2px;">Guice</td>
<td style="background-color:#FFFFFF;padding:2px;">
<pre>Guice.createInjector(new ChefModule());</pre>
</td>
</tr>
<tr>
<td style="background-color:#FFFFFF;padding:2px;">MyModule</td>
<td style="background-color:#FFFFFF;padding:2px;">ChefModule</td>
</tr>
<tr>
<td style="background-color:#FFFFFF;padding:2px;">Binder</td>
<td style="background-color:#FFFFFF;padding:2px;">
<pre>ChefModule.configure(Binder binder);</pre>
</td>
</tr>
<tr>
<td style="background-color:#FFFFFF;padding:2px;">Injector</td>
<td style="background-color:#FFFFFF;padding:2px;"><i>@Inject Annotation</i></td>
</tr>
</table>
<p>The following is the Guice Runtime Model<br />
<img style="width:578px;height:216px;" src="http://docs.google.com/File?id=dd2fhx4z_30f3dppc" alt="Runtime Model"><br />
<b>Note: The above code snippet uses Key.Type. It does not use any annotation</b><br />
</span></p>
<p><span style="font-family:verdana;font-size:130%;">DI with annotations &#8212; &#8216;choosing between implementations&#8217;</span><br />
<pre class="brush: java;">
Using the above Interface (i.e FortuneService) &amp;amp; Implemementation (i.e FortuneServiceImpl)

//Service Provider -- Implementation 2
public class MegaFortuneService implements FortuneService {
 private static final List&lt;fortuneservice&gt; SERVICES =
     Arrays.&lt;fortuneservice&gt;asList(
         new FunnyFortuneService(),
        new QuoteFortuneService()
     );

 public String randomFortune() {
     int index = new Random().nextInt(SERVICES.size());
     return SERVICES.get(index).randomFortune();
 }
}

//Configuration Module
public class CommonSenseModule extends AbstractModule {
 protected void configure() {
     bind(FortuneService.class).to(FortuneServiceImpl.class);
     bind(FortuneService.class).to(MegaFortuneService.class); //ERROR!!!
 }
}

Hence, we need a better means to tell Guice to use MegaFortuneService. Using 'Binding Annotations' would resolve this problem.

//Service Receiver.
public class Chef {
 private final FortuneService fortuneService;

 @Inject
 public Chef(@Mega FortuneService fortuneService) {  //Updated Usage!
     this.fortuneService = fortuneService;
 }

 public String randomFortune() {
     return MESSAGES.get(new Random().nextInt(MESSAGES.size()));
 }
}

//Module class.
public class ChefModule extends AbstractModule {
 protected void configure() {
     bind(FortuneService.class).to(FortuneServiceImpl.class);
     bind(FortuneService.class)
         .annotatedWith(Mega.class)        //Add annotation key!
         .to(MegaFortuneService.class);
 }
}

//Annotation class.
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD, ElementType.PARAMETER})
@BindingAnnotation
public @interface Mega {}


//Bootstraping
public class FortuneApplication {   //Main class
 public static void main(String[] args) {
     Injector i = Guice.createInjector(new ChefModule());   // Can also be Injector i = Guice.createInjector(Stage.PRODUCTION, new ChefModule());
     Chef chef = i.getInstance(Key.get(FortuneService.class, Mega.class));  //Refer: http://docs.google.com/File?id=dd2fhx4z_30f3dppc
     chef.makeFortuneCookie();
 }
}
</pre></p>
<p><span style="font-family:verdana;font-size:130%;">Implicit Binding &#8211; @ImplementedBy</span><br />
<pre class="brush: java;">
//Service Provider
@ImplementedBy(FortuneServiceImpl.class)  //Implicit binding. Note: Module configuration i.e bind(FortuneService.class).to(FortuneServiceImpl.class) would still take precidence over this.
public interface FortuneService {
 String randomFortune();
}

//Service Receiver.
public class Chef {
 private final FortuneService fortuneService;

 @Inject
 public Chef(FortuneService fortuneService) {
     this.fortuneService = fortuneService;
 }

 public void makeFortuneCookie() {
     new FortuneCookie(fortuneService.randomFortune());
 }
}

//Service Provider -- Implementation 1
public class FortuneServiceImpl implements FortuneService {
 private static final List&lt;string&gt; MESSAGES =
     Arrays.asList(
         &quot;Today you will have some refreshing juice.&quot;,
         &quot;Larry just bought your company.&quot;
     );

 public String randomFortune() {
     return MESSAGES.get(new Random().nextInt(MESSAGES.size()));
 }
}

Notice that, 'ChefModule' is not required for default configuration.
&lt;/string&gt;&lt;/pre&gt;

&lt;span style=&quot;;font-family:verdana;font-size:130%;&quot;  &gt;Scoping&lt;/span&gt;
[sourcecode language='java']
public class ChefModule extends AbstractModule {
 protected void configure() {
     bind(FortuneService.class)
         .to(FortuneServiceImpl.class)
         .in(Singleton.class);  //Either Singleton.class or Scopes.SINGLETON
     bind(FortuneService.class)
         .annotatedWith(Mega.class)
         .to(MegaFortuneService.class)
         .asEagerSingleton(); //Do singletons load lazily or eagerly?

 }
}
</pre></p>
<p><span style="font-family:verdana;font-size:130%;">Guice Provider</span><br />
<pre class="brush: java;">
A Provider implementation is basically a small factory class that Guice will invoke whenever it needs an instance of the given type.

public class Gum {}

public class GumballMachine {
 @Inject
 private Provider&lt;gum&gt; gumProvider;

 public Gum dispense() {
     return gumProvider.get();
 }
}

public class GumProvider implements Provider&lt;gum&gt; {
 public Gum get() {
     return new Gum();
 }
}

public class GumModule extends AbstractModule {
 protected void configure() {
     bind(Gum.class).toProvider(GumProvider.class);
 }
}

public class GumballExample {
 public static void main(String[] args) {
     Injector injector = Guice.createInjector(new GumModule());
     GumballMachine m = injector.getInstance(GumballMachine.class);
     System.out.println(m.dispense());  // Gum@10f11b8
     System.out.println(m.dispense());  // Gum@544ec1
 }
}

Injecting into Provider:
public class BlueGumProvider implements Provider&lt;gum&gt; {
 @Inject Color color;
 public Gum get() {
     return new Gum(color);
 }
}
</pre></p>
<p><span style="font-family:verdana;font-size:130%;">Implict Binding &#8211; @ProvidedBy</span><br />
<pre class="brush: java;">Similar to @ImplementedBy&lt;/pre&gt;

&lt;span style=&quot;;font-family:verdana;font-size:130%;&quot;  &gt;Using @Named&lt;/span&gt;
[sourcecode language='java']
@Named is a OOTB annotation, that uses string identifier to differentiate among different bindings.

//Service Consumer
public class ActionMovie {
 @Inject @Named(&quot;stallone&quot;)
 private Actor actor;
}

Module code snippet:
 bind(Actor.class).annotatedWith(Names.named(&quot;stallone&quot;)).to(...); //Note: The usual way of using annotations, 'bind(Actor.class).annotatedWith(Named.class).to(...);' will NOT work.
&lt;/pre&gt;

&lt;span style=&quot;;font-family:verdana;font-size:130%;&quot;  &gt;Binding Constants&lt;/span&gt;
[sourcecode language='java']
//Service Consumer
public class ConcertHall {
 @Inject @Named(&quot;capacity&quot;)
 private int capacity;

 @Inject @Named(&quot;stage&quot;)
 private Class stageType;

 @Inject @Named(&quot;setting&quot;)
 private Setting setting;

 public String toString() {
     return String.format(&quot;%s[capacity=%s, stageType=%s, setting=%s]&quot;,
                          getClass().getName(), capacity, stageType, setting);
 }
}

//Another service provider with package &quot;somepackage&quot;
public class BigStage {}

//Service Configuration
public class ConcertModule extends AbstractModule {
 protected void configure() {
     bindConstant()
         .annotatedWith(Names.named(&quot;capacity&quot;))
         .to(&quot;322&quot;);
     bindConstant()
         .annotatedWith(Names.named(&quot;stage&quot;))
         .to(&quot;somepackage.BigStage&quot;);
     bindConstant()
         .annotatedWith(Names.named(&quot;setting&quot;))
         .to(&quot;INDOOR&quot;);
 }
}

//Bootstraping
public class ConcertExample {
 public static void main(String[] args) {
     Injector i = Guice.createInjector(new ConcertModule());
     ConcertHall hall = i.getInstance(ConcertHall.class);
     System.out.println(hall);  //Outputs, ConcertHall[capacity=322, stageType=class somepackage.BigStage, setting=INDOOR]
 }
}

A better way of binding, especially while using generic types.
//Service Consumer
public class LongHolder {
 @Inject @Named(&quot;long&quot;)
 @Inject @Named(&quot;list&quot;) List&lt;string&gt; strings;
 @Inject @Named(&quot;list&quot;) List&lt;integer&gt; integers;
 private Long theLong;
}

//Service Configuration
public class LongModule extends AbstractModule {
 protected void configure() {
     bind(Long.class)
     .annotatedWith(Names.named(&quot;long&quot;))
     .toInstance(123L); 
 bind(new TypeLiteral&lt;list&gt;&lt;string&gt;&gt;(){})
         .annotatedWith(Names.named(&quot;list&quot;))
         .to(new TypeLiteral&lt;arraylist&gt;&lt;string&gt;&gt;(){});
     bind(new TypeLiteral&lt;list&gt;&lt;integer&gt;&gt;(){})
         .annotatedWith(Names.named(&quot;list&quot;))
         .to(new TypeLiteral&lt;arraylist&gt;&lt;integer&gt;&gt;(){});

 }
}

//Bootstraping
public class LongHolderExample {
 public static void main(String[] args) {
     Injector i = Guice.createInjector(new LongModule());
     i.getInstance(LongHolder.class);
 }
}

//A more readable Service Configuration that can deal with types. --- Essentially the same functionality.
public class TypeLiteralModule extends AbstractModule {
 protected void configure() {
     bind(listOf(String.class))
         .annotatedWith(Names.named(&quot;list&quot;))
         .to(arrayListOf(String.class));
     bind(listOf(Integer.class))
         .annotatedWith(Names.named(&quot;list&quot;))
         .to(arrayListOf(Integer.class));
 }

 @SuppressWarnings(&quot;unchecked&quot;)
 static &lt;t&gt; TypeLiteral&lt;list&gt;&lt;t&gt;&gt; listOf(final Class&lt;t&gt; parameterType) {
     return (TypeLiteral&lt;list&gt;&lt;t&gt;&gt;) TypeLiteral.get(new ParameterizedType() {
         public Type[] getActualTypeArguments(){return new Type[] {parameterType};}
         public Type getRawType() { return List.class; }
         public Type getOwnerType() { return null; }
     }
 );
 }

 @SuppressWarnings(&quot;unchecked&quot;)
 static &lt;t&gt; TypeLiteral&lt;arraylist&gt;&lt;t&gt;&gt; arrayListOf(final Class&lt;t&gt; parameterType) {
     return (TypeLiteral&lt;arraylist&gt;&lt;t&gt;&gt;) TypeLiteral.get(new ParameterizedType() {
         public Type[] getActualTypeArguments(){return new Type[] {parameterType};}
         public Type getRawType() { return ArrayList.class; }
 }
 );
 }
}
</pre></p>
<p><span style="font-family:verdana;font-size:130%;">Properties</span><br />
<pre class="brush: java;">
Sample property file: db.properties
db.url = jdbc:mysql://localhost/test
db.driver = com.mysql.jdbc.Driver
db.user = test
db.password = test

public class PropertiesModule extends AbstractModule {
 protected void configure() {
     try {
         Properties databaseProperties = loadProperties(&quot;db.properties&quot;);
         Names.bindProperties(binder(), databaseProperties);
     } catch (RuntimeException e) {
         addError(&quot;Could not configure database properties&quot;, e);
   }
 }

 private static Properties loadProperties(String name) { //loads file as java.util.Properties
     Properties properties = new Properties();
     InputStream is = new Object(){}
                         .getClass()
                         .getEnclosingClass()
                         .getResourceAsStream(name);
     try {
      properties.load(is);
     } catch(IOException e) {
         throw new RuntimeException(e);
     } finally {
         if (is != null) {
            try {
                is.close();
            } catch (IOException dontCare) {}
         }
     }
     return properties;
 }
}

public class PropertiesExample {
 @Inject
 public void databaseURL(@Named(&quot;db.url&quot;) String url) {
     System.out.println(url);
 }

 public static void main(String[] args) {
     Injector i = Guice.createInjector(new PropertiesModule());
     i.getInstance(PropertiesExample.class);  //Output: jdbc:mysql://localhost/test.
 }
}
</pre></p>
<p><span style="font-family:verdana;font-size:130%;">Static Injection</span><br />
<pre class="brush: java;">
public class StaticModule extends AbstractModule {
 protected void configure() {
     bindConstant().annotatedWith(Names.named(&quot;s&quot;)).to(&quot;D'OH!&quot;);
     requestStaticInjection(StaticInjection.class);
 }
}

public class StaticInjection {
 @Inject
 public static void staticMethod(@Named(&quot;s&quot;) String str) {
     System.out.println(str); //Output: D'OH!
 }

 public static void main(String[] args) {
     Guice.createInjector(new StaticModule());
 }
}
</pre></p>
<p><span style="font-family:verdana;font-size:130%;">Custom Scope</span><br />
<pre class="brush: java;">
public class CustomScopes {
 public static final Scope DEFAULT = new Scope() {
     public &lt;t&gt; Provider&lt;t&gt; scope(Key&lt;t&gt; key, Provider&lt;t&gt; creator) {
         System.out.println(&quot;Scoping &quot;+key);
         return creator;
     }
     public String toString() {
         return CustomScopes.class.getSimpleName()+&quot;.DEFAULT&quot;;
     }
 };
}

public class Person {
 public Person() {
     System.out.printf(&quot;Hi, I'm a Person. With hashCode '%s', I'm unique!%n&quot;, super.hashCode());
 }
}

public class CustomScopeModule extends AbstractModule {
 protected void configure() {
     bind(Person.class).in(CustomScopes.DEFAULT);
 }
}

public class UseCustomScope {
 public static void main(String[] args) {
     Injector i = Guice.createInjector(new CustomScopeModule());
     i.getInstance(Person.class);  //Output: Hi, I'm a Person. With hashCode '7841785', I'm unique!
     i.getInstance(Person.class);  //Output: Hi, I'm a Person. With hashCode '1847634', I'm unique!
 }
}

Using custom scope as an annotation,

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@ScopeAnnotation
public @interface DefaultScoped {}

@DefaultScoped
public class Person {
 public Person() {
     System.out.printf(&quot;Hi, I'm a Person. With hashCode '%s', I'm unique!%n&quot;, super.hashCode());
 }
}

public class CustomScopeModule extends AbstractModule {
 protected void configure() {
     bindScope(DefaultScoped.class, CustomScopes.DEFAULT);  //CustomScopes.DEFAULT is defined in the previous example.
 }
}

public class UseCustomScope {
 public static void main(String[] args) {
     Injector i = Guice.createInjector(new CustomScopeModule());
     i.getInstance(Person.class);  //Output: Hi, I'm a Person. With hashCode '7841785', I'm unique!
     i.getInstance(Person.class);  //Output: Hi, I'm a Person. With hashCode '1847634', I'm unique!
 }
}
</pre></p>
<p><span style="font-family:verdana;font-size:130%;">Organizing Modules</span><br />
<pre class="brush: java;">
If a project has more than a module (i.e service configurations), then...

public class ApplicationModule extends AbstractModule {
 protected void configure() {
     install(new DefaultScopeModule());  //Install all the modules in the order of depedency?
     install(new BindingsModule());
 }
}

public class UseCustomScopeWithApplicationModule {
 public static void main(String[] args) {
     Injector i = Guice.createInjector(new ApplicationModule());
     i.getInstance(Person.class);
     i.getInstance(Person.class);
 }
}
</pre></p>
<p><span style="font-family:verdana;font-size:130%;">AOP (using) Guice</span><br />
<pre class="brush: java;">
//The class that would be intercepted.
public class Phone {
 private static final Map&lt;number, receiver=&quot;&quot;&gt; RECEIVERS =
     new HashMap&lt;number, receiver=&quot;&quot;&gt;();

 static {
     RECEIVERS.put(123456789, new Receiver(&quot;Aunt Jane&quot;));
 }

 public Receiver call(Number number) {
     return RECEIVERS.get(number);
 }
}

public class Receiver {
 private final String name;
 public Receiver(String name) {
     this.name = name;
 }
 public String toString() {
     return String.format(&quot;%s[name=%s]&quot;, getClass().getName(), name);
 }
}


import static com.google.inject.matcher.Matchers.*;
public class PhoneModule extends AbstractModule {
 protected void configure() {
     bindInterceptor(
         subclassesOf(Phone.class),       //Class Constraint   //any(), not(...), annotatedWith(...), subclassesOf(...), only(...), identicalTo(...), inPackage(...)
         returns(only(Receiver.class)),   //Method Constraint  //any(), not(...), annotatedWith(...), only(...), identicalTo(...), returns(...)
         new PhoneLoggerInterceptor(),
     new PhoneRedirectInterceptor()
   );
 }
}


public class PhoneLoggerInterceptor implements MethodInterceptor {
 public Object invoke(MethodInvocation invocation) throws Throwable {
     for (Object arg : invocation.getArguments())
         if (arg instanceof Number)
            System.out.println(&quot;CALL: &quot;+arg);

     return invocation.proceed();
 }
}

public class PhoneRedirectInterceptor implements MethodInterceptor {
 public Object invoke(MethodInvocation invocation) throws Throwable {
     return new Receiver(&quot;Alberto's Pizza Place&quot;);
 }
}

//Bootstrap...
public class MakePhoneCall {
 public static void main(String[] args) {
     Injector i = Guice.createInjector(new PhoneModule());
 Phone phone = i.getInstance(Phone.class);
     Receiver auntJane = phone.call(123456789); //Output:  CALL: 123456789 Receiver[name=Alberto's Pizza Place]
 }
}
</pre></p>
<p><span style="font-family:verdana;font-size:78%;">Credits: <a title="Book" href="http://my.safaribooksonline.com/9781590599976">APRESS &#8211; Google Guice: Agile Lightweight Dependency Injection Framework</a>, <a title="User Guide" href="http://docs.google.com/Doc?id=dd2fhx4z_5df5hw8">Guice User&#8217;s Guice</a></span></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/babloo80.wordpress.com/10/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/babloo80.wordpress.com/10/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/babloo80.wordpress.com/10/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/babloo80.wordpress.com/10/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/babloo80.wordpress.com/10/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/babloo80.wordpress.com/10/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/babloo80.wordpress.com/10/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/babloo80.wordpress.com/10/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/babloo80.wordpress.com/10/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/babloo80.wordpress.com/10/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/babloo80.wordpress.com/10/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/babloo80.wordpress.com/10/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/babloo80.wordpress.com/10/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/babloo80.wordpress.com/10/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=babloo80.wordpress.com&amp;blog=7614788&amp;post=10&amp;subd=babloo80&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://babloo80.wordpress.com/2009/05/03/guice-dependency-injection-framework/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/532782c081a9ab858cb7b1892d510163?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">babloo80</media:title>
		</media:content>

		<media:content url="http://docs.google.com/File?id=dd2fhx4z_29f8h7x7" medium="image">
			<media:title type="html">Sequence Diagram</media:title>
		</media:content>

		<media:content url="http://docs.google.com/File?id=dd2fhx4z_30f3dppc" medium="image">
			<media:title type="html">Runtime Model</media:title>
		</media:content>
	</item>
	</channel>
</rss>
