<?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>AnandhanSubbiah.com &#187; Java</title>
	<atom:link href="http://anandhansubbiah.com/blog/category/java/feed/" rel="self" type="application/rss+xml" />
	<link>http://anandhansubbiah.com/blog</link>
	<description>'Inspire and Innovate'</description>
	<lastBuildDate>Wed, 11 Jan 2012 03:30:01 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8.6</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Session Management in Axis</title>
		<link>http://anandhansubbiah.com/blog/session-management-in-axis/</link>
		<comments>http://anandhansubbiah.com/blog/session-management-in-axis/#comments</comments>
		<pubDate>Wed, 20 May 2009 19:51:11 +0000</pubDate>
		<dc:creator>Anandhan Subbiah</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Technical Articles]]></category>

		<guid isPermaLink="false">http://anandhansubbiah.com/blog/?p=437</guid>
		<description><![CDATA[There are different types of sessions, and the lifetime of the session may vary from one to another. Some sessions last for a few seconds while others last for the lifetime of the whole system. Axis2 architecture has been designed to support four types of sessions, and we observe that there are minor differences between [...]]]></description>
			<content:encoded><![CDATA[<p>There are different types of sessions, and the lifetime of the session may vary from one to another. Some sessions last for a few seconds while others last for the lifetime of the whole system. Axis2 architecture has been designed to support four types of sessions, and we observe that there are minor differences between one type and another. By considering the different types of use cases, Axis2 has the following four types of session scopes:</p>
<p>    <strong>1.Request</p>
<p>    2.SOAPSession</p>
<p>    3.Application</p>
<p>    4.Transport</strong></p>
<p>There are five types of contexts in the hierarchy, which have been listed below with a brief explanation:</p>
<p>    <strong>ConfigurationContext:</strong> This is the run-time representation of whole system. To start an Axis2 system, we need to have configuration context. The lifetime of configuration context will be the lifetime of the system. So, if we store some state (a property) it will last forever (until system shutdown).<br />
    <strong>ServiceGroupContext:</strong> In Axis2, we can deploy multiple services together as a service group. Then, the run-time representation of that is called ServiceGroupContext.<br />
   <strong> ServiceContext:</strong> This represents the run time of one service. The context lifetime will be the lifetime of the session. There can be one or many service contexts in the system, depending on the session scope of the corresponding service.<br />
    <strong>OperationContext:</strong> This context represents the lifetime of an MEP (Message Exchange Pattern). The lifetime of an operation context is, usually less than the lifetime of the ServiceContext.<br />
   <strong> MessageContext:</strong> The lifetime of an incoming message is represented by the message context. If two handlers in a given execution chain want to share data, then the best way to store them is in message context. One OperationContext may have one or more MessageContexts.</p>
<p><strong>Request Session Scope</strong></p>
<p>Request session scope is the default session scope in Axis2. When we deploy a service without knowing anything about session management, then our service will be deployed in request session scope. The lifetime of this session is limited to the method invocation lifetime, or request processing time. When we deploy a service in request scope, it simply means that we are not going to worry about the session management at all. So it is not like session management at all.</p>
<p><strong>SOAP Session Scope</strong></p>
<p>The idea of a SOAP session is to have a transport-independent way of managing session between two SOAP nodes, obviously between the client and the server. Here, Axis2 uses SOAP headers in order to manage the session. SOAP session scope has slightly longer lifetime as compared to a request session scope, and deploying a service in a SOAP session requires changing services.xml as well. Managing SOAP session requires both the client and the service to be aware of the sessions, that is, the client has to send the session-related data if it wants to access the same session, and the service has to validate the user using session-related data.</p>
<p><strong>Transport Session Scope</strong></p>
<p>In the case of Transport Session, Axis2 uses transport-related session management techniques to manage session. As an example, in the case of HTTP, it uses HTTP cookies to manage session. Then the lifetime of the session is controlled by the transport session and not by Axis2. What Axis2 does is store service context and ServiceGroupContext in the transport session object so that the service can access those contexts, as long as the session lives.</p>
<p>One of the key advantages that the Transport Session has over other sessions is that we can talk to multiple service groups within one transport session. In a SOAP session, we don&#8217;t have a way to communicate between two service groups, but with the transport session, we have that capability too. In this case, the number of service instances created depends on the number of transport sessions created.</p>
<p><strong>Application Scope</strong></p>
<p>Application scope has the longest lifetime as compared to all the others, and the lifetime of the application session is equal to the lifetime of the system. If we deploy a service in application scope, we will find that there is only one instance of the service implementation class. In addition to that, there will be only one ServiceContext for the deployed service. Considering the memory footprint, in the Axis2 world, it is better to deploy the service in application scope, if we don&#8217;t want to manage the session.</p>
<p><strong>Reference : Quickstart Apache Axis2<br />
by Deepal Jayasinghe</strong></p>
<p><a class="a2a_dd a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fanandhansubbiah.com%2Fblog%2Fsession-management-in-axis%2F&amp;title=Session%20Management%20in%20Axis" id="wpa2a_2"><img src="http://anandhansubbiah.com/blog/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://anandhansubbiah.com/blog/session-management-in-axis/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Villu &#8211; Music Review</title>
		<link>http://anandhansubbiah.com/blog/villu-music-review/</link>
		<comments>http://anandhansubbiah.com/blog/villu-music-review/#comments</comments>
		<pubDate>Wed, 17 Dec 2008 03:07:17 +0000</pubDate>
		<dc:creator>Anandhan Subbiah</dc:creator>
				<category><![CDATA[Cool Products]]></category>
		<category><![CDATA[Featured]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Movies]]></category>
		<category><![CDATA[Music]]></category>

		<guid isPermaLink="false">http://anandhansubbiah.com/blog/?p=313</guid>
		<description><![CDATA[
Directed by Prabhu Deva 
Produced by Karunamoorthy, Arun Pandian 
Written by Prabhu Deva 
Starring
          Vijay
          Nayanthara
          Vadivel
          Biju Menon
 [...]]]></description>
			<content:encoded><![CDATA[<p><img src="http://anandhansubbiah.com/blog/wp-content/uploads/2008/12/384px-villu-2.jpg" alt="384px-villu-2" title="384px-villu-2" width="384" height="600" class="alignnone size-full wp-image-316" /></p>
<p>Directed by <strong>Prabhu Deva </strong><br />
Produced by <strong>Karunamoorthy, Arun Pandian </strong><br />
Written by <strong>Prabhu Deva </strong><br />
Starring<br />
          <strong>Vijay<br />
          Nayanthara<br />
          Vadivel<br />
          Biju Menon<br />
          Prakash Raj</strong><br />
Music by <strong>Devi Sri Prasad </strong><br />
Cinematography <strong>Ravi Varman </strong></p>
<p>Devi Sri Prasad has already composed a music album for vijay and is well known for his peppy and energetic music. Sachin had really good music as the focus was on the story and not Vijay the actor. The script is different this time around as the music director has tried to score the music for a typical Vijay movie.If I were to rate the music director on that basis he has done a commendable job.</p>
<p><strong>Dheemthanakka Thillana (Devi Sri Prasad , Divya)</strong><br />
 Devi Sri Prasad is all about the energy he brings to the table and this song is a classic example. This is a fast paced song with a catchy tune. It is not electrifying by any means but the heavy voice of Divya and Devi Sri Prasad seems to fit the bill perfectly for this song.</p>
<p><strong>Jalsa ( Baba Sehgal , Rita)</strong><br />
Baba Sehgal is an iconic Indian rapper who was famous in the mid 1990s. I think this is the first time he has sung a tamil song. He has done a decent job and the song is tailor made for his voice. The heavy beats in the middle are interesting. Baba gets to Rap a bit as well . Rita does not have a lot to do in this Sehgal dominated song. </p>
<p><strong>Nee Kobapattal (Sagar)</strong><br />
The only slow song in the album. There is no dearth of orchestration even in this song . Sagar seems to be an exact replica of Devi Sri Prasad as his voice is very similar to that of the music director. The news is that Devi Sri Prasad has a twin named Sagar who is currently a playback singer.This is just an average song which passes muster.</p>
<p><strong>Vada Maapilley (Tippu , Rita , Vadivel)</strong><br />
A rhythmic song with interesting tune and beats. The song seems to be inspired from the ganna songs from the 80&#8217;s. The song definitely reminded me of the yesteryear block buster Surangini. I was not all that impressed but this might really interest the front benches and folks who like the gana genre.</p>
<p><strong>Daddy Mummy (Divya)</strong><br />
The song starts with a nice piano interlude and transforms into a nice rhtymic song. The tune is very catchy and Divya&#8217;s voice is unique. The lyrics are simply horrible and are a huge let down.</p>
<p><strong>Hey Rama ( Amalraj , Kovai Sarala)</strong><br />
This fast Kuthu Song has a very catchy tune. Kovai Sarala , the famous comdian is the surprise package. This is most likely when Vijay is introduced in the movie.<br />
<strong><br />
Are You Krazy (Divya)</strong><br />
Obviously this song is supposed to be funny and nothing else. There is nothing to review other than the fact that this piece could have been avoided.</p>
<p>Overall the album is decent and is strictly aimed at the actors fans. A genuine music lover will find this album average at the most.</p>
<p>Devi Sri Prasad has the talent to compose a much better album. That said he has delivered on the commercial front and the fast numbers will be a huge hit with the actor&#8217;s fans.</p>
<p><a class="a2a_dd a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fanandhansubbiah.com%2Fblog%2Fvillu-music-review%2F&amp;title=Villu%20%26%238211%3B%20Music%20Review" id="wpa2a_4"><img src="http://anandhansubbiah.com/blog/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://anandhansubbiah.com/blog/villu-music-review/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Writing your first Android Application.</title>
		<link>http://anandhansubbiah.com/blog/writing-your-first-android-application/</link>
		<comments>http://anandhansubbiah.com/blog/writing-your-first-android-application/#comments</comments>
		<pubDate>Thu, 09 Oct 2008 00:47:22 +0000</pubDate>
		<dc:creator>Anandhan Subbiah</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Technical Articles]]></category>
		<category><![CDATA[Android]]></category>

		<guid isPermaLink="false">http://anandhansubbiah.com/blog/?p=260</guid>
		<description><![CDATA[Setting Up Your Development Environment
Android applications, like most mobile phone applications, are developed in a host-target development environment. In other words, you develop your application on a host computer (where resources are abundant), and download it to a target mobile phone for testing and ultimate use.
To write your own Android mobile phone applications, you&#8217;ll first [...]]]></description>
			<content:encoded><![CDATA[<p><strong>Setting Up Your Development Environment</strong></p>
<p>Android applications, like most mobile phone applications, are developed in a host-target development environment. In other words, you develop your application on a host computer (where resources are abundant), and download it to a target mobile phone for testing and ultimate use.</p>
<p>To write your own Android mobile phone applications, you&#8217;ll first need to collect the required tools and set up an appropriate development environment on your PC or Mac. </p>
<p>The Android SDK supports several different development environments. For this book we will focus on using Eclipse, because it is the best integrated with the SDK, and, hey, it&#8217;s free. No matter which operating system you are using, you will need essentially the same set of tools:</p>
<p>    * The Eclipse Integrated Development Environment<br />
    * Sun&#8217;s Java Development Kit (JDK)<br />
    * The Android Software Developer&#8217;s Kit (SDK)<br />
    *  A special Eclipse plug in: the Android Developer Tool (ADT)</p>
<p><strong> Creating an Android Development Environment</strong></p>
<p>The Android Software Development Kit supports Windows (XP and Vista), Linux (Ubuntu Dapper Drake), and Mac OS X (10.4.8 or later) as host development environments. Installation of the SDK is substantially the same for any of the operating systems, and most of this description applies equally to all of them. Where the procedure differs, we will clearly tell you what to do for each environment.</p>
<p>   1.Install Eclipse:<br />
   2.Check for Required Plugins<br />
   3.Install JDK: The Android SDK requires JDK version 5 or version 6.<br />
   4. Install Android SDK: This is where you&#8217;d start if you already have the right versions of Eclipse and the JDK loaded. The Android SDK is distributed through Google&#8217;s code site, http://code.google.com/android/download.html.<br />
  5. Update Environment Variables: To make it easier to launch the Android tools, add the tools directory to your path.<br />
  6. Install the Android Plugin (ADT):  https://dl-ssl.google.com/android/eclipse.</p>
<p><strong> Starting a New Android Application: HelloWorld</strong></p>
<p>Several components are needed to build an Android application. Fortunately, the Eclipse IDE with the Android plug-in automates a lot of the work needed to create and maintain these components. We will start by using the IDE to create a project for our application. Start up Eclipse and select &#8220;File -> New -> Project&#8230;&#8221; from the menu bar (be sure to select &#8220;Project&#8230;,&#8221; not &#8220;Java Project&#8221;).</p>
<p>Select &#8220;Android Project&#8221; and click &#8220;Next&#8221; to get the &#8220;New Android Project&#8221; dialog box.</p>
<p>We&#8217;ll use &#8220;HelloWorld&#8221; as the name for both the Project and the Application. You don&#8217;t need to change the button or checkbox selections, and we&#8217;ll use the package name com.oreilly.helloworld as shown.</p>
<p>Every Android application has to have at least one Activity (an executable that usually has a user interface), so let&#8217;s say we&#8217;re going to include an Activity called HelloWorldActivity, as shown in the dialog box. Click &#8220;Finish,&#8221; and the Android Development Kit does a number of things for you, to make your life easier as a developer. In [figure to come], I&#8217;ve expanded the tree in the Package Explorer window to show some of the files and directories that the ADK created.</p>
<p>The ADK created a HelloWorld directory in the default Eclipse workspace for your project. It also created subdirectories for your source files (.src), references to the Android Library, assets, resources (.res), and a manifest file (AndoidManifest.xml). In each of the subdirectories it created another level of subdirectories as appropriate. Let&#8217;s take a quick look at them:</p>
<p><strong>Sources (under .src)</strong></p>
<p>        * Contains a directory structure that corresponds to the package name you gave for your application: in this case, com.android.helloworld.<br />
        *Contains a Java template for the Activity you indicated was in the application (HelloWorldActivity) and a directory of resource references (R.java). We&#8217;ll come back to R.java later.</p>
<p><strong>Android Library</strong></p>
<p>    This is just what it says. If you like, you can expand the android.jar tree and see the names of the modules included in the library. This is where your application will go for Android library references.</p>
<p><strong>assets</strong></p>
<p>    Files you want to bundle with your application. We won&#8217;t have any for HelloWorld.</p>
<p><strong>Resources (under .res)</strong></p>
<p>        * Drawable resources are any images, bitmaps, etc. that you need for your application. For HelloWorld, the ADK has supplied us with the default Android icon, and that&#8217;s all we&#8217;ll need.<br />
        * Layout resources tell Android how to arrange items on the screen when the application runs. These resources are XML files that give you quite a bit of freedom in laying out the screen for different purposes. For HelloWorld, we&#8217;ll just use the defaults generated by the ADK<br />
        * Values are constants, strings, etc. available for use by your application. Keeping them outside the sources makes it easier to customize the application, such as adapting it for different languages.</p>
<p><strong>Manifest (AndroidManifest.xml)</strong></p>
<p>    This is another XML file that tells the Android build system what it needs to know to build and package your application so it can be installed on an Android phone or the emulator. This file has its own specialized editor, which we&#8217;ll describe as we get to more complicated applications.</p>
<p><strong>Double Click on HelloWorldActivity.java</strong><br />
Looking quickly at the template code that the ADK has provided for us, we can note several things:</p>
<p>    *The ADK has included the package reference we asked for, which is consistent with the directory structure it created.<br />
    *It has also created a (collapsed) set of imports for the library references it knows we need.<br />
    *It created a class definition for the Activity we said we wanted (HelloWorldActivity) including a method called OnCreate.</p>
<p>      For the moment, don&#8217;t worry about the parameter passed into OnCreate. The icicle Bundle is a way of passing data between activities and storing data between instantiations of the same Activity. We won&#8217;t need to use this for HelloWorld.<br />
    * One special line of code has been included in OnCreate:</p>
<p>      setContentView (R.layout.main);</p>
<p>      Remember that Android uses layouts to define screen layouts on the target, and that main.xml was the name of the default layout file that the ADK created for us under .res/layout. The R.java file is generated automatically and contains java references for each of the resources under .res. You will never need to edit the R.java file by hand— the ADK takes care of it as you add, change or delete resources.</p>
<p><strong>Double Click on main.xml</strong><br />
Again, let&#8217;s look at the key features of this template code:</p>
<p>    * Like any other XML file, this one starts with a reference to the XML version and encoding used.<br />
    * LinearLayout is one of the screen layout formats provided by the ADK. There are several others, which can be combined hierarchically to create very complex screen layouts. For our purposes, a simple linear layout is fine.</p>
<p>      Within the LinearLayout definition:<br />
          o The code:</p>
<p>            xmlns:android=&#8221;http://schemas.android.com/apk/res/android&#8221;</p>
<p>            identifies the XML schema being used.<br />
          o The code:</p>
<p>            android:orientation=&#8221;vertical&#8221;<br />
            android:layout_width=&#8221;fill_parent&#8221;<br />
            android:layout_height=&#8221;fill_parent&#8221;</p>
<p>            defines an orientation, width and height for the entire scope of the layout.<br />
    *TextView describes how to handle text within&#8230;. It resembles the text boxes you may have encountered when programming in other graphical environments.</p>
<p>      Within the TextView definition:<br />
          o The code:</p>
<p>            android:layout_width=&#8221;fill_parent&#8221;<br />
            android:layout_height=&#8221;wrap_content&#8221;</p>
<p>            a width and height for the TextView box.<br />
          o The code:</p>
<p>            android:text=&#8221;Hello World, HelloWorldActivity&#8221;</p>
<p>            provides some text to display in the TextView. By a stroke of luck, the ADK has already included text that is almost what we wanted to display anyway. Just to show them who&#8217;s boss, change the android:text line to say &#8220;Hello, Android!&#8221;, or something else equally clever:</p>
<p>            android:text=&#8221;Hello, Android!&#8221;</p>
<p>if you edit the file, save it either from the Eclipse File menu (File -> Save) or by clicking on the diskette icon in the menu bar.</p>
<p>Believe it or not, we&#8217;re done. We don&#8217;t have to write a single line of Java to create this application.</p>
<p>From the Eclipse menu bar, select Run -> Run. A &#8220;Run As&#8221; dialog box will pop up. Select &#8220;Android Application&#8221; from the list and you can see your first Android Application.</p>
<p><strong>Reference : Android Application Development, 1st Edition<br />
By: Rick Rogers</strong></p>
<p><a class="a2a_dd a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fanandhansubbiah.com%2Fblog%2Fwriting-your-first-android-application%2F&amp;title=Writing%20your%20first%20Android%20Application." id="wpa2a_6"><img src="http://anandhansubbiah.com/blog/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://anandhansubbiah.com/blog/writing-your-first-android-application/feed/</wfw:commentRss>
		<slash:comments>11</slash:comments>
		</item>
		<item>
		<title>Rewrite convention and optimize your code for maintainability</title>
		<link>http://anandhansubbiah.com/blog/optimize-your-code-for-maintainability/</link>
		<comments>http://anandhansubbiah.com/blog/optimize-your-code-for-maintainability/#comments</comments>
		<pubDate>Thu, 07 Aug 2008 14:56:33 +0000</pubDate>
		<dc:creator>Anandhan Subbiah</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Technical Articles]]></category>
		<category><![CDATA[code maintainability]]></category>
		<category><![CDATA[code review]]></category>
		<category><![CDATA[technology]]></category>

		<guid isPermaLink="false">http://anandhansubbiah.com/blog/?p=197</guid>
		<description><![CDATA[The vast majority of programmers end up having to maintain code written by someone else. I was reading this article in javaworld.com and it really was in line with my thought process.
The original source is here : http://www.javaworld.com/javaworld/jw-07-2008/jw-07-harmful-idioms.html
Four harmful Java idioms, and how to fix them
Rewrite convention and optimize your code for maintainability
By John O&#8217;Hanley, [...]]]></description>
			<content:encoded><![CDATA[<p>The vast majority of programmers end up having to maintain code written by someone else. I was reading this article in javaworld.com and it really was in line with my thought process.</p>
<p>The original source is here : http://www.javaworld.com/javaworld/jw-07-2008/jw-07-harmful-idioms.html</p>
<p>Four harmful Java idioms, and how to fix them<br />
Rewrite convention and optimize your code for maintainability</p>
<p>By John O&#8217;Hanley, JavaWorld.com, 07/29/08</p>
<p>Idioms in any programming language help you get your bearings and provide structure when you start writing code. But, as John O&#8217;Hanley points out, some Java programming idioms are both widespread and harmful, having a negative influence on code maintainability. Read on if you&#8217;re ready to break with convention, rewrite four harmful Java idioms, and optimize your code for maintainability.</p>
<p>Coding idioms exist to make life easier for programmers &#8212; in particular for maintenance programmers, who are usually reading code produced by someone else. Coding conventions are fundamentally about showing compassion for these maintenance workers; the conventions you choose should allow them to read, understand, and use your code as quickly and as painlessly as possible. The more you optimize your coding style for the mental experience of those who will be maintaining your code, the more compassionate your code becomes, and the more quickly it will be understood.</p>
<p>Similarly, higher-level idioms (immutability and package structure, for example) aim to both improve the design and make code easier to understand. In fact, some might say that &#8220;improving the design&#8221; and &#8220;making the code easier to understand&#8221; are, in the end, one and the same thing.</p>
<p>In this article, you&#8217;ll see that some popular idioms should be changed in favor of alternatives that are demonstrably more compassionate towards the reader. One might argue that any idioms that are already widespread should never be abandoned, simply because they are expected by most readers. However, reader expectations are only one part of the equation, and they shouldn&#8217;t necessarily override all other considerations. The fundamental question should not be &#8220;Does the reader expect this?&#8221; but rather &#8220;How fast will the reader understand it?&#8221; I&#8217;ll approach four different problematic &#8212; but common! &#8212; idioms in turn.<br />
Local variables, method arguments, and fields: Which is which?</p>
<p>When trying to understand code, a reader often needs to answer a simple question: Where did this data come from? In particular, when trying to understand a method, a reader needs to know which items are local variables, which are fields, and which are method arguments. To exercise compassion for your reader, and to absolutely minimize the effort required to understand your code, it&#8217;s likely best to use a simple naming convention to distinguish between these three cases.</p>
<p>Many organizations qualify field variables with this to distinguish them from other kinds of variables. That&#8217;s good, but it doesn&#8217;t go far enough: there should be a convention to distinguish method arguments as well. The logic that justifies naming conventions for fields also applies to method arguments, and for exactly the same reasons.</p>
<p>Listing 1 offers an example of an equals() method that does not distinguish between the three kinds of variables.<br />
Listing 1. A method that doesn&#8217;t distinguish between variable types</p>
<p>public boolean equals (Object arg) {<br />
  if (! (arg instanceof Range)) return false;<br />
  Range other = (Range) arg;<br />
  return start.equals(other.start) &#038;&#038; end.equals(other.end);<br />
}</p>
<p>The French writer Marcel Proust was famous for analyzing human experience to microscopic levels. How would a modern-day Proust describe the experience of reading this equals() method? When you try to understand it, you experience a small amount of discomfort when you encounter start, because it&#8217;s suddenly referenced out of the blue. Your brain hits a speed bump as it encounters something it hasn&#8217;t seen before &#8212; Uh oh, what&#8217;s this? After a moment, through a tedious process of elimination (the length of which is proportional to the size of the method), you will eventually figure out that start is actually a field. The same sort of trivial and tedious reasoning is also needed to distinguish method arguments from other types of data.</p>
<p>Listing 1 isn&#8217;t very long. If the method were larger, then the effort necessary to understand it would be increased as well.</p>
<p>Why make the reader experience this jolt, this moment of confusion, however slight? Why not spare your readers the unpleasant experience of not understanding something immediately? Why force them to figure it out? If a simple naming convention can allow the reader to distinguish the three kinds of variables almost unconsciously, then shouldn&#8217;t it be used? As Steve McConnell says in Code Complete, &#8220;It&#8217;s OK to figure out murder mysteries, but you shouldn&#8217;t need to figure out code. You should be able to read it.&#8221;</p>
<p>One might argue that this is why fields should be declared at the start of a class. But that isn&#8217;t a good solution, because it forces the reader to either memorize field names or perform a lookup operation in a distant section of the class. Either option makes the reader do more work. And the whole point is to exercise maximal compassion for the readers, and let them read and understand your code with minimal effort.</p>
<p>Listing 2 contains the example code from Listing 1, rewritten. It uses a naming convention in which:</p>
<p>    * Method arguments are prefixed with a<br />
    * Fields are prefixed with f<br />
    * Local variables have no prefix at all</p>
<p>Listing 2. Variable types are now clearly distinguished</p>
<p>public boolean equals (Object aOther) {<br />
  if (! (aOther instanceof Range)) return false;<br />
  Range other = (Range) aOther;<br />
  return fStart.equals(other.fStart) &#038;&#038; fEnd.equals(other.fEnd);<br />
}</p>
<p>You might object to the style on display in Listing 2, protesting that &#8220;Hungarian notation is obsolete.&#8221; But that objection is erroneous: Hungarian notation specifies type information. The above naming convention says nothing about type. Rather, it distinguishes between fields, arguments, and local variables. These are two completely different concepts.</p>
<p>The idea of using naming conventions in this way may seem trivial, but it isn&#8217;t: when such conventions are used throughout your code, the effort needed to understand it is significantly reduced, because you can perform more operations without thinking about them.</p>
<p>    &#8220;By relieving the brain of all unnecessary work, a good notation sets it free to concentrate on more advanced problems, and in effect increases the mental power of the race. Before the introduction of the Arabic notation, multiplication was difficult, and the division even of integers called into play the highest mathematical faculties. Probably nothing in the modern world would have more astonished a Greek mathematician than to learn that &#8230; a large proportion of the population of Western Europe could perform the operation of division for the largest numbers. This fact would have seemed to him a sheer impossibility &#8230; Our modern power of easy reckoning with decimal fractions is the almost miraculous result of the gradual discovery of a perfect notation.&#8221;<br />
    &#8212; Alfred North Whitehead, An Introduction To Mathematics</p>
<p>Package-by-layer: Preventing the use of package-private scope</p>
<p>A common way of dividing up an application is package-by-layer:</p>
<p>    * com.blah.action<br />
    * com.blah.dao<br />
    * com.blah.model<br />
    * com.blah.util</p>
<p>In other words, items belonging to any one feature are spread out over different packages, according to what might be called behavioral categories. Because the items in each feature need to be visible to each other, this implies that nearly all of the classes in such an application are public.</p>
<p>In effect, this common packaging style throws package-private scope out the window. Package-private scope isn&#8217;t simply ignored; you&#8217;re actually prevented from using it. Now, package-private scope was chosen as the default scope by the designers of the Java programming language. This choice was made, of course, to push you gently in the direction of better design &#8212; to start with minimal scope, and increase it only if necessary. (This is the usual &#8220;minimize ripple effects by keeping secrets&#8221; technique, an idea at the very heart of object programming.) For some strange reason, a significant part of the Java community has, by adopting the package-by-layer convention, rejected an important way of minimizing scope. This seems unjustified.</p>
<p>An alternate style is package-by-feature:</p>
<p>    * com.blah.painting<br />
    * com.blah.buyer<br />
    * com.blah.seller<br />
    * com.blah.auction<br />
    * com.blah.webmaster<br />
    * com.blah.useraccess<br />
    * com.blah.util</p>
<p>Here, items are not grouped according to their behavioral style. Instead, the behavior of individual classes is treated as an implementation detail, and classes are grouped according to the highest possible level of abstraction &#8212; the level of the feature &#8212; wherein all items related to a feature (and only to that feature) reside in one and the same package. This is not a revolutionary or heretical idea; this is exactly what packages were created for in the first place.</p>
<p>For example, in a Web application, the com.blah.painting package might consist of these items:</p>
<p>    * Painting.java: A model object<br />
    * PaintingDAO.java: A data access object<br />
    * PaintingAction.java: A controller or action object<br />
    * statements.sql: The SQL statements used by the DAO<br />
    * view.jsp: The JSP used to render the result to the user</p>
<p>It&#8217;s important to note that, in this style, each package should contain all items related to a feature (and only that feature). In particular, the package may contain files other than Java source code. In package-by-feature, the ideal is to pass the deletion test: you should be able to delete a feature by deleting a single directory, without leaving behind any cruft.</p>
<p>The benefits of this style over package-by-layer are compelling:</p>
<p>    *</p>
<p>      Packages have much higher cohesion and modularity. Coupling between packages is minimized.<br />
    *</p>
<p>      Code is much more self-documenting. The reader gets a general idea of what features are included just by reading the package names. In Code Complete, Steve McConnell refers to self-documenting code as &#8220;the Holy Grail of legibility.&#8221;<br />
    *</p>
<p>      The design still honors the idea of separation of layers, simply by using separate classes within each feature.<br />
    *</p>
<p>      Related items are in the same place. There is no need to navigate around the source tree to edit closely related items.<br />
    *</p>
<p>      Items are package-private by default, as they should be. If an item needs to be visible from another package, then it&#8217;s changed to public. (Note that changing a class to public does not mean that all of its members should be made public as well; there can be a mixture of public and package-private members in the same class.)<br />
    *</p>
<p>      Deleting a feature is often as simple as deleting a single item: a directory.<br />
    *</p>
<p>      There are fewer items in each package, and the overall package structure evolves more naturally. For example, if a package gets too large, then it can be refactored as desired into two or more new packages. The alternative package-by-layer style, however, does not scale or evolve in this way at all: its packages contain an arbitrarily large number of classes, and you cannot easily refactor the package structure.</p>
<p>Some frameworks promote a package-by-layer style with conventional package names as a purported advantage: because conventional package names are used, programmers always know where to navigate to find items. But why force them to navigate at all? With the alternative package-by-feature style, such tedious navigation is usually not needed, so it entirely transcends the need for any such naming convention.</p>
<p>    &#8220;The single most important factor that distinguishes a well-designed module from a poorly designed one is the degree to which the module hides its internal data and other implementation details from other modules.&#8221;<br />
    &#8212; Joshua Bloch, Effective Java</p>
<p>JavaBeans: Why use them when immutables will do?</p>
<p>Immutable objects are objects that do not change state (their data, in other words) after construction. Martin Odersky, the principal creator of Scala, has recently praised the qualities of immutables. In Effective Java, Joshua Bloch makes a very convincing case in favor of strongly preferring immutable objects. To summarize Bloch&#8217;s points, immutables:</p>
<p>    * Are simple<br />
    * Are thread-safe, and require no synchronization<br />
    * Can be shared freely<br />
    * Never need to be defensively copied<br />
    * Never need a copy constructor, or a clone() method<br />
    * Make good building blocks for other classes<br />
    * Make good Map keys and Set elements<br />
    * Have failure atomicity &#8212; that is, they cannot be left in an invalid state when an error occurs</p>
<p>&#8220;Classes should be immutable unless there is a very good reason for making them mutable,&#8221; says Bloch. But his advice seems to have been largely ignored. In place of immutable objects, most applications use JavaBeans (or something similar) instead. JavaBean objects are significantly more complex than immutables. Their complexity arises from their large state space. In a rough sense, you might think of a JavaBean as the diametric opposite of an immutable object: it allows maximal mutability.</p>
<p>It&#8217;s common to use JavaBeans to model database records. Is that an appropriate design? Think of it this way: if you were modeling a row from a database ResultSet, without any preconceptions or framework constraints whatsoever, what would your design be like? Would it be similar to a JavaBean, or would it be significantly different?</p>
<p>I think it would be enormously different:</p>
<p>    *</p>
<p>      It would likely not include a no-argument constructor, as such constructors carry no data. Does it make sense to model a database ResultSet by creating objects that by design can carry no data, even temporarily? Does a no-argument constructor suggest itself naturally to the mind for this domain? No, it doesn&#8217;t. (It&#8217;s true that data is often optional, but how often are all columns in a ResultSet optional?)<br />
    *</p>
<p>      It would likely not have anything to say about events and listeners.<br />
    *</p>
<p>      It would likely not force you to use mutable objects. In Web applications in particular, model objects often exist only for the duration of a single request. Such objects aren&#8217;t long-lived, and don&#8217;t need to change state in response to user actions.<br />
    *</p>
<p>      It would likely define a data validation mechanism. Such validation is one of the most important features of database apps, and should be supported directly in the model. (Remember the first thing you learned about objects: an object encapsulates both data and operations on the data. In this case, the operations are the validations.)<br />
    *</p>
<p>      The validation mechanism would allow for reporting errors to the end user.</p>
<p>The JavaBeans specification was created for a very particular problem domain: that of manipulating graphical widgets at design time. The specification makes absolutely no mention of databases, because it was not created with databases in mind. As a result, it&#8217;s not surprising that JavaBeans aren&#8217;t a very natural choice for the problem of modeling database records.</p>
<p>From a practical perspective, many widely-used frameworks require application programmers to use JavaBeans (or something similar) to model database records. This is deeply unfortunate, because it doesn&#8217;t allow programmers to take advantage of the many positive qualities of immutable objects.</p>
<p>Private members: Why put them up front?</p>
<p>Old Hollywood movies usually start with the credits &#8212; all of the credits. In a similar way, most Java classes place implementation details (the private members) first. Listing 3 shows a typical example of this style.<br />
Listing 3. Private members, listed up front</p>
<p>public class OilWell implements EnergySource {<br />
   private Long id;<br />
   private String name;<br />
   private String location;<br />
   private Date discoveryDate;<br />
   private Long totalReserves;<br />
   private Long productionToDate;</p>
<p>   public Long getId() {<br />
      return id;<br />
   }<br />
   public void setId(Long id) {<br />
      this.id = id;<br />
   }</p>
<p>  //..elided<br />
}</p>
<p>However, placing private items last, not first, seems to show more compassion for the reader. When trying to understand something &#8212; anything &#8212; you should move from the general to the specific. More precisely, you should move from a higher to a lower level of abstraction. If you do the reverse, then initially the reader will likely not know the point of the whole thing, or grasp how things work together, and will be confused by trying to remember a number of potentially disconnected facts.</p>
<p>The whole point of abstraction is to allow you to ignore details. The higher the level of abstraction, the more details you can ignore. The more details the readers of a class can ignore, the happier they are. Holding many details in your head is painful, so fewer details are better. Thus, placing private items last seems more compassionate, as it puts off details that may not be necessary at all for the reader&#8217;s current task (whatever that may be).</p>
<p>Originally, the C++ programming culture placed private items first, just as in Java. However, unlike the Java community, the C++ community quickly came to realize that this was an unhelpful convention, and it is now reversed. Here is a comment from a typical C++ style guide:</p>
<p>    Notice that the public interface is placed first in the class, protected next, and private last. The reasons are:</p>
<p>        * programmers should care about a class&#8217;s interface more than implementation<br />
        * when programmers need to use a class they need the interface not the implementation</p>
<p>    It makes sense then to have the interface first. Placing implementation, the private section, first, is a historical accident, as the first examples used the private-first layout. Over time emphasis has switched, de-emphasizing a class&#8217;s interface over implementation details.</p>
<p>Similarly, the Imperial College London C++ Style Guide says, &#8220;By placing the public section first, everything that is of interest to a user is gathered in the beginning of the class definition. The protected section may be of interest to designers when considering inheriting from the class. The private section contains details that should have the least general interest.&#8221;</p>
<p>One might object that that readers should use Javadoc when trying to understand a class, and not the source code. This argument doesn&#8217;t hold, however, because Javadoc includes no information regarding implementation details. When maintaining a class, a programmer clearly needs access to the source code.</p>
<p>For all kinds of technical documentation, it&#8217;s commonplace to put high-level information at the start &#8212; the table of contents of a book, for instance, or the abstract of an academic paper. Why should a Java class be an exception to this rule? Placing private members first just seems like a bad habit waiting to be broken. The reason it exists in the first place is likely early coding style documents, such as the Coding Conventions published by Sun. As Joshua Bloch noted, &#8220;I wouldn&#8217;t take that document [Sun's Coding Conventions] too seriously. It is not actively maintained or used at Sun.&#8221;</p>
<p>It seems best to arrange code to imitate the same order used by Javadoc: first the constructors, then non-private methods, and finally private fields and methods. That&#8217;s the only style in which the reader moves naturally from a higher to a lower level of abstraction.<br />
In conclusion</p>
<p>I have argued in this article that four common Java idioms should be modified. The ultimate justification for such changes is that they will make code demonstrably easier to read, understand, and use &#8212; and, in the process, they will exhibit more compassion for the mental experience of the reader. In the case of immutability and packaging style, they will also nudge you in the direction of improved design.</p>
<p>In summary, I suggest that the following idioms should be favored as the preferred style:</p>
<p>    * Use a naming convention to distinguish three kinds of data, not two: local variables, fields, and method arguments.<br />
    * Prefer the package-by-feature style over package-by-layer.<br />
    * Prefer immutable objects over JavaBeans.<br />
    * Order items in a class in terms of decreasing scope, with private items appearing last.</p>
<p>If the arguments presented in this article are correct, then they lead to a question: Why do harmful idioms still persist in Java programming culture, after so many years? In answer to that question, I would offer the following speculation. Style guides and other tools published in the early years of Java didn&#8217;t have the benefit of long experience. They got most things right, but a few things wrong. This is completely natural, and doesn&#8217;t reflect poorly on their creators. Some of these items, which were published by Sun Microsystems, were very widely imitated. They had a very strong influence, and were often treated as authoritative. Perhaps they were treated with a little too much deference.</p>
<p>The few harmful idioms that were created in the early days of Java have persisted because they become popular, ingrained habits &#8212; and perhaps because of a little bit of consensus trance or groupthink, wherein the fact that something is popular or treated as authoritative often overrides any opposing viewpoint.</p>
<p>Will Java programming culture gradually change these bad habits, or will they persist, in spite of their defects? My guess is that, unfortunately, they will remain a part of Java programming culture. But I would love to be proved wrong! </p>
<p><a class="a2a_dd a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fanandhansubbiah.com%2Fblog%2Foptimize-your-code-for-maintainability%2F&amp;title=Rewrite%20convention%20and%20optimize%20your%20code%20for%20maintainability" id="wpa2a_8"><img src="http://anandhansubbiah.com/blog/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://anandhansubbiah.com/blog/optimize-your-code-for-maintainability/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Is Java the best programming language (Still) ?</title>
		<link>http://anandhansubbiah.com/blog/is-java-the-best-programming-language-still/</link>
		<comments>http://anandhansubbiah.com/blog/is-java-the-best-programming-language-still/#comments</comments>
		<pubDate>Wed, 04 Jun 2008 16:22:10 +0000</pubDate>
		<dc:creator>Anandhan Subbiah</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Technical Articles]]></category>
		<category><![CDATA[forum]]></category>
		<category><![CDATA[java discussion]]></category>

		<guid isPermaLink="false">http://anandhansubbiah.com/blog/?p=174</guid>
		<description><![CDATA[I thought this would be a discussion worth having with all those scripting languages floating around.
Please click on the link below to share your thoughts :
Is Java the best programming language ?
]]></description>
			<content:encoded><![CDATA[<p>I thought this would be a discussion worth having with all those scripting languages floating around.</p>
<p>Please click on the link below to share your thoughts :</p>
<p><a href="http://anandhansubbiah.com/forum/comments.php?DiscussionID=1&#038;page=1#Item_1">Is Java the best programming language ?</a></p>
<p><a class="a2a_dd a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fanandhansubbiah.com%2Fblog%2Fis-java-the-best-programming-language-still%2F&amp;title=Is%20Java%20the%20best%20programming%20language%20%28Still%29%20%3F" id="wpa2a_10"><img src="http://anandhansubbiah.com/blog/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://anandhansubbiah.com/blog/is-java-the-best-programming-language-still/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>useful mvn commands</title>
		<link>http://anandhansubbiah.com/blog/useful-mvn-commands/</link>
		<comments>http://anandhansubbiah.com/blog/useful-mvn-commands/#comments</comments>
		<pubDate>Tue, 27 May 2008 15:53:22 +0000</pubDate>
		<dc:creator>Anandhan Subbiah</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[mvn]]></category>
		<category><![CDATA[mvn help]]></category>
		<category><![CDATA[mvn useful commands]]></category>

		<guid isPermaLink="false">http://anandhansubbiah.com/blog/?p=169</guid>
		<description><![CDATA[Here are some useful mvn commands
mvn eclipse:eclipse -DdownloadSources=true
This will set up the eclipse environment and also download the source for the jar files.
mvn clean install war:inplace
This will create a open war inside the target directory. This is very useful to modify non-java resources.
mvn clean install  -Dmaven.test.skip=true
This will skip the unit tests . It helps to [...]]]></description>
			<content:encoded><![CDATA[<p>Here are some useful mvn commands</p>
<p><strong>mvn eclipse:eclipse -DdownloadSources=true</strong></p>
<p>This will set up the eclipse environment and also download the source for the jar files.</p>
<p><strong>mvn clean install war:inplace</strong></p>
<p>This will create a open war inside the target directory. This is very useful to modify non-java resources.</p>
<p><strong>mvn clean install  -Dmaven.test.skip=true</strong></p>
<p>This will skip the unit tests . It helps to speed up the install but it is a bad practice.</p>
<p><a class="a2a_dd a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fanandhansubbiah.com%2Fblog%2Fuseful-mvn-commands%2F&amp;title=useful%20mvn%20commands" id="wpa2a_12"><img src="http://anandhansubbiah.com/blog/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://anandhansubbiah.com/blog/useful-mvn-commands/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Hibernate Filters</title>
		<link>http://anandhansubbiah.com/blog/hibernate-filters/</link>
		<comments>http://anandhansubbiah.com/blog/hibernate-filters/#comments</comments>
		<pubDate>Thu, 03 Apr 2008 16:55:41 +0000</pubDate>
		<dc:creator>Anandhan Subbiah</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[hibernate filter je22 hbm]]></category>

		<guid isPermaLink="false">http://anandhansubbiah.com/blog/hibernate-filters/</guid>
		<description><![CDATA[Hibernate filters provide you with a programmatic way to restrict the result of your query.The advantage is that you can programmatically change filters even though you can&#8217;t do it at runtime it is still a better approach. In the following code sample I created a filter called activatedFilter and added it to the User class. [...]]]></description>
			<content:encoded><![CDATA[<p>Hibernate filters provide you with a programmatic way to restrict the result of your query.The advantage is that you can programmatically change filters even though you can&#8217;t do it at runtime it is still a better approach. In the following code sample I created a filter called activatedFilter and added it to the User class. You can specify or define the attribute in the filter-def. In this case the filter is boolean. You can enable the filter using the session.enableFilter() API.<br />
<code></p>
<p>PUBLIC "-//Hibernate/Hibernate Mapping DTD//EN"<br />
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"&amp;gt;</code></p>
<p>import org.hibernate.Filter;<br />
import org.hibernate.Query;<br />
import org.hibernate.Session;<br />
import org.hibernate.SessionFactory;<br />
import org.hibernate.Transaction;</p>
<p>import org.hibernate.cfg.Configuration;</p>
<p>public class SimpleFilterExample {<br />
public static void main (String args[]) {<br />
SessionFactory factory =<br />
new Configuration().configure().buildSessionFactory();<br />
Session session = factory.openSession();</p>
<p>//insert the users<br />
insertUser(&#8221;ray&#8221;,true,session);<br />
insertUser(&#8221;jason&#8221;,true,session);<br />
insertUser(&#8221;beth&#8221;,false,session);<br />
insertUser(&#8221;judy&#8221;,false,session);<br />
insertUser(&#8221;rob&#8221;,false,session);</p>
<p>//Show all users<br />
System.out.println(&#8221;===ALL USERS===&#8221;);<br />
displayUsers(session);</p>
<p>//Show activated users<br />
Filter filter = session.enableFilter(&#8221;activatedFilter&#8221;);<br />
filter.setParameter(&#8221;activatedParam&#8221;,new Boolean(true));<br />
System.out.println(&#8221;===ACTIVATED USERS===&#8221;);<br />
displayUsers(session);</p>
<p>//Show nonactivated users<br />
filter.setParameter(&#8221;activatedParam&#8221;,new Boolean(false));<br />
System.out.println(&#8221;===NON-ACTIVATED USERS===&#8221;);<br />
displayUsers(session);</p>
<p>session.close();<br />
}</p>
<p>public static void displayUsers(Session session) {<br />
session.beginTransaction();<br />
Query query = session.createQuery(&#8221;from User&#8221;);<br />
Iterator results = query.iterate();<br />
while (results.hasNext())<br />
{<br />
User user = (User) results.next();<br />
System.out.print(user.getUsername() + &#8221; is &#8220;);<br />
if (user.isActivated())<br />
{<br />
System.out.println(&#8221;activated.&#8221;);<br />
}<br />
else<br />
{<br />
System.out.println(&#8221;not activated.&#8221;);<br />
}<br />
}</p>
<p>session.getTransaction().commit();<br />
}</p>
<p>public static void insertUser(String name, boolean activated, Session session) {<br />
session.beginTransaction();</p>
<p>User user = new User();<br />
user.setUsername(name);<br />
user.setActivated(activated);<br />
session.save(user);</p>
<p>session.getTransaction().commit();<br />
}<br />
}</p>
<p><a class="a2a_dd a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fanandhansubbiah.com%2Fblog%2Fhibernate-filters%2F&amp;title=Hibernate%20Filters" id="wpa2a_14"><img src="http://anandhansubbiah.com/blog/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://anandhansubbiah.com/blog/hibernate-filters/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Hibernate Cache</title>
		<link>http://anandhansubbiah.com/blog/hibernate-cache/</link>
		<comments>http://anandhansubbiah.com/blog/hibernate-cache/#comments</comments>
		<pubDate>Thu, 03 Apr 2008 02:49:17 +0000</pubDate>
		<dc:creator>Anandhan Subbiah</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Technical Articles]]></category>
		<category><![CDATA[hibernate cache java Treecache]]></category>

		<guid isPermaLink="false">http://anandhansubbiah.com/blog/hibernate-cache/</guid>
		<description><![CDATA[Database operations are typically very expensive. A typical query would have to be first transmitted over the network. The database has to create a query plan for it and then execute it. The response then has to be transmitted over the network again before the client can process the results. Most databases will cache the [...]]]></description>
			<content:encoded><![CDATA[<p>Database operations are typically very expensive. A typical query would have to be first transmitted over the network. The database has to create a query plan for it and then execute it. The response then has to be transmitted over the network again before the client can process the results. Most databases will cache the results and some will cache queries thereby preventing the execution of the queries and sometimes eliminate the need for the query plan. But these are largely dependent on the number of unique queries and the network overhead is still there.</p>
<p>The natural and obvious answer is to have a cache at the client end of the database connection. Hibernateprovides one cache (the first-level cache) through which all requests must pass. A second-level cache is optional and configurable.</p>
<p>The L1 cache ensures that within a session the request for a object from the database always returns the same object instance hence preventing the object from being reloaded. You can always use object.evict() to discard the object and force a reload.To discard all objects in a session you can issue session.clear().This can also be called called a Java Virtual Machine (JVM) or SessionFactory-level class. . If you have a second-level cache at the SessionFactory level, the application objects are cached in a manner where they are available across sessions.</p>
<p>The L2 cache also called as query cache is external to hibernate . Hibernate provides a pluggable interface for the L2 cache. This allows a cache to be shared between applications on the same machine or even between multiple applications on multiple machines. The L2 cache will not be able to react to changes made by an external application so you have to be careful not to lose the state of the data. Also a distributed cache creates lot of network traffic and takes up memory as well.</p>
<p>Java threads do not timeout when there is a deadlock so don&#8217;t share sessions between different threads. If you absolutely must maintain an instance for a longer duration, maintain the instance within a ThreadLocal object. For most purposes, however, the lightweight nature of the Session object makes it practical to construct, use, and destroy an instance, rather than to store a session.</p>
<p>Some of the widely used L2 cache implementations are</p>
<p>EHCache<br />
An in-process cache which is not cluster safe but supports Query Cache. It can use memory as well as disk.</p>
<p>OSCache<br />
An in-process cache which is not cluster safe but supports Query Cache. It can use memory as well as disk.</p>
<p>SwarmCache<br />
A multicast distributed cache which is cluster safe(clustered invalidation) but does not support Query Cache.</p>
<p>TreeCache<br />
A multicast distributed transactional cache which is cluster safe but does not support Query Cache.</p>
<p>Configuration of EH Cache</p>
<p>When the objects being cached need to be updated, the read-write usage mechanism is an appropriate option to choose. If you use database imports or have an alternate way to update the database this option will not be suitable. It becomes even more difficult if the cache is clustered. The database has to be locked for the cache and the database to be in sync.</p>
<p>The nonstrict read-write cache is the same as read write except that it writes to the database occasionally.</p>
<p>The following properties are available in the Hibernate Configuration files to handle cache setup:</p>
<p>hibernate.cache.use_minimal_puts: Optimizes second-level cache operation to minimize writes, at the cost of more frequent reads (useful for clustered caches). Possible values are true and false.</p>
<p>hibernate.cache.use_query_cache: Enables the query cache. The query cache is disabled by default. Possible values are true and false.</p>
<p>Example<br />
<code>Session session = SessionFactory.openSession();<br />
Query query = session.createQuery("from Users");<br />
query.setCacheable(true);<br />
List users = query.list();<br />
SessionFactory.closeSession();</code></p>
<p>To explictly use EHCache :<br />
Add this property to the hibernate .cfg.xml</p>
<pre>
<code>&lt;property name="hibernate.cache.provider_class"&gt;net.sf.ehcache.hibernate
.Provider&lt;/property&gt;</code>
</pre>
<p>Create a file ehcache.xml and make sure it is available in the classpath</p>
<pre>
<code>&lt;ehcache&gt;

    &lt;diskStore path="java.io.tmpdir"/&gt;

    &lt;defaultCache
        maxElementsInMemory="1000"
        eternal="false"
        timeToIdleSeconds="120"
        timeToLiveSeconds="120"
        overflowToDisk="true"
        /&gt;

    &lt;cache name="example.survey.Survey"
        maxElementsInMemory="1000"
        eternal="false"
        timeToIdleSeconds="3600"
        overflowToDisk="true"
        /&gt;

    &lt;cache name="example.survey"
        maxElementsInMemory="1000"
        eternal="true"
        overflowToDisk="true"
        /&gt;
&lt;/ehcache&gt;</code>
</pre>
<p>timeToIdleSeconds specifies how long an object can be idle before it expires. The timeToLiveSecondsvalue specifies the overall length of time that an object can be cached before being expired.</p>
<p>When not to use Cache<br />
1) When the database can be modified by an external source. You may be able to deal with this issue by specifying a version or timestamp property for your object and using the Session.lock() method to verify that the object hasn&#8217;t been changed.<br />
2)Caching only helps when the same data is used multiple times within the expiry time period. There is no point in caching data which expires before it can be used.<br />
3)In financial applications where auditing is very important.<br />
4)When the dataset is too large<br />
5) when you don&#8217;t know what the hell you are doing <img src='http://anandhansubbiah.com/blog/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p><a class="a2a_dd a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fanandhansubbiah.com%2Fblog%2Fhibernate-cache%2F&amp;title=Hibernate%20Cache" id="wpa2a_16"><img src="http://anandhansubbiah.com/blog/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://anandhansubbiah.com/blog/hibernate-cache/feed/</wfw:commentRss>
		<slash:comments>12</slash:comments>
		</item>
		<item>
		<title>Hibernate Events</title>
		<link>http://anandhansubbiah.com/blog/hibernate-events/</link>
		<comments>http://anandhansubbiah.com/blog/hibernate-events/#comments</comments>
		<pubDate>Thu, 20 Mar 2008 18:24:19 +0000</pubDate>
		<dc:creator>Anandhan Subbiah</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Technical Articles]]></category>
		<category><![CDATA[code sample]]></category>
		<category><![CDATA[hibernate]]></category>
		<category><![CDATA[hibernate event example]]></category>
		<category><![CDATA[hibernate event list]]></category>
		<category><![CDATA[hibernate events]]></category>
		<category><![CDATA[source code]]></category>

		<guid isPermaLink="false">http://anandhansubbiah.com/blog/hibernate-events/</guid>
		<description><![CDATA[Hibernate 3 actually implements most of its functionality as event listeners. Event listeners are always registered globally for the event that they handle. You can register them in the configuration file or programmatic ally. Either way, you will need to map your implementation of one of the interfaces to the associated types.Here is the different [...]]]></description>
			<content:encoded><![CDATA[<p>Hibernate 3 actually implements most of its functionality as event listeners. Event listeners are always registered globally for the event that they handle. You can register them in the configuration file or programmatic ally. Either way, you will need to map your implementation of one of the interfaces to the associated types.Here is the different types of events supported by hibernate </p>
<p>AutoFlushEventListener</p>
<p>DeleteEventListener</p>
<p>DirtyCheckEventListener</p>
<p>EvictEventListener</p>
<p>FlushEventListener</p>
<p>FlushEntityEventListener</p>
<p>LoadEventListener</p>
<p>InitializeCollectionEventListener</p>
<p>LockEventListener</p>
<p>MergeEventListener</p>
<p>PersistEventListener</p>
<p>PostDeleteEventListener</p>
<p>PostInsertEventListener</p>
<p>PostLoadEventListener</p>
<p>PostUpdateEventListener</p>
<p>PreDeleteEventListener</p>
<p>PreInsertEventListener</p>
<p>PreLoadEventListener</p>
<p>PreUpdateEventListener</p>
<p>RefreshEventListener</p>
<p>ReplicateEventListener</p>
<p>SaveOrUpdateEventListener<br />
Let us consider the following example</p>
<pre>
<code>
public class EventExample {
public static void main(String[] args) {
Configuration config = new Configuration();

// Apply this event listener (programmatically)
config.setListener("save-update", new BookingSaveOrUpdateEventListener());

SessionFactory factory = config.configure().buildSessionFactory();
Session session = factory.openSession();

Transaction tx = session.beginTransaction();

// Make our bookings... seat R1 is NOT to be saved.
session.saveOrUpdate(new Booking("charles","R1"));
session.saveOrUpdate(new Booking("camilla","R2"));

// The confirmation letters should not be sent
// out until AFTER the commit completes.
tx.commit();
}
}</code>
</pre>
<pre>
<code>import java.io.Serializable;
import org.hibernate.HibernateException;
import org.hibernate.event.SaveOrUpdateEvent;
import org.hibernate.event.def.DefaultSaveOrUpdateEventListener;

public class BookingSaveOrUpdateEventListener
extends DefaultSaveOrUpdateEventListener
{
public Serializable onSaveOrUpdate(SaveOrUpdateEvent event)
throws HibernateException {
if( event.getObject() instanceof Booking) {
Booking booking = (Booking)event.getObject();
System.out.println("Preparing to book seat " + booking.getSeat());

if( booking.getSeat().equalsIgnoreCase("R1")) {
System.out.println("Royal box booked");
System.out.println("Conventional booking not recorded.");

// By returning null instead of invoking the
// default behavior‚ we prevent the invocation
// of saveOrUpdate on the Session from having
// any effect on the database!
return null;
}
}

// The default behavior:
return super.onSaveOrUpdate(event);
}
}</code>
</pre>
<p>The objective of the listener is to prevent R1 from getting saved so the default behavior is overridden by the listener class.</p>
<p><a class="a2a_dd a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fanandhansubbiah.com%2Fblog%2Fhibernate-events%2F&amp;title=Hibernate%20Events" id="wpa2a_18"><img src="http://anandhansubbiah.com/blog/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://anandhansubbiah.com/blog/hibernate-events/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Invoking a stored procedure using hibernate</title>
		<link>http://anandhansubbiah.com/blog/invoking-a-stored-procedure-using-hibernate/</link>
		<comments>http://anandhansubbiah.com/blog/invoking-a-stored-procedure-using-hibernate/#comments</comments>
		<pubDate>Thu, 20 Mar 2008 17:56:46 +0000</pubDate>
		<dc:creator>Anandhan Subbiah</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Technical Articles]]></category>

		<guid isPermaLink="false">http://anandhansubbiah.com/blog/invoking-a-stored-procedure-using-hibernate/</guid>
		<description><![CDATA[Stored procedures may be a thing of the past  but sometimes they can be very helpful. They reduce network traffic and can perform efficient and fast computations if required.
&#60;sql-insert callable="true"&#62;
{call insertClient(?,?,?,?,?,?)}
&#60;/sql-insert&#62;
This example may be very trivial but really complex computations can be performed using stored procedures. The drawback with hibernate and stored procedures is [...]]]></description>
			<content:encoded><![CDATA[<p>Stored procedures may be a thing of the past  but sometimes they can be very helpful. They reduce network traffic and can perform efficient and fast computations if required.<br />
<code>&lt;sql-insert callable="true"&gt;<br />
{call insertClient(?,?,?,?,?,?)}<br />
&lt;/sql-insert&gt;</code><br />
This example may be very trivial but really complex computations can be performed using stored procedures. The drawback with hibernate and stored procedures is hibernate session cache cannot track any modifications done using a stored procedure.</p>
<p><a class="a2a_dd a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fanandhansubbiah.com%2Fblog%2Finvoking-a-stored-procedure-using-hibernate%2F&amp;title=Invoking%20a%20stored%20procedure%20using%20hibernate" id="wpa2a_20"><img src="http://anandhansubbiah.com/blog/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://anandhansubbiah.com/blog/invoking-a-stored-procedure-using-hibernate/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

