<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>@InitBinder &#187; java</title>
	<atom:link href="http://initbinder.com/categories/java/feed" rel="self" type="application/rss+xml" />
	<link>http://initbinder.com</link>
	<description>My thoughts, notes and ideas as a passionate software engineer</description>
	<lastBuildDate>Sat, 24 Mar 2012 13:29:46 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Is TDD Only for &#8230; Junior Developers??</title>
		<link>http://initbinder.com/articles/is-tdd-only-for-junior-developers.html</link>
		<comments>http://initbinder.com/articles/is-tdd-only-for-junior-developers.html#comments</comments>
		<pubDate>Sun, 24 Apr 2011 03:05:45 +0000</pubDate>
		<dc:creator>Alexander Zagniotov</dc:creator>
				<category><![CDATA[best practices]]></category>
		<category><![CDATA[design patterns]]></category>
		<category><![CDATA[java]]></category>

		<guid isPermaLink="false">http://javabeans.asia/?p=1027</guid>
		<description><![CDATA[Just before the Easter holidays, I had a discussion with two senior developers from my project about TDD. These guys are experienced software engineers that have been around for some time: they have 11 and 20 years of experience in &#8230; <a href="http://initbinder.com/articles/is-tdd-only-for-junior-developers.html">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Just before the Easter holidays, I had a discussion with two senior developers from my project about TDD. These guys are experienced software engineers that have been around for some time: they have 11 and 20 years of experience in software development under their belts.</p>
<p>I don&#8217;t claim to be an advocate for TDD. Currently, I do not practice it (yet), but I do recognize and appreciate its importance. TDD really &#8220;forces&#8221; you to have clear understanding about the business requirements to be implemented. You cant implement what you do not understand, right? Because you have to write the test first, your code becomes more solid, less bug prune and you have better test coverage.</p>
<p>Sure, writing the test first its an interesting concept: You start writing a test, and you discoverer that you need a class, and possibly a function. You create the class, function and keep writing the test. Basically, you write few lines of test, and few lines of code, few more lines of test and few more lines of code etc. etc.</p>
<p>Ok, I think I diverted a bit, back to the topic <img src='http://initbinder.com/bunker/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  The discussion took an interesting turn, and I still keep thinking about it. My question to them was &#8211; what do you think about TDD? The responses I received totally surprised me.</p>
<p>One of the claims supported by them, was that TDD does not serve much purpose, and a developer will end up re-factoring the unit tests eventually anyway as a result of re-factoring the concrete classes as the development goes on. So if latter is the case, my colleagues argued that there is no point writing unit tests first. Its better to finish writing concrete class, before attempting to write any unit tests.</p>
<p>Also, one of the developers claimed that many books and articles written on TDD discuss examples that are quite simple to implement, and in reality it is quite difficult to use TDD for complex business scenarios.</p>
<p>Another claim was that TDD should be used to teach junior developers the importance of unit testing, the experienced developers don&#8217;t really need to use it. The developers should follow KISS principles instead.</p>
<p>I respected their opinions about it, but it seemed fundamentally wrong to me that such experienced developers claim that TDD is basically overrated. The feeling that I got from them was that a lot of developers and software engineers in IT industry really got it wrong.</p>
<p>It got me wondering how, after more than ten years of experience in the industry, one does not appreciate one of the best software engineering practices around &#8230;</p>
<p>Offcourse, having said all that, I must point out that TDD is not suitable for every case. TDD can be effective only when it is clear what need to be implemented and there is a deep understanding of requirements.</p>
]]></content:encoded>
			<wfw:commentRss>http://initbinder.com/articles/is-tdd-only-for-junior-developers.html/feed</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>Java, Good Ways &#8211; A Book of Unwritten Rules, Tips and Gotchas</title>
		<link>http://initbinder.com/articles/java-good-ways-a-book-of-unwritten-rules-tips-and-gotchas.html</link>
		<comments>http://initbinder.com/articles/java-good-ways-a-book-of-unwritten-rules-tips-and-gotchas.html#comments</comments>
		<pubDate>Tue, 19 Apr 2011 06:37:49 +0000</pubDate>
		<dc:creator>Alexander Zagniotov</dc:creator>
				<category><![CDATA[java]]></category>
		<category><![CDATA[java book]]></category>
		<category><![CDATA[java tips]]></category>

		<guid isPermaLink="false">http://javabeans.asia/?p=996</guid>
		<description><![CDATA[A colleague of mine, who is currently my tech lead, wrote a book. The book Java, Good Ways is a collection of unwritten rules, tips and gotchas collected over a long period of time. The book comes to minimize the &#8230; <a href="http://initbinder.com/articles/java-good-ways-a-book-of-unwritten-rules-tips-and-gotchas.html">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>A colleague of mine, who is currently my tech lead, wrote a book.</p>
<p>The book <a title="Java, Good Ways" href="http://javagoodways.com/" target="_blank">Java, Good Ways</a> is a collection of unwritten rules, tips and gotchas collected over a long period of time. The book comes to minimize the gap between university studies and what Java developers actually need to know.</p>
<p>Have a look, read through, let me know what you think or simply leave a comment on Java, Good Ways <img src='http://initbinder.com/bunker/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://initbinder.com/articles/java-good-ways-a-book-of-unwritten-rules-tips-and-gotchas.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Integrating Spring MVC with Hibernate Annotation-Based Validation</title>
		<link>http://initbinder.com/articles/integrating-spring-mvc-with-hibernate-annotation-based-validation.html</link>
		<comments>http://initbinder.com/articles/integrating-spring-mvc-with-hibernate-annotation-based-validation.html#comments</comments>
		<pubDate>Sat, 26 Mar 2011 07:55:32 +0000</pubDate>
		<dc:creator>Alexander Zagniotov</dc:creator>
				<category><![CDATA[java]]></category>
		<category><![CDATA[spring]]></category>
		<category><![CDATA[bean validation]]></category>
		<category><![CDATA[hibernate validator]]></category>
		<category><![CDATA[JSR-303]]></category>
		<category><![CDATA[mvc]]></category>
		<category><![CDATA[spring mvc]]></category>
		<category><![CDATA[validation]]></category>
		<category><![CDATA[web]]></category>

		<guid isPermaLink="false">http://javabeans.asia/?p=969</guid>
		<description><![CDATA[In this article, I would like to demonstrate how to integrate Spring MVC, Spring bean validation framework and hibernate validator using annotations. The Hibernate Validator project is implementation of JSR 303 &#8211; Bean Validation standard, which defines a metadata model &#8230; <a href="http://initbinder.com/articles/integrating-spring-mvc-with-hibernate-annotation-based-validation.html">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>In this article, I would like to demonstrate how to integrate Spring MVC, Spring bean validation framework and hibernate validator using annotations. The <a title="Hibernate Vlidator - Implementation of JSR 303  Bean Validation" href="http://www.hibernate.org/412.html" target="_blank">Hibernate Validator</a> project is implementation of <a title="Metadata model and API for JavaBean validation standard" href="http://jcp.org/en/jsr/detail?id=303" target="_blank">JSR 303 &#8211; Bean Validation</a> standard, which defines a metadata model and API for JavaBean validation. For the the purpose of this example, I used Spring Framework v3.0.5 and Hibernate Validator v4.1.0.</p>
<p>What I like about Spring + Hibernate validation, is that this combination eliminates the need to use validator classes in controllers for bean validation. In other words, less code, less classes, everything looks much cleaner.</p>
<p>I am not going to talk about how to build web application from scratch using Spring MVC. I assume that you already have something working in place. I am just going to show the important bits needed, in order to plug hibernate validation in to your code:</p>
<p>1. Define two following beans in your application context XML in your WEB-INF directory:</p>
<p>[xml]<br />
&lt;bean id=&quot;validator&quot;<br />
class=&quot;org.springframework.validation.beanvalidation.LocalValidatorFactoryBean&quot;/&gt;<br />
[/xml]</p>
<p>The basic configuration above will trigger JSR-303 to initialize using its default bootstrap mechanism. A JSR-303 provider, such as Hibernate Validator, is expected to be present in the classpath and will be detected automatically.</p>
<p>[xml]<br />
&lt;bean id=&quot;messageSource&quot;<br />
     class=&quot;org.springframework.context.support.ResourceBundleMessageSource&quot;&gt;<br />
	&lt;property name=&quot;basename&quot; value=&quot;/WEB-INF/message-resources.bundle&quot; /&gt;<br />
&lt;/bean&gt;<br />
[/xml]</p>
<p>The bean above knows how to access resource bundles using specified basenames.</p>
<p>2. Create resource bundle (in this example it is &#8220;message-resources.bundle&#8221;) under WEB-INF. The resource bundle is where you should define your validation messages that the end user sees if his form submission fails validation. Please note that the bundle does not have to be at the root of WEB-INF, it can be placed also in a sub-directory of WEB-INF. The format for validation messages in your bundle should be as follows:</p>
<p>[java]Annotation.bean-variable-name.bean-propery=validation error message.[/java]</p>
<p>For example:</p>
<p>[java]<br />
NotBlank.someFormName.name=Name must not be blank,<br />
Size.someFormName.name=Name must be less than or equal to {1} characters.<br />
NotBlank.someFormName.street=Street name should not be blank. Please enter a value<br />
NotEmpty.someFormName.selectedItem=Item selection is required<br />
[/java]</p>
<p>The example above describes four different validation messages for different validation rules. In case of a particular validation rule disobeyed, its respective validation message will be found based on the validation annotation, bean name and bean property name.</p>
<p>3. In your controller, in the method that validates bean from the POST request, annotate your bean with annotation <em>@Valid</em>. For example:</p>
<p>[java]<br />
@RequestMapping(value = &quot;/update.html&quot;, method = RequestMethod.POST)<br />
 public String update (    @ModelAttribute(&quot;someFormName&quot;)<br />
 @Valid SomeForm someFormName,<br />
 BindingResult result,<br />
 Model model)<br />
 {</p>
<p> if(result.hasErrors()) {<br />
 // Return view name<br />
 }</p>
<p> // Do stuff</p>
<p> // Return view name<br />
 }<br />
[/java]</p>
<p>The <em>@Valid</em> annotation is part of the standard <a title="Metadata model and API for JavaBean validation standard" href="http://jcp.org/en/jsr/detail?id=303" target="_blank">JSR 303 &#8211; Bean Validation</a> API, and is not a Spring-specific construct. The <a title="Hibernate Vlidator - Implementation of JSR 303  Bean Validation" href="http://www.hibernate.org/412.html" target="_blank">Hibernate Validator</a> instance invoked when a <em>@Valid </em>method argument is encountered.</p>
<p><strong>Very important</strong>: your bean variable name in your controller method (in this case its &#8220;<em>someFormName</em>&#8220;) must match the bean variable name in your validation message resource bundle.</p>
<p>4. Annotate your bean member variables with annotations that tell <a title="Hibernate Vlidator - Implementation of JSR 303  Bean Validation" href="http://www.hibernate.org/412.html" target="_blank">Hibernate Validator</a> what should be validated and what are the validation rules:</p>
<p>[java]<br />
public final class SomeForm {</p>
<p> @NotBlank<br />
 @Size(min=0,max=20)<br />
 private String name;</p>
<p> @NotBlank<br />
 private String street;</p>
<p> @NotEmpty<br />
 private String selectedItem;</p>
<p> // Getters</p>
<p> // Setters<br />
}<br />
[/java]</p>
<p>As you can see from the above bean, the three fields that should be validated are annotated with <em>@NotBlank</em>, <em>@NotEmpty</em> and <em></em><em>@Size</em>. The validation rules are simple: the <em>name </em>property must not be blank nor longer than 20 characters, <em>street </em>property must not be blank, while <em>selectedItem </em>must not be empty.</p>
<p>By the way, you can have more complicated validation rules in place using annotations. It is possible to use expressions which decide whether validation rules should fire. Consider the following, which validate an email field:</p>
<p>[java]<br />
@Email(applyIf=&quot;email is not blank&quot;)<br />
@NotBlank<br />
private String email;<br />
[/java]</p>
<p>You don&#8217;t want to display invalid email format error message when the filed is blank. Therefore that above expression in <em>@Email</em> annotation will have the rule fired only when the property is not blank. Expression can be especially very convenient when validating password fields:</p>
<p>[java]<br />
@NotBlank<br />
private String password;</p>
<p>@NotBlank(applyIf = &quot;password is not blank&quot;)<br />
@Expression(value = &quot;confirmedPassword= password&quot;, applyIf = &quot;password is not blank&quot;)<br />
private String confirmedPassword;<br />
[/java]</p>
<p>Validation rules for <em>confirmedPassword</em> property will fire only when <em>password</em> field will not be blank.</p>
<p>That&#8217;s it <img src='http://initbinder.com/bunker/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  If any rule(s) are disobeyed, the BindingResult result object will be populated with appropriate error messages, loaded from your message bundle. The error messages then can be displayed in your JSP using Spring tag:</p>
<p>[xml]<br />
&lt;spring:hasBindErrors name=&quot;someFormName&quot;&gt;<br />
	&lt;c:forEach items=&quot;${errors.allErrors}&quot; var=&quot;error&quot;&gt;<br />
		&lt;spring:message message=&quot;${error}&quot;/&gt;<br />
	&lt;/c:forEach&gt;<br />
&lt;/spring:hasBindErrors&gt;<br />
[/xml]</p>
<p>And that is it! Feel free to post a comment if you run into problems and I iwll try to help you the best I can <img src='http://initbinder.com/bunker/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://initbinder.com/articles/integrating-spring-mvc-with-hibernate-annotation-based-validation.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Cheat Sheet for Selecting Map/List/Set in Java</title>
		<link>http://initbinder.com/articles/cheat-sheet-for-selecting-maplistset-in-java.html</link>
		<comments>http://initbinder.com/articles/cheat-sheet-for-selecting-maplistset-in-java.html#comments</comments>
		<pubDate>Sun, 20 Mar 2011 11:57:13 +0000</pubDate>
		<dc:creator>Alexander Zagniotov</dc:creator>
				<category><![CDATA[java]]></category>
		<category><![CDATA[collections]]></category>
		<category><![CDATA[hashmap]]></category>
		<category><![CDATA[list]]></category>
		<category><![CDATA[map]]></category>
		<category><![CDATA[set]]></category>

		<guid isPermaLink="false">http://javabeans.asia/?p=930</guid>
		<description><![CDATA[I have prepared a cheat sheet that can help to select appropriate Map, Set or List implementation when required. Java API has many implementations of interfaces mentioned, and it is not always clear which implementation should be used in a &#8230; <a href="http://initbinder.com/articles/cheat-sheet-for-selecting-maplistset-in-java.html">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>I have prepared a cheat sheet that can help to select appropriate Map, Set or List implementation when required. Java API has many implementations of interfaces mentioned, and it is not always clear which implementation should be used in a particular scenario. The cheat sheet comes in the form of a flow chart, which makes it easy to follow and understand.</p>
<p>The idea was inspired by Sergiy Kovalchuk. Sergiy made a flow chart using the most commonly used collections. I tried to take it one step further and make it much more thorough.  Please do let me know if anything needs to be corrected. I hope this can help developers out there to choose the right collection for the right job.</p>
<div id="attachment_931" class="wp-caption aligncenter" style="width: 272px"><a title="Guide for selecting appropriate Set/Map/List in Java" href="http://initbinder.com/bunker/wp-content/uploads/2011/03/collections.png" target="_blank"><img class="size-medium wp-image-931 " title="collections" src="http://initbinder.com/bunker/wp-content/uploads/2011/03/collections-262x300.png" alt="Cheat sheet for selecting appropriate set/list/map in Java" width="262" height="300" /></a><p class="wp-caption-text">Click on the image to load it in a new window</p></div>
<p style="text-align: center;"><em> </em></p>
<p><em>Inspired by <a title="Sergiy Kovalchuk" href="http://www.sergiy.ca/" target="_blank">Sergiy Kovalchuk</a></em></p>
]]></content:encoded>
			<wfw:commentRss>http://initbinder.com/articles/cheat-sheet-for-selecting-maplistset-in-java.html/feed</wfw:commentRss>
		<slash:comments>10</slash:comments>
		</item>
		<item>
		<title>How To Define a Spring Bean With Generics Parameter</title>
		<link>http://initbinder.com/articles/how-to-define-spring-bean-with-a-generic-parameter.html</link>
		<comments>http://initbinder.com/articles/how-to-define-spring-bean-with-a-generic-parameter.html#comments</comments>
		<pubDate>Tue, 15 Mar 2011 18:00:39 +0000</pubDate>
		<dc:creator>Alexander Zagniotov</dc:creator>
				<category><![CDATA[design patterns]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[spring]]></category>
		<category><![CDATA[xml]]></category>
		<category><![CDATA[generics]]></category>
		<category><![CDATA[spring mvc]]></category>

		<guid isPermaLink="false">http://javabeans.asia/?p=882</guid>
		<description><![CDATA[At the time when this article was written, the Spring framework does not allow to define beans in application context xml file using parameterized classes. The reason for that is that generics parameters are compiler information, and not run-time. Compiler &#8230; <a href="http://initbinder.com/articles/how-to-define-spring-bean-with-a-generic-parameter.html">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>At the time when this article was written, the Spring framework does not allow to define beans in application context xml file using parameterized classes. The reason for that is that generics parameters are compiler information, and not run-time. Compiler information is something that Spring does not care about. For example, the following (or something similar) will NOT work:</p>
<p>[java]<br />
&lt;bean id=&quot;someClass&quot; class=&quot;asia.javabeans.SomeClass&lt;asia.javabeans.Blah&gt;&quot;  /&gt;<br />
[/java]</p>
<p>Sometimes, this restriction can create a problem if you have a parameterized class that has to be loaded by Spring. As a workaround, create an empty child class that extends your  parameterized class, and then use that class&#8217;s canonical name as your bean definition. Consider the following  parameterized parent and the extending child classes:</p>
<p>[java]<br />
public class SomeParent&lt;Blah&gt; {</p>
<p>}</p>
<p>public class Child extends SomeParent&lt;Blah&gt; {<br />
   // Just an empty class<br />
}<br />
[/java]</p>
<p>and your Spring definition can now look like this:</p>
<p>[java]<br />
&lt;bean id=&quot;childClass&quot; class=&quot;asia.javabeans.Child&quot; /&gt;<br />
[/java]</p>
<p>The down side here is that you get stuck with an empty class, but at least you can have your bean definition in your application context xml file.</p>
]]></content:encoded>
			<wfw:commentRss>http://initbinder.com/articles/how-to-define-spring-bean-with-a-generic-parameter.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Inheritance and Generics with Abstract Data Types</title>
		<link>http://initbinder.com/articles/inheritance-and-generics-with-abstract-data-types.html</link>
		<comments>http://initbinder.com/articles/inheritance-and-generics-with-abstract-data-types.html#comments</comments>
		<pubDate>Tue, 15 Mar 2011 06:20:01 +0000</pubDate>
		<dc:creator>Alexander Zagniotov</dc:creator>
				<category><![CDATA[design patterns]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[abstract generics]]></category>
		<category><![CDATA[design concepts]]></category>
		<category><![CDATA[generics]]></category>
		<category><![CDATA[inheritance]]></category>

		<guid isPermaLink="false">http://javabeans.asia/?p=873</guid>
		<description><![CDATA[In this article, I want to demonstrate a simple inheritance example that uses generics.  The abstract parent class is generic in the type, and it defines an abstract method that accepts as a method parameter the generic data type. The &#8230; <a href="http://initbinder.com/articles/inheritance-and-generics-with-abstract-data-types.html">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>In this article, I want to demonstrate a simple inheritance example that uses generics.  The abstract parent class is generic in the type, and it defines an abstract method that accepts as a method parameter the generic data type.</p>
<p>The generic data type used by the extending child in the implementation of the abstract method. This example is going to discuss the benefit of this approach.</p>
<p>Consider the following parent class:</p>
<p>[java]<br />
public abstract class Parent&lt;T&gt; {<br />
    protected abstract void process(T data);<br />
}<br />
[/java]</p>
<p>Consider the following two child classes that extend the parent:</p>
<p>[java]<br />
public class Child extends Parent&lt;SomeClass&gt; {<br />
    @Override<br />
    public void process(SomeClass data) {<br />
        // Do stuff<br />
    }<br />
}<br />
[/java]</p>
<p>[java]<br />
public class AnotherChild extends Parent&lt;OtherClass&gt; {<br />
    @Override<br />
    public void process(OtherClass data) {<br />
        // Do stuff<br />
    }<br />
}<br />
[/java]</p>
<p>You can clearly see how this approach creates flexibility when multiple child classes require different data type parameters when implementing the abstract method. Because of the generic type setting in the abstract method, any data type can be passed to the child. This approach can be particularly useful when implementing a strategy design pattern.</p>
]]></content:encoded>
			<wfw:commentRss>http://initbinder.com/articles/inheritance-and-generics-with-abstract-data-types.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Making Instance Variables Thread Safe</title>
		<link>http://initbinder.com/articles/making-instance-variables-thread-safe.html</link>
		<comments>http://initbinder.com/articles/making-instance-variables-thread-safe.html#comments</comments>
		<pubDate>Sat, 23 Oct 2010 12:01:06 +0000</pubDate>
		<dc:creator>Alexander Zagniotov</dc:creator>
				<category><![CDATA[java]]></category>
		<category><![CDATA[threads]]></category>
		<category><![CDATA[multithreading]]></category>
		<category><![CDATA[thread safety]]></category>

		<guid isPermaLink="false">http://javabeans.asia/?p=787</guid>
		<description><![CDATA[One of the ways to achieve thread safety when creating instance variables is to make a use of ThreadLocal class.  When instance variable is wrapped in ThreadLocal, each thread accessing the variable has its own independent copy of the variable. &#8230; <a href="http://initbinder.com/articles/making-instance-variables-thread-safe.html">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>One of the ways to achieve thread safety when creating instance variables is to make a use of <a title="ThreadLocal" href="http://download.oracle.com/javase/1.4.2/docs/api/java/lang/ThreadLocal.html" target="_blank">ThreadLocal</a> class.  When instance variable is wrapped in ThreadLocal, each thread accessing the variable has its own independent copy of the variable.</p>
<p>An even better approach is to wrap the instance variable in <a title="SoftReference" href="http://download.oracle.com/javase/1.4.2/docs/api/java/lang/ref/SoftReference.html" target="_blank">SoftReference</a>, which can eliminate the risk if getting <a title="OutOfMemoryError" href="http://download.oracle.com/javase/1.4.2/docs/api/java/lang/OutOfMemoryError.html" target="_blank">OutOfMemoryError</a> if there is a need to keep a an object in memory for a long period of time, for example when implementing caching mechanism. The garbage collector will only collect softly referenced objects when it decides that memory is low enough to warrant it</p>
<p>Consider the following snippet:</p>
<p>[java]<br />
public class ThreadSafeExample {</p>
<p> private static final ThreadLocal&lt;SoftReference&lt;List&lt;SomeObject&gt;&gt;&gt; trhLocal =<br />
                                new ThreadLocal&lt;SoftReference&lt;List&lt;SomeObject&gt;&gt;&gt;();<br />
 .<br />
 .<br />
    public static List&lt;SomeObject&gt; getSafeList() {</p>
<p>      // Get the value of the current thread&#8217;s copy of this thread-local variable<br />
      SoftReference&lt;List&lt;SomeObject&gt;&gt; reference = trhLocal.get();</p>
<p>      if (reference != null)  {<br />
         // Get this reference object&#8217;s referent<br />
         List&lt;SomeObject&gt; safeList = reference.get();</p>
<p>            if (safeList != null)  {<br />
                 return safeList;<br />
            }<br />
       }</p>
<p>       // Ok, so we did not have previously anything,<br />
       // lets create thread-local variable<br />
       List&lt;SomeObject&gt; safeList = new LinkedList&lt;SomeObject&gt;();<br />
       reference = new SoftReference&lt;List&lt;SomeObject&gt;&gt;(safeList);<br />
       trhLocal.set(reference);</p>
<p>     return safeList;<br />
   }<br />
}<br />
[/java]</p>
<p>What happens in the above example is, when getSafeList() is called, the thread&#8217;s list is assigned the first time it invokes getSafeList(), which causes invocation of  trhLocal.get().  If get() does not return anything, a new copy of the instance variable is created and set to the <a title="ThreadLocal" href="http://download.oracle.com/javase/1.4.2/docs/api/java/lang/ThreadLocal.html" target="_blank">ThreadLocal</a> instance. Each thread holds an implicit reference to its copy of a thread-local variable as long as the thread is alive and the <a title="ThreadLocal" href="http://download.oracle.com/javase/1.4.2/docs/api/java/lang/ThreadLocal.html" target="_blank">ThreadLocal</a> instance is accessible. This approach does not require  synchronization, which can create thread contention, and provides much faster access to the variable than via synchronization.</p>
<p>Off course one should consider whether <a title="ThreadLocal" href="http://download.oracle.com/javase/1.4.2/docs/api/java/lang/ThreadLocal.html" target="_blank">ThreadLocal</a> is really needed. Normally, a good candidates for object re-use via thread local are objects that are frequently accessed by a given thread and are non-trivial to construct. Another scenario for making use of <a title="ThreadLocal" href="http://download.oracle.com/javase/1.4.2/docs/api/java/lang/ThreadLocal.html" target="_blank">ThreadLocal</a>, would be when it is not really practical to extend Thread class (for example creating servlets) and thread safety is needed.</p>
]]></content:encoded>
			<wfw:commentRss>http://initbinder.com/articles/making-instance-variables-thread-safe.html/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Convert XML into POJO using HierarchicalStreamReader</title>
		<link>http://initbinder.com/articles/convert-xml-into-pojo-using-hierarchicalstreamreader.html</link>
		<comments>http://initbinder.com/articles/convert-xml-into-pojo-using-hierarchicalstreamreader.html#comments</comments>
		<pubDate>Sun, 29 Aug 2010 07:55:31 +0000</pubDate>
		<dc:creator>Alexander Zagniotov</dc:creator>
				<category><![CDATA[java]]></category>
		<category><![CDATA[xml]]></category>
		<category><![CDATA[HierarchicalStreamReader]]></category>
		<category><![CDATA[marshalling]]></category>
		<category><![CDATA[serialization]]></category>
		<category><![CDATA[xml marshalling]]></category>

		<guid isPermaLink="false">http://javabeans.asia/?p=744</guid>
		<description><![CDATA[In this example I would like to show how unmarshall XML into a POJO using HierarchicalStreamReader. I will introduce how to use  XStream and a custom XML-to-POJO converter, describe a case study and develop an application to show the solution. &#8230; <a href="http://initbinder.com/articles/convert-xml-into-pojo-using-hierarchicalstreamreader.html">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>In this example I would like to show how unmarshall XML into a POJO using HierarchicalStreamReader. I will introduce how to use  <a title="XStream" href="http://xstream.codehaus.org/" target="_blank">XStream</a> and a custom XML-to-POJO converter, describe a case study and develop an application to show the solution.</p>
<p><strong>Purchase History Example</strong><br />
Consider the following XML. It represents represents a purchase history of a customer, that has purchased different items during a week:</p>
<p>[xml]<br />
&lt;PURCHASE&gt;<br />
	&lt;ITEM&gt;<br />
		&lt;SUBITEM&gt;<br />
			&lt;CODE&gt;PDCT-001&lt;/CODE&gt;<br />
			&lt;NAME&gt;Product-1&lt;/NAME&gt;<br />
			&lt;DAY5&gt;1.75&lt;/DAY5&gt;<br />
			&lt;TOTAL&gt;1.75&lt;/TOTAL&gt;<br />
		&lt;/SUBITEM&gt;<br />
		&lt;SUBITEM&gt;<br />
			&lt;CODE&gt;PDCT-002&lt;/CODE&gt;<br />
			&lt;NAME&gt;Product-2&lt;/NAME&gt;<br />
			&lt;DAY7&gt;1.00&lt;/DAY7&gt;<br />
			&lt;DAY6&gt;1.75&lt;/DAY6&gt;<br />
			&lt;TOTAL&gt;2.75&lt;/TOTAL&gt;<br />
		&lt;/SUBITEM&gt;<br />
		&lt;SUBITEM&gt;<br />
			&lt;CODE&gt;PDCT-003&lt;/CODE&gt;<br />
			&lt;NAME&gt;Product-3&lt;/NAME&gt;<br />
			&lt;DAY7&gt;4.50&lt;/DAY7&gt;<br />
			&lt;DAY6&gt;2.00&lt;/DAY6&gt;<br />
			&lt;DAY5&gt;3.00&lt;/DAY5&gt;<br />
			&lt;DAY4&gt;2.25&lt;/DAY4&gt;<br />
			&lt;TOTAL&gt;11.75&lt;/TOTAL&gt;<br />
		&lt;/SUBITEM&gt;<br />
		&lt;SUBITEM&gt;<br />
			&lt;CODE&gt;PDCT-004&lt;/CODE&gt;<br />
			&lt;NAME&gt;Product-4&lt;/NAME&gt;<br />
			&lt;DAY7&gt;3.50&lt;/DAY7&gt;<br />
			&lt;DAY6&gt;3.75&lt;/DAY6&gt;<br />
			&lt;DAY5&gt;2.75&lt;/DAY5&gt;<br />
			&lt;DAY1&gt;3.75&lt;/DAY1&gt;<br />
			&lt;TOTAL&gt;13.75&lt;/TOTAL&gt;<br />
		&lt;/SUBITEM&gt;<br />
		&lt;REFERENCE&gt;9571-EDGDFG-DGSNJE-1837&lt;/REFERENCE&gt;<br />
		&lt;GRANDTOTAL&gt;30&lt;/GRANDTOTAL&gt;<br />
	&lt;/ITEM&gt;<br />
&lt;/PURCHASE&gt;<br />
[/xml]</p>
<p>To unmarshall the XML, I created three POJOs to represent the hierarchy of XML elements. The domain objects Purchase, Item and SubItem are involved.  The Purchase  has an Item, that has a collection of SubItem objects. My customer XML converter will transform customer&#8217;s purchase history from XML into a domain model using the POJOs.</p>
<p>I am not going to describe the full structure of the POJOs here, as I want to concentrate on talking about the XML converter . The source code as Eclipse project is attached to the current article, so you can download it.</p>
<p>I use <a title="XStream" href="http://xstream.codehaus.org/" target="_blank">XStream</a>, which is a simple open-source Java library for serialize objects to and from <a title="XML" href="http://en.wikipedia.org/wiki/XML" target="_blank">XML</a>. The following is the unit test case code snippet that show how I register my custom converter that is used for XML unmarshalling:</p>
<p>[java]<br />
XStream xstream = new XStream(new DomDriver());<br />
xstream.alias(&quot;PURCHASE&quot;, Purchase.class);<br />
xstream.registerConverter(new PurchaseConverter());<br />
Purchase purchase = (Purchase) xstream.fromXML(xmlContent);<br />
[/java]</p>
<p>I created an alias for Purchase that matches XML root element and registered my custom converter. The converter is a specific converter that knows how to handle this particular XML example, so it is not a generic solution. The converter code as follows:</p>
<p>[java]<br />
package asia.javabeans.streamreader.util;</p>
<p>import asia.javabeans.streamreader.domain.Purchase;<br />
import asia.javabeans.streamreader.domain.SubItem;</p>
<p>import com.thoughtworks.xstream.converters.Converter;<br />
import com.thoughtworks.xstream.converters.MarshallingContext;<br />
import com.thoughtworks.xstream.converters.UnmarshallingContext;<br />
import com.thoughtworks.xstream.io.HierarchicalStreamReader;<br />
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;</p>
<p>/**<br />
 * Current class represents converter for a Purchase XML.<br />
 *<br />
 * @author alexander.zagniotov<br />
 *<br />
 */<br />
final public class PurchaseConverter implements Converter {</p>
<p>	private static final int NUM_OF_DAYS = 7;</p>
<p>	public void marshal(Object value, HierarchicalStreamWriter writer,<br />
			MarshallingContext context) {<br />
	}</p>
<p>	public Object unmarshal(HierarchicalStreamReader reader,<br />
			UnmarshallingContext context) {</p>
<p>		Purchase purchase = new Purchase();</p>
<p>                //while there are unread XML element children and the reader has not reached the closing PURCHASE element<br />
		while (!(reader.getNodeName().equals(XmlElements.PURCHASE) &amp;&amp; !reader<br />
				.hasMoreChildren())) {</p>
<p>			if (reader.hasMoreChildren()) {<br />
				reader.moveDown(); // Move down to ITEM element</p>
<p>				// Process child SUBITEM elements of the parent ITEM<br />
				if (reader.getNodeName().equals(XmlElements.ITEM)) {<br />
					iterateThroughItemSubitems(reader, XmlElements.ITEM,<br />
							XmlElements.SUBITEM, purchase);<br />
				}<br />
			}<br />
                        //store value of REFERENCE element in a POJO<br />
			if (reader.getNodeName().equals(XmlElements.REFERENCE)) {<br />
				purchase.setReference(reader.getValue());<br />
			}</p>
<p>			reader.moveUp(); // Move back up to PURCHASE element<br />
		}</p>
<p>		return purchase;<br />
	}</p>
<p>	private Purchase iterateThroughItemSubitems(<br />
			HierarchicalStreamReader reader, String parentNameName,<br />
			String childNodeName, Purchase purchase) {<br />
		boolean hasSubitemNodes = true;</p>
<p>		while (reader.getNodeName().equals(parentNameName) &amp;&amp; hasSubitemNodes) {<br />
			reader.moveDown(); // Move down to SUBITEM element</p>
<p>			// We have SUBITEM element that we can read<br />
			if (reader.getNodeName().equals(childNodeName)) {<br />
				purchase = iterateThroughSubitemChildren(reader, childNodeName,<br />
						purchase);<br />
			} else { // No more children SUBITEM elements to read<br />
				break;<br />
			}</p>
<p>			reader.moveUp(); // Move back up to parent ITEM element<br />
			continue;<br />
		}</p>
<p>		return purchase;<br />
	}</p>
<p>	private Purchase iterateThroughSubitemChildren(<br />
			HierarchicalStreamReader reader, String nodeName, Purchase purchase) {<br />
		boolean hasChildrenNodes = true;</p>
<p>		SubItem subItem = new SubItem();</p>
<p>		while (reader.getNodeName().equals(nodeName) &amp;&amp; hasChildrenNodes) {<br />
			// Move down to the children of current SUBITEM element<br />
			reader.moveDown();</p>
<p>			if (reader.getNodeName().equals(XmlElements.CODE)) {<br />
				String subItemCode = reader.getValue();<br />
				subItem.setCode(subItemCode);<br />
				reader.moveUp(); // Move back up to parent SUBITEM<br />
				continue;<br />
			}</p>
<p>			if (reader.getNodeName().equals(XmlElements.NAME)) {<br />
				String subItemName = reader.getValue();<br />
				subItem.setName(subItemName);<br />
				reader.moveUp(); // Move back up to parent SUBITEM<br />
				continue;<br />
			}</p>
<p>			if (reader.getNodeName().startsWith(XmlElements.DAY)) {</p>
<p>				for (int i = 1; i &lt;= NUM_OF_DAYS; i++) {<br />
					String xmlDay = XmlElements.DAY + i;</p>
<p>					if (reader.getNodeName().equals(xmlDay)) {</p>
<p>						double hours = Double.parseDouble(reader.getValue());<br />
						subItem.addToDailyHours(xmlDay, hours);<br />
						purchase.addToGrandTotal(hours);<br />
						break;<br />
					}<br />
				}</p>
<p>				reader.moveUp(); // Move back up to parent SUBITEM<br />
				continue;<br />
			}</p>
<p>			if (reader.getNodeName().equals(XmlElements.TOTAL)) {<br />
				hasChildrenNodes = false; // This is the last child of parent SUBITEM</p>
<p>				String itemTotalStr = reader.getValue();<br />
				subItem.setItemTotal(Double.parseDouble(itemTotalStr));<br />
				purchase.getItem().addSubItem(subItem);<br />
				reader.moveUp(); // Move back up to parent SUBITEM<br />
				continue;<br />
			}<br />
		}<br />
		return purchase;<br />
	}</p>
<p>	@SuppressWarnings(&quot;unchecked&quot;)<br />
	public boolean canConvert(Class clazz) {<br />
		return clazz.equals(Purchase.class);<br />
	}</p>
<p>}<br />
[/java]</p>
<p>As you can see, the key to operate a stream reader is to move it down to a child element for reading and back up to a parent element. Each time I move the reader down, it moves to an element that has not being read yet.</p>
<p><strong>Conclusion</strong></p>
<p>I presented a simple example where I show how to unmarshall XML into Java POJOs using HierarchicalStreamReader and <a title="XStream" href="http://xstream.codehaus.org/" target="_blank">XStream</a>. The <a href="http://initbinder.com/bunker/wp-content/uploads/2010/08/HierarchicalStreamReader.zip">source code</a> is attached.</p>
<p>I hope this tutorial was helpful to some of you,<br />
Regards</p>
]]></content:encoded>
			<wfw:commentRss>http://initbinder.com/articles/convert-xml-into-pojo-using-hierarchicalstreamreader.html/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Right Tool For the Right Job</title>
		<link>http://initbinder.com/articles/right-tool-for-the-right-job.html</link>
		<comments>http://initbinder.com/articles/right-tool-for-the-right-job.html#comments</comments>
		<pubDate>Sat, 28 Aug 2010 00:05:47 +0000</pubDate>
		<dc:creator>Alexander Zagniotov</dc:creator>
				<category><![CDATA[app servers]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[jboss]]></category>
		<category><![CDATA[tomcat]]></category>
		<category><![CDATA[j2ee]]></category>
		<category><![CDATA[jboss applications]]></category>
		<category><![CDATA[jboss5.x]]></category>
		<category><![CDATA[web-services]]></category>

		<guid isPermaLink="false">http://javabeans.asia/?p=739</guid>
		<description><![CDATA[I wanted to start a discussion what is the better choice for an application server when building an enterprise J2E application? Should one go for a Tomcat + Spring combination which provide light-weight simplified alternative to JEE container or should &#8230; <a href="http://initbinder.com/articles/right-tool-for-the-right-job.html">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>I wanted to start a discussion what is the better choice for an application server when building an enterprise J2E application? Should one go for a Tomcat + Spring combination which provide light-weight simplified alternative to JEE container or should more heavy weight app server like JBoss be considered?</p>
<p>I have found some resources on <a title="Stackoverflow" href="http://stackoverflow.com/" target="_blank">Stackoverflow</a> that provided me enough information to think about:</p>
<ol>
<li><a title="What are benefits of JBoss AS-based application architecture?" href="http://stackoverflow.com/questions/3143382/what-are-benefits-of-jboss-as-based-application-architecture" target="_blank">What are benefits of JBoss AS-based application architecture?</a></li>
<li><a title="When to ditch a J2EE container (i.e. JBoss) for straight Tomcat" href="http://stackoverflow.com/questions/697805/when-to-ditch-a-j2ee-container-i-e-jboss-for-straight-tomcat" target="_blank">When to ditch a J2EE container (i.e. JBoss) for straight Tomcat</a></li>
<li><a title="Should I go with Tomcat or a full J2EE container?" href="http://stackoverflow.com/questions/844640/should-i-go-with-tomcat-or-a-full-j2ee-container" target="_blank">Should I go with Tomcat or a full J2EE container?</a></li>
</ol>
]]></content:encoded>
			<wfw:commentRss>http://initbinder.com/articles/right-tool-for-the-right-job.html/feed</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Are There No Other Developing Platforms?</title>
		<link>http://initbinder.com/articles/are-there-no-other-developing-platforms.html</link>
		<comments>http://initbinder.com/articles/are-there-no-other-developing-platforms.html#comments</comments>
		<pubDate>Sun, 11 Jul 2010 08:43:43 +0000</pubDate>
		<dc:creator>Alexander Zagniotov</dc:creator>
				<category><![CDATA[java]]></category>
		<category><![CDATA[off topic]]></category>

		<guid isPermaLink="false">http://javabeans.asia/?p=723</guid>
		<description><![CDATA[I came across a video called Java 4-Ever Trailer. Produced by guys at Java Zone.  Its a trailer about supposedly upcoming movie about an average family living in .NET world.  Their son grows up to be rebellious by starting to &#8230; <a href="http://initbinder.com/articles/are-there-no-other-developing-platforms.html">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>I came across a video called Java 4-Ever Trailer. Produced by guys at <a title="Java Zone - Java 4-Ever Trailer" href="http://jz10.java.no/" target="_blank">Java Zone</a>.  Its a trailer about supposedly upcoming movie about an average family living in .NET world.  Their son grows up to be rebellious by starting to experiment with Java as a teenager. I think it is absolutely hilarious. I had to remove a link to the video on Youtube, because its no longer available there.</p>
<p><a title="Java 4 Ever trailer" href="http://jz10.java.no/java-4-ever-trailer.html" target="_blank">http://jz10.java.no/java-4-ever-trailer.html</a></p>
<p>My favorite moment is when father screams on his last breath &#8220;&#8230; They actually enable us to send XML messages through SOAP&#8230; Through SOAP!! &#8230; &#8221;</p>
<p>Brilliant!</p>
]]></content:encoded>
			<wfw:commentRss>http://initbinder.com/articles/are-there-no-other-developing-platforms.html/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>
<!-- This Quick Cache file was built for (  initbinder.com/categories/java/feed ) in 0.28999 seconds, on May 18th, 2012 at 2:10 pm UTC. -->
<!-- This Quick Cache file will automatically expire ( and be re-built automatically ) on May 18th, 2012 at 3:10 pm UTC -->
