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

<channel>
	<title>Charming Talk</title>
	<atom:link href="http://www.charmingtalk.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.charmingtalk.com</link>
	<description>Charmed by Technology</description>
	<pubDate>Sun, 25 Jan 2009 03:43:10 +0000</pubDate>
	<generator>http://wordpress.org/?v=2.7</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Singleton Pattern In Java</title>
		<link>http://www.charmingtalk.com/2009/01/22/singleton-pattern-unleashed-in-java/</link>
		<comments>http://www.charmingtalk.com/2009/01/22/singleton-pattern-unleashed-in-java/#comments</comments>
		<pubDate>Thu, 22 Jan 2009 05:10:05 +0000</pubDate>
		<dc:creator>admin</dc:creator>
		
		<category><![CDATA[Java]]></category>

		<guid isPermaLink="false">http://www.charmingtalk.com/?p=47</guid>
		<description><![CDATA[Singleton pattern is probably one of most popular widely used patterns that I have seen. It&#8217;s implemented to create an access restriction to a specific resource like: printer, network, pooling, memory, logging.

Here is a simple and correct implementation:
public class Singleton implements Serializable{
	private static Singleton _INSTANCE = null;

	static{
  		_INSTANCE = new Singleton();
 	}

	private Singleton() {
 [...]]]></description>
			<content:encoded><![CDATA[<p>Singleton pattern is probably one of most popular widely used patterns that I have seen. It&#8217;s implemented to create an access restriction to a specific resource like: printer, network, pooling, memory, logging.<br />
<br />
Here is a simple and correct implementation:</p>
<pre>public class Singleton implements Serializable{
	private static Singleton _INSTANCE = null;

	static{
  		_INSTANCE = new Singleton();
 	}

	private Singleton() {
  	}

	public static Singleton getInstance() {
		return _INSTANCE;
	}
 }</pre>
<p>Lets look at one by one.</p>
<p><em><strong>private static Singleton  _INSTANCE</strong></em> keeps reference of the instance<br />
<strong><em>static block</em></strong> this will prevent multi-thread initialization<br />
<strong><em>readResolve() </em></strong> to make sure a new instance is not created by deserialization process</p>
<p>Beware that double locking solution will not work:</p>
<pre>class Singleton {
  private static  Singleton singleton = null;
  public static Singleton getSingleton() {
    if (singleton == null){
        synchronized(this) {
           if (singleton == null)
              singleton = new Singleton ();
        }
   }
    return singleton ;
    }
  }</pre>
<p>Please read <a href="http://www.cs.umd.edu/~pugh/java/memoryModel/DoubleCheckedLocking.html">the article</a> why.<br />
<strong><em><br />
</em></strong></p>
<p></p>
]]></content:encoded>
			<wfw:commentRss>http://www.charmingtalk.com/2009/01/22/singleton-pattern-unleashed-in-java/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Understanding Dynamic Proxies</title>
		<link>http://www.charmingtalk.com/2009/01/11/dynamic-proxy/</link>
		<comments>http://www.charmingtalk.com/2009/01/11/dynamic-proxy/#comments</comments>
		<pubDate>Sun, 11 Jan 2009 19:30:59 +0000</pubDate>
		<dc:creator>admin</dc:creator>
		
		<category><![CDATA[Java]]></category>

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

		<category><![CDATA[Dynamic proxies]]></category>

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

		<guid isPermaLink="false">http://www.charmingtalk.com/?p=3</guid>
		<description><![CDATA[Dynamic proxies have existed since J2SE 1.3 and have been mainly utilized as a mechanism for method interception so that additional behavior could be interposed between a class caller and its callee. Dynamic proxies exemplify AOP (Aspect Oriented Programming) which bundled within Spring Framework API, it provides alternative for implementing common design patterns like Façade, [...]]]></description>
			<content:encoded><![CDATA[<p>Dynamic proxies have existed since J2SE 1.3 and have been mainly utilized as a mechanism for method interception so that additional behavior could be interposed between a class caller and its callee. Dynamic proxies exemplify <a title="Aspect Oriented Programming" href="http://en.wikipedia.org/wiki/Aspect-oriented_programming" target="_blank">AOP</a> (Aspect Oriented Programming) which bundled within <a title="Spring framework" href="http://www.springsource.org" target="_blank">Spring Framework API</a>, it provides alternative for implementing common design patterns like Façade, Bridge, Decorator, Proxy.</p>
<p></p>
<p><span id="more-3"></span></p>
<p>First lets create a basic Account class that will contain two pieces of information: account id and amount</p>
<pre>public class Account {
	private int accountId = -1;
	private BigDecimal amount = null;

	public Account(int id, BigDecimal amount) {
		this.accountId = id;
		this.amount = amount;
	}

	public int getAccountId() {
		return accountId;
	}

	public void setAccountId(int accountId) {
		this.accountId = accountId;
	}

	public BigDecimal getAmount() {
		return amount;
	}

	public void setAmount(BigDecimal amount) {
		this.amount = amount;
	}

}</pre>
<p>Next step we create an interface for processing banking requests.</p>
<pre>import java.math.BigDecimal;
public interface Bank {
	public void deposit(BigDecimal amount, int accountId);
	public void withdraw(BigDecimal amount, int accountId);
}</pre>
<p>Create a contrete class that will implement Bank interface and provide implementations for deposit and withrdaw methods. We will use hashtable to store all accounts in and we will syncronize updates per account basis.</p>
<pre>import java.math.BigDecimal;
import java.util.Hashtable;
import java.util.Map;

public class BankImpl implements Bank  {

	final private Map accounts = new  Hashtable();

	public BankImpl(){
		//create accounts
		accounts.put(new Integer(1234), new Account(1234,
                                            new BigDecimal("1000.00")));
	 	accounts.put(new Integer(1000), new Account(1000,
                                            new BigDecimal("5000.00")));
	 	accounts.put(new Integer(1500), new Account(1500,
                                            new BigDecimal("10000.00")));
	}

	@Override
	public void deposit(BigDecimal amount,int accountId) {
		Account account  = accounts.get(accountId);
		if (account==null)
                   throw new RuntimeException("Account not found ["+accountId+"]");

		synchronized (account) {
		 account.getAmount().add(amount);
		 System.out.printf("Deposited $%(,.2f to account[%d]%n",
                                        amount, accountId);
    	}
 	}

	@Override
	public void withdraw(BigDecimal amount,int accountId) {
		Account account  = accounts.get(accountId);
		if (account==null)
                 throw new RuntimeException("Account not found ["+accountId+"]");
		synchronized (account) {
		 account.getAmount().subtract(amount);
		 System.out.printf("Withdrew $%(,.2f from account[%d]%n",
                                        amount, accountId);

		}
	}

}</pre>
<p>Now, we need to create a LoggingHandler class that will inject &#8220;additional&#8221; code before and after the business calls.</p>
<p></p>
<pre>import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class LoggingHandler implements InvocationHandler{
	protected Object actual;

	public LoggingHandler(Object actual) {

		this.actual = actual;
	}

	public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
		try {
			System.out.println("&gt;&gt;&gt;&gt;&gt;&gt;start executing method: "
                                                + method.getName());
			Object result = method.invoke(actual, args);
			return result;
		} catch (InvocationTargetException ite) {
			throw new RuntimeException(ite.getMessage());
		} finally {
			System.out.println("&lt;&lt;&lt;&lt;&lt;executing method: " + method.getName());
		}
	}
}</pre>
<p>Create a factory class to return a bank instance with or without the proxy.</p>
<pre>import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;

public class BankFactory {
	private static BankFactory singleInstance = null;

	private BankFactory() {
	}

	public static BankFactory getInstance() {
		if (singleInstance == null) {
			singleInstance = new BankFactory();
		}
		return singleInstance;
	}

	public Bank getBank(boolean withLogging) {
		Bank bank = new BankImpl();

		if (withLogging) {
		 	InvocationHandler handler = new LoggingHandler(bank);
		 	bank = (Bank) Proxy.newProxyInstance(bank.getClass().getClassLoader(),
                                   bank.getClass().getInterfaces(), handler);
		}
		return bank;
	}
}</pre>
<p>Now finally we create the main class to demo methods calls with and without the proxy.</p>
<pre>import java.math.BigDecimal;

public class TestProxy {

	public static void main(String[] args) {

		System.out.println("++++++++++++++++Without dynamic proxy++++++++++++++++");

	 	Bank bank = BankFactory.getInstance().getBank(false);
		bank.deposit(new BigDecimal("200.00"), 1000);

		System.out.println("+++++++++++++ With dynamic proxy++++++++++++++++");
		bank = BankFactory.getInstance().getBank(true);
		bank.deposit(new BigDecimal("200.00"), 1000);

	}

}</pre>
<p>Results:</p>
<pre>++++++++++++++++Without dynamic proxy++++++++++++++++
Deposited $200.00 to account[1000]
+++++++++++++ With dynamic proxy++++++++++++++++
&gt;&gt;&gt;&gt;&gt;&gt; start executing method: deposit
Deposited $200.00 to account[1000]
&lt;&lt;&lt;&lt;&lt;&lt; finished executing method: deposit</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.charmingtalk.com/2009/01/11/dynamic-proxy/feed/</wfw:commentRss>
		</item>
	</channel>
</rss>
