<?xml version='1.0' encoding='UTF-8'?><rss xmlns:atom="http://www.w3.org/2005/Atom" xmlns:openSearch="http://a9.com/-/spec/opensearchrss/1.0/" xmlns:blogger="http://schemas.google.com/blogger/2008" xmlns:georss="http://www.georss.org/georss" xmlns:gd="http://schemas.google.com/g/2005" xmlns:thr="http://purl.org/syndication/thread/1.0" version="2.0"><channel><atom:id>tag:blogger.com,1999:blog-7189178189432269741</atom:id><lastBuildDate>Wed, 05 Aug 2026 19:50:02 +0000</lastBuildDate><category>Java</category><category>Design Pattern</category><category>Design</category><category>For-each</category><category>Immutable</category><category>JVM</category><category>Java 7</category><category>remote debug</category><title>Technology is Art</title><description></description><link>http://hellotojavaworld.blogspot.com/</link><managingEditor>noreply@blogger.com (Vineet Mangal)</managingEditor><generator>Blogger</generator><openSearch:totalResults>9</openSearch:totalResults><openSearch:startIndex>1</openSearch:startIndex><openSearch:itemsPerPage>25</openSearch:itemsPerPage><item><guid isPermaLink="false">tag:blogger.com,1999:blog-7189178189432269741.post-4938654388271609126</guid><pubDate>Tue, 21 Apr 2015 10:02:00 +0000</pubDate><atom:updated>2019-10-30T07:46:20.570+05:30</atom:updated><title>Java 8 : Date and Time - Part I</title><description>&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;
&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;
&lt;b&gt;&lt;span class=&quot;Apple-style-span&quot; style=&quot;color: #0b5394;&quot;&gt;Preface&lt;/span&gt;&lt;/b&gt;&lt;br /&gt;
&lt;br /&gt;
Wikipedia defines &lt;b&gt;Time &lt;/b&gt;as:&lt;br /&gt;
&lt;br /&gt;
&quot;&lt;i&gt;&lt;b&gt;Time&lt;/b&gt; is a measure in which events can be ordered from the past through the present into the future, and also the measure of durations of events and the intervals between them.Time is often referred to as the &lt;b&gt;fourth dimension&lt;/b&gt;, along with the three spatial dimensions&lt;/i&gt;.&quot;&lt;br /&gt;
&lt;br /&gt;
Since Time is a natural concept, in an ideal world, dealing with it should be simple, but unfortunately it is not the case and we humans made it more complex by introducing different time zones and day light saving.&lt;br /&gt;
&lt;br /&gt;
&lt;span style=&quot;font-family: inherit;&quot;&gt;As a programmer, we want that programming languages immune us from these complexity and being a Java programmer, we have similar expectations from Java. Java tried to overcome these complexities in its first two editions of Date and Time API, but failed measurably. A simple google will give you nume&lt;/span&gt;rous posts criticizing Java for this. Few years back, I was introduced to &lt;a href=&quot;http://www.joda.org/joda-time/&quot; target=&quot;_blank&quot;&gt;Joda-Time&lt;/a&gt;&amp;nbsp;library that provide APIs that help you to work with Time with ease.&lt;br /&gt;
&lt;br /&gt;
In its latest edition (Java 8), in its third attempt, finally Java brought this change that we all were looking for long. With its new APIs, it is no more require to use either third party APIs or create several utility classes/methods to deal with date and time. &amp;nbsp;This new API is heavily inspired by&amp;nbsp;&lt;a href=&quot;http://www.joda.org/joda-time/&quot; target=&quot;_blank&quot;&gt;Joda-Time&lt;/a&gt;&amp;nbsp;library.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;&lt;span class=&quot;Apple-style-span&quot; style=&quot;color: #0b5394;&quot;&gt;Java 8 - Date and Time API&lt;/span&gt;&lt;/b&gt;&lt;br /&gt;
&lt;br /&gt;
New API defines classes to map the concepts of Instant, Duration, Period, Time (Local and Zoned). All the classes are immutable and thread safe. Official&amp;nbsp;&lt;a href=&quot;https://docs.oracle.com/javase/8/docs/api/java/time/package-summary.html&quot; target=&quot;_blank&quot;&gt;java.time package summary&lt;/a&gt;&amp;nbsp;offers a great detail on the different concepts and worth a visit.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;&lt;span class=&quot;Apple-style-span&quot; style=&quot;color: #0b5394;&quot;&gt;Instant and Duration:&lt;/span&gt;&lt;/b&gt;&lt;br /&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;div style=&quot;text-indent: 0.00266666663810611px;&quot;&gt;
&lt;span style=&quot;background-color: white;&quot;&gt;&lt;span style=&quot;font-family: inherit;&quot;&gt;In Java, an Instant represents a point on the time line. An origin, called the epoch, is arbitrarily set at midnight of January 1, 1970 GMT. This is the same convention used in the Unix/POSIX time. Starting from that origin, time is measured in 86,400 seconds per day, forwards and backwards, in nanosecond precision.&lt;i&gt;&lt;b&gt; &lt;span style=&quot;color: #351c75;&quot;&gt;&lt;u&gt;Instant is essentially a timestamp&lt;/u&gt;.&lt;/span&gt;&lt;/b&gt;&lt;/i&gt;&lt;/span&gt;&lt;/span&gt;&lt;/div&gt;
&lt;div style=&quot;text-indent: 0.00266666663810611px;&quot;&gt;
&lt;span style=&quot;background-color: white;&quot;&gt;&lt;span style=&quot;font-family: inherit;&quot;&gt;&lt;br /&gt;&lt;/span&gt;&lt;/span&gt;&lt;/div&gt;
&lt;div style=&quot;text-indent: 0.00266666663810611px;&quot;&gt;
&lt;span style=&quot;background-color: white;&quot;&gt;&lt;span style=&quot;font-family: inherit;&quot;&gt;Duration is amount of time between two instants. Both instants and duration are scalar values, that mean time zone or day light saving doesn&#39;t affect them.&lt;/span&gt;&lt;/span&gt;&lt;br /&gt;
&lt;span style=&quot;background-color: white;&quot;&gt;&lt;span style=&quot;font-family: inherit;&quot;&gt;&lt;br /&gt;&lt;/span&gt;&lt;/span&gt;
&lt;span style=&quot;background-color: white;&quot;&gt;&lt;span style=&quot;color: #741b47; font-family: inherit;&quot;&gt;&lt;b&gt;Getting Current Instant:&lt;/b&gt;&lt;/span&gt;&lt;/span&gt;&lt;/div&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush:java&quot;&gt;Instant instant = Instant.now();&lt;/pre&gt;
&lt;br /&gt;
&lt;b&gt;Duration between two instants:&lt;/b&gt;&lt;br /&gt;
&lt;pre class=&quot;brush:java&quot;&gt;        Instant startInstant = Instant.now();
        Instant endInstant = Instant.now();
        Duration duration = Duration.between(startInstant,endInstant);
&lt;/pre&gt;
&lt;br /&gt;
&lt;b&gt;Adding time to a duration is pretty straight forward:&lt;/b&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush:java&quot;&gt;    public void editDuration(Duration duration){
        // Enhance Duration by 5 minutes
        Duration enhanceDurationByMinute = duration.plusMinutes(5);
        
        //Enhance Duration by 2 Days, 5 hours, 6 minutes, 
        // 10 Seconds, 200 milliseconds and 788 nanoseconds
        Duration enchanced = duration.plusDays(2).plusHours(5).plusMinutes(6)
                .plusSeconds(10).plusMillis(200).plusNanos(788);
        
    }
&lt;/pre&gt;
&lt;br /&gt;
Important point to note here is, since &lt;u&gt;Duration is an immutable&lt;/u&gt;, every time you call a plusXXX() method, it returns a new object of Duration.&lt;br /&gt;
&lt;br /&gt;
Duration stores time in two parts, seconds and nano seconds and provide two methods to get these parts. It provides methods to get total time in different units viz. milliseconds, minutes, hours.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Getting Duration in human readable form:&lt;/b&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush: java&quot;&gt;    public static void getDurationBetweenTwoInstants(){
        Logger logger = Logger.getGlobal();
        Instant startInstant = Instant.now();
        for(int i = 0; i &amp;lt; Integer.MAX_VALUE; i++){
            //Do nothing
        }
        Instant endInstant = Instant.now();
        Duration duration = Duration.between(startInstant, endInstant);
        logger.log(INFO, &quot;&quot; + duration);
        duration = duration.plusHours(5).plusMinutes(8).plusSeconds(2)
                        .plusMillis(234).plusNanos(234);
        logger.log(INFO, &quot;Total Time :&quot; + duration);

        logger.log(INFO, &quot;NanoSecond Part of Total Time: &quot; 
                                    +  duration.getNano());
        logger.log(INFO,&quot;Seconds Part of Total Time: &quot; 
                                    +  duration.getSeconds());

        logger.log(INFO,&quot;Total time in Nano : &quot; +  duration.toNanos());
        logger.log(INFO,&quot;Total time in Millis : &quot; +  duration.toMillis());
        logger.log(INFO,&quot;Total time in Minutes : &quot; +  duration.toMinutes());
        logger.log(INFO,&quot;Total time in Hours : &quot; +  duration.toHours());
    }
&lt;/pre&gt;
&lt;br /&gt;
&lt;b&gt;A sample Output of above program looks like:&lt;/b&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;div style=&quot;text-align: left;&quot;&gt;
&lt;span style=&quot;color: #274e13; font-size: x-small;&quot;&gt;&lt;span style=&quot;font-family: &amp;quot;courier new&amp;quot; , &amp;quot;courier&amp;quot; , monospace;&quot;&gt;INFO: Time in looping: PT0.006S&lt;/span&gt;&lt;/span&gt;&lt;br /&gt;
&lt;span style=&quot;color: #274e13; font-size: x-small;&quot;&gt;&lt;span style=&quot;font-family: &amp;quot;courier new&amp;quot; , &amp;quot;courier&amp;quot; , monospace;&quot;&gt;INFO: Total Time :PT5H8M2.240000234S&lt;/span&gt;&lt;/span&gt;&lt;br /&gt;
&lt;span style=&quot;color: #274e13; font-size: x-small;&quot;&gt;&lt;span style=&quot;font-family: &amp;quot;courier new&amp;quot; , &amp;quot;courier&amp;quot; , monospace;&quot;&gt;INFO: NanoSecond Part of Total Time: 240000234&lt;/span&gt;&lt;/span&gt;&lt;br /&gt;
&lt;span style=&quot;color: #274e13; font-size: x-small;&quot;&gt;&lt;span style=&quot;font-family: &amp;quot;courier new&amp;quot; , &amp;quot;courier&amp;quot; , monospace;&quot;&gt;INFO: Seconds Part of Total Time: 18482&lt;/span&gt;&lt;/span&gt;&lt;br /&gt;
&lt;span style=&quot;color: #274e13; font-size: x-small;&quot;&gt;&lt;span style=&quot;font-family: &amp;quot;courier new&amp;quot; , &amp;quot;courier&amp;quot; , monospace;&quot;&gt;INFO: Total time in Nano : 18482240000234&lt;/span&gt;&lt;/span&gt;&lt;br /&gt;
&lt;span style=&quot;color: #274e13; font-size: x-small;&quot;&gt;&lt;span style=&quot;font-family: &amp;quot;courier new&amp;quot; , &amp;quot;courier&amp;quot; , monospace;&quot;&gt;INFO: Total time in Millis : 18482240&lt;/span&gt;&lt;/span&gt;&lt;br /&gt;
&lt;span style=&quot;color: #274e13; font-size: x-small;&quot;&gt;&lt;span style=&quot;font-family: &amp;quot;courier new&amp;quot; , &amp;quot;courier&amp;quot; , monospace;&quot;&gt;INFO: Total time in Minutes : 308&lt;/span&gt;&lt;/span&gt;&lt;br /&gt;
&lt;span style=&quot;color: #274e13; font-size: x-small;&quot;&gt;&lt;span style=&quot;font-family: &amp;quot;courier new&amp;quot; , &amp;quot;courier&amp;quot; , monospace;&quot;&gt;INFO: Total time in Hours : 5&lt;/span&gt;&lt;/span&gt;&lt;/div&gt;
&lt;br /&gt;
&lt;br /&gt;
Similar methods exists for subtraction as well.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Conclusion&lt;/b&gt;&lt;br /&gt;
&lt;b&gt;&lt;br /&gt;&lt;/b&gt;
Instants and Duration is the basis of new Date and Time API. But as you can see, both the APIs are not that useful from human being interaction and for that there are other APIs that relates to Periods, Local and Zoned Date/Time. I will discuss about them in my next post.&lt;br /&gt;
&lt;br /&gt;&lt;/div&gt;
</description><link>http://hellotojavaworld.blogspot.com/2015/04/java-8-date-and-time-part-i.html</link><author>noreply@blogger.com (Vineet Mangal)</author><thr:total>1</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-7189178189432269741.post-8435112433745033205</guid><pubDate>Fri, 15 Jun 2012 16:51:00 +0000</pubDate><atom:updated>2019-10-30T05:27:28.639+05:30</atom:updated><category domain="http://www.blogger.com/atom/ns#">Java 7</category><title>Exploring Java 7 : Try-with-resources</title><description>&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;
&lt;i&gt;Try-with-Resource &lt;/i&gt;is new featured added in Java 7. Personally, I like this feature very much, as it helps to reduce a lot of boiler plate code.&lt;br /&gt;
&lt;br /&gt;
Consider a scenario, where we have to release a system resource, like &lt;i&gt;JDBC Connection &lt;/i&gt;or &lt;i&gt;File Stream.&lt;/i&gt;&amp;nbsp;Prior to Java 7, it meant that developer has to write a lot of boiler plate code to release that resource. In order to ensure releasing of resource in all the situations, one has to use finally block as well for exception cases. Consider following example, written with Java 6:&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush: java&quot;&gt;String readFirstLine(String path) throws IOException {
  BufferedReader br = new BufferedReader(new FileReader(path));
  try {
   return br.readLine();
  } finally {
   if (br != null)
    br.close();
  }
 }&lt;/pre&gt;
Clearly, one has to write almost 4-5 lines for closing each resource. Now, what Java 7 did is that it made the process of closing resource automatic.&lt;br /&gt;
&lt;br /&gt;
In Java 7, a resource is defined as&amp;nbsp;&lt;i style=&quot;background-color: white;&quot;&gt;&quot;An object of type java.lang.AutoCloseable.&quot;&lt;/i&gt;&lt;span style=&quot;background-color: white;&quot;&gt;. This &lt;i&gt;AutoCloseable&lt;/i&gt;&amp;nbsp;interface has a single method &lt;i&gt;close()&lt;/i&gt;&amp;nbsp;and this method is invoked automatically when a resource is used with try block. See below example:&lt;/span&gt;&lt;br /&gt;
&lt;pre class=&quot;brush:java&quot;&gt;String readFirst(String path) throws IOException {
  try (BufferedReader br = new BufferedReader(new FileReader(path))) {
   return br.readLine();
  }
 }
&lt;/pre&gt;
&lt;pre class=&quot;brush:java&quot;&gt;&lt;/pre&gt;
Impressive!!! Isn&#39;t it? We have reduced boiler plate code drastically and there is no scope of accidentally forgetting to close a resource. All resource will be freed automatically.&lt;br /&gt;
&lt;br /&gt;
Few points to remember:&lt;br /&gt;
&lt;ul style=&quot;text-align: left;&quot;&gt;
&lt;li&gt;A resource must be declared in parenthesis, immediately after &lt;i&gt;try&lt;/i&gt;&amp;nbsp;block.&lt;/li&gt;
&lt;li&gt;A &lt;i&gt;Try-with-Resource&lt;/i&gt;&amp;nbsp;can have &lt;i&gt;catch&lt;/i&gt;&amp;nbsp;and &lt;i&gt;finally &lt;/i&gt;blocks, just as with try block.&lt;/li&gt;
&lt;li&gt;There can be multiple resources in a single &lt;i&gt;Try-with-Resource&lt;/i&gt;&amp;nbsp;block&lt;/li&gt;
&lt;pre class=&quot;brush:java&quot;&gt;public void readEmployees(Connection con){
  String sql = &quot;Select * from Employee&quot;;
  try (Statement stmt = con.createStatement();
    ResultSet rs = stmt.executeQuery(sql)){
   //Work with Statement and ResultSet   
  } catch (SQLException sqe) {
   sqe.printStackTrace();
  }
 }&lt;/pre&gt;
&lt;li&gt;In case of multiple resources, &lt;i&gt;close()&lt;/i&gt;&amp;nbsp;method of all the resources is called, and order of calling &lt;i&gt;close()&lt;/i&gt;&amp;nbsp;method is reverse of declaration&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;</description><link>http://hellotojavaworld.blogspot.com/2012/06/exploring-java-7-try-with-resources.html</link><author>noreply@blogger.com (Vineet Mangal)</author><thr:total>4</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-7189178189432269741.post-4728009880393370620</guid><pubDate>Fri, 01 Jun 2012 09:38:00 +0000</pubDate><atom:updated>2012-06-29T09:01:13.380+05:30</atom:updated><category domain="http://www.blogger.com/atom/ns#">Design</category><title>Interface or Abstract Class</title><description>&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;
&lt;b&gt;&lt;span class=&quot;Apple-style-span&quot; style=&quot;color: #0b5394;&quot;&gt;What is the difference between an Abstract Class and an Interface?&lt;/span&gt;&lt;/b&gt;&lt;br /&gt;
Well, isn&#39;t it an interesting question or for few, a foolish question?&lt;br /&gt;
&lt;br /&gt;
For a number of Java newbies, the only difference between two is, &quot;&lt;span class=&quot;Apple-style-span&quot; style=&quot;color: #3d85c6;&quot;&gt;You can&#39;t have method body in Interface.&lt;/span&gt;&quot;. Well, I would say that it is technically (Implementation vise) correct, but doesn&#39;t reflect the concept.&lt;br /&gt;
&lt;br /&gt;
&lt;span class=&quot;Apple-style-span&quot; style=&quot;color: #0b5394;&quot;&gt;&lt;b&gt;Abstract Class&lt;/b&gt;&lt;/span&gt;&lt;br /&gt;
An abstract class, is the most generalized form of an Entity hierarchy (In Java, a Class is an entity), such that it doesn&#39;t represent a real entity on its own, but provides a basis on which real entities can be build within that hierarchy. An abstract class provides a default behavior and also provide abstract behavior (Operations that must be override by the real classes).&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;&lt;span class=&quot;Apple-style-span&quot; style=&quot;color: #0b5394;&quot;&gt;Interface&lt;/span&gt;&lt;/b&gt;&lt;br /&gt;
An interface, on the other hand is a contract that states that you have to agree to provide following operations if you agree to abide by me, i.e. an entity that agrees to abide by the contract of interface, will have to provide the behavior (operations) declared in interface.&lt;br /&gt;
&lt;br /&gt;
&lt;span class=&quot;Apple-style-span&quot; style=&quot;color: #0b5394;&quot;&gt;&lt;b&gt;Interface or Abstract Class&lt;/b&gt;&lt;/span&gt;&lt;br /&gt;
Next question is when to use abstract class and when use an Interface? Though it many a depends on requirements as well, but I follow a thumb rule,&lt;br /&gt;
&lt;div style=&quot;text-align: left;&quot;&gt;
&lt;/div&gt;
&lt;ul style=&quot;text-align: left;&quot;&gt;
&lt;li&gt;If I have to build a class hierarchy, I should consider generalization. Many a time I will reach to most crude form of generalization, i.e. at an abstract level. I would declare abstract methods and will also define common behavior for few of the methods. This would be my abstract class.&lt;/li&gt;
&lt;li&gt;On the other hand, if I want to expose a particular behavior to the client, then I would define an interface.&amp;nbsp;&lt;/li&gt;
&lt;/ul&gt;
&lt;div style=&quot;text-align: left;&quot;&gt;
&lt;br /&gt;&lt;/div&gt;
Further, I would suggest that one should go through different Java APIs, and spend some time understanding when and why they used interface or abstract class. Java APIs are excellent source for learning on building design blocks for any OOPs language.&lt;br /&gt;
&lt;div style=&quot;text-align: left;&quot;&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;/div&gt;</description><link>http://hellotojavaworld.blogspot.com/2011/03/interface-or-abstract-class.html</link><author>noreply@blogger.com (Vineet Mangal)</author><thr:total>2</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-7189178189432269741.post-8755359100383878441</guid><pubDate>Wed, 14 Dec 2011 09:50:00 +0000</pubDate><atom:updated>2012-06-29T09:01:36.799+05:30</atom:updated><category domain="http://www.blogger.com/atom/ns#">Design Pattern</category><category domain="http://www.blogger.com/atom/ns#">Java</category><title>Singleton Pattern: Am I implementing it Correctly? - Part II</title><description>&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;
In my last post, I discussed implementation of Singleton Pattern in a Single Threaded Environment. There was a very good discussion on whether about very existence of this pattern as well. Actually it is an ever going debate, few people think that it is an anti pattern and few think it is a simple solution of a common problem.&lt;br /&gt;
&lt;br /&gt;
My intent of this post (and previous also) is to discuss on how to implement it, rather than whether to use it!!! So, let&#39;s start discussing Singleton Pattern in a Multi-threaded environment.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;&lt;span class=&quot;Apple-style-span&quot; style=&quot;color: #0b5394;&quot;&gt;Singleton Pattern in Multi-Thread environment:&lt;/span&gt;&lt;/b&gt;&lt;br /&gt;
&lt;br /&gt;
We have seen using static factory to implement Singleton Pattern in a single thread environment and also discussed problems associated with it. When in Multi-threaded environment, there are other problems as well.&lt;br /&gt;
&lt;br /&gt;
What will happen if two threads&amp;nbsp;simultaneously try to access static factory method (getInstance() method)? It will result in two instance of class, though we required only one instance. Clearly, singleton pattern is broken.&lt;br /&gt;
&lt;br /&gt;
This problem is not only associated with Java, but also to other languages as well, like C++. &amp;nbsp;A naive solution is to synchronize the static factory method, so that at any given time, only one thread can execute getInstance() method. So, even if we ignore the problems arising from reflection (see previous post) and want to use singleton pattern, then it would be used in this way:&lt;br /&gt;
&lt;pre class=&quot;brush:java&quot;&gt;public class SingletonInMultiThread {
 private static SingletonInMultiThread singletonInstance; 
 private SingletonInMultiThread(){} 
 public SingletonInMultiThread getInstance(){
  if(singletonInstance == null) singletonInstance = new SingletonInMultiThread();
  return singletonInstance;
 } 
}&lt;/pre&gt;
&lt;br /&gt;
Well, there is no problem (other than we discussed for reflection) in above code, but there is an overhead of synchronization every time, as we need synchronization only at the time of creation.There are two ways to resolve this problem.&lt;br /&gt;
&lt;br /&gt;
One is to instantiate the variable at the time of declaration and remove synchronization from static factory method.To resolve this synchronization&lt;br /&gt;
&lt;pre class=&quot;brush:java&quot;&gt;public class SingletonInMultiThread {
 private static SingletonInMultiThread singletonInstance = new SingletonInMultiThread(); 
 private SingletonInMultiThread(){} 
 public SingletonInMultiThread getInstance(){  
  return singletonInstance;
 } 
}&lt;/pre&gt;
Another solution is to use infamous Double Checked Locking (Just google it and can find thousands of articles saying same thing), but it is also broken, see &lt;a href=&quot;http://www.cs.umd.edu/~pugh/java/memoryModel/DoubleCheckedLocking.html&quot;&gt;DCL&lt;/a&gt;.&lt;br /&gt;
&lt;br /&gt;
But, Good News is that with Java 5 and using volatile for instance variable, you can seal this DCL broking :)&lt;br /&gt;
&lt;br /&gt;
So, we have seen how we can use Singleton Pattern in a multi-thread environment, but with above discussion, there are still few issues:&lt;br /&gt;
&lt;ul&gt;
&lt;li&gt;We ignore the breaking of Singleton Pattern by reflection&lt;/li&gt;
&lt;li&gt;It is quite cumbersome to implement Singleton Pattern in multi-threaded environment&lt;/li&gt;
&lt;/ul&gt;
&lt;br /&gt;
As I said in previous post, starting from Java 5, a much easier way to control number of instances is to use ENUM. With all the advantages we discussed earlier, it is threadsafe!!!&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;&lt;span class=&quot;Apple-style-span&quot; style=&quot;color: #0b5394;&quot;&gt;Conclusion:&lt;/span&gt;&lt;/b&gt;&lt;br /&gt;
Whenever you need to control number of instances of a type, it is better to consider Enum. Enums are special classes whose number of instances are controlled by JVM itself!!!&lt;/div&gt;</description><link>http://hellotojavaworld.blogspot.com/2010/12/singleton-pattern-am-i-implementing-it.html</link><author>noreply@blogger.com (Vineet Mangal)</author><thr:total>2</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-7189178189432269741.post-4537936697992591695</guid><pubDate>Sat, 27 Nov 2010 12:34:00 +0000</pubDate><atom:updated>2010-11-27T18:09:04.230+05:30</atom:updated><category domain="http://www.blogger.com/atom/ns#">Design Pattern</category><category domain="http://www.blogger.com/atom/ns#">Java</category><title>Singleton Pattern: Am I implementing it Correctly? - Part I</title><description>&lt;b&gt;&lt;span class=&quot;Apple-style-span&quot; style=&quot;color: #0b5394;&quot;&gt;Novice way to implement a Singleton:&lt;/span&gt;&lt;/b&gt;&lt;br /&gt;
&lt;span class=&quot;Apple-style-span&quot; style=&quot;color: #351c75;&quot;&gt;I believe everyone starts (and even continues to do so) implementing Singleton pattern in following fashion:&lt;/span&gt;&lt;br /&gt;
&lt;pre class=&quot;brush:java&quot;&gt;package com.singleton;

public class SimpleSingleton {
 private static SimpleSingleton simpleSingleton;

 private SimpleSingleton() {
 };

 public static SimpleSingleton getInstance() {
  if (simpleSingleton == null)
   simpleSingleton = new SimpleSingleton();
  return simpleSingleton;
 }
}&lt;/pre&gt;&lt;br /&gt;
&lt;b&gt;&lt;span class=&quot;Apple-style-span&quot; style=&quot;color: #0b5394;&quot;&gt;Do you find any problem in it?&lt;/span&gt;&lt;/b&gt;&lt;br /&gt;
&lt;span class=&quot;Apple-style-span&quot; style=&quot;color: #351c75;&quot;&gt;Well, I have!!!&amp;nbsp;The contract of Singleton class can be broken.&amp;nbsp;&lt;/span&gt;&lt;br /&gt;
&lt;span class=&quot;Apple-style-span&quot; style=&quot;color: #351c75;&quot;&gt;Let&#39;s discuss Singleton pattern in Simple Threaded environment and then in next post I will discuss this pattern in Multithreaded environment.&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;&lt;span class=&quot;Apple-style-span&quot; style=&quot;color: #0b5394;&quot;&gt;In a Single Threaded Environment:&lt;/span&gt;&lt;/b&gt;&lt;br /&gt;
&lt;span class=&quot;Apple-style-span&quot; style=&quot;color: #351c75;&quot;&gt;Do you remember the double edge sword in Java, &quot;REFLECTION&quot;? &lt;/span&gt;&lt;br /&gt;
&lt;span class=&quot;Apple-style-span&quot; style=&quot;color: #351c75;&quot;&gt;With the help of reflection, one can very easily breach the singleton contract for above class and  create as many instance as he wants. Let&#39;s consider following three statements:&lt;/span&gt;&lt;br /&gt;
&lt;pre class=&quot;brush:java&quot;&gt;//Get Private Constructor
  Constructor pvtConstructor = Class.forName(
    &quot;com.singleton.SimpleSingleton&quot;).getDeclaredConstructors()[0];
  
  //Set its access control
  pvtConstructor.setAccessible(true);
  
  //Invoke Private Constructor
  SimpleSingleton notSingleton = (SimpleSingleton) pvtConstructor
    .newInstance(null);
&lt;/pre&gt;&lt;br /&gt;
&lt;span class=&quot;Apple-style-span&quot; style=&quot;color: #351c75;&quot;&gt;Here is a summary what is happening in above statements:&lt;/span&gt;&lt;br /&gt;
&lt;ul&gt;&lt;li&gt;&lt;span class=&quot;Apple-style-span&quot; style=&quot;color: #351c75;&quot;&gt;First statement retrieves the &lt;span class=&quot;Apple-style-span&quot; style=&quot;font-family: &#39;Courier New&#39;, Courier, monospace;&quot;&gt;Constructor &lt;/span&gt;object for private constructor of &lt;span class=&quot;Apple-style-span&quot; style=&quot;font-family: &#39;Courier New&#39;, Courier, monospace;&quot;&gt;SimpleSingleton &lt;/span&gt;class. &lt;br /&gt;
&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;&lt;span class=&quot;Apple-style-span&quot; style=&quot;color: #351c75;&quot;&gt;Since the constructor retrieved is a private one, we need to set its accessibility to true.&lt;br /&gt;
&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;&lt;span class=&quot;Apple-style-span&quot; style=&quot;color: #351c75;&quot;&gt;Last statement invokes the private constructor and create a new instance of &lt;span class=&quot;Apple-style-span&quot; style=&quot;font-family: &#39;Courier New&#39;, Courier, monospace;&quot;&gt;SimpleSingleton &lt;/span&gt;class.&lt;br /&gt;
&lt;/span&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;span class=&quot;Apple-style-span&quot; style=&quot;color: #351c75;&quot;&gt;Clearly, we have breached the contract of Singleton class. So, how to overcome this problem?&lt;/span&gt;&lt;br /&gt;
&lt;span class=&quot;Apple-style-span&quot; style=&quot;color: #351c75;&quot;&gt;Well, prior to Java 1.5, there was no way (at least in my knowledge, but Java Universe is so big that I can&#39;t say with 100% surity :) ) to save a singleton class from Reflection mechanism. In Java 1.5, a new kind of classes were introduced, &quot;&lt;span class=&quot;Apple-style-span&quot; style=&quot;font-family: &#39;Courier New&#39;, Courier, monospace;&quot;&gt;Enum&lt;/span&gt;&quot;.&lt;/span&gt;&lt;br /&gt;
&lt;span class=&quot;Apple-style-span&quot; style=&quot;color: #351c75;&quot;&gt;&lt;br /&gt;
&lt;/span&gt;&lt;br /&gt;
&lt;span class=&quot;Apple-style-span&quot; style=&quot;color: #351c75;&quot;&gt;Unlike Classes, an &lt;span class=&quot;Apple-style-span&quot; style=&quot;font-family: &#39;Courier New&#39;, Courier, monospace;&quot;&gt;Enum &lt;/span&gt;has fix number of objects and since this restriction is implemented by JVM&#39;s native libraries, hence it is unbreakable. Let&#39;s see an example:&lt;/span&gt;&lt;br /&gt;
&lt;pre class=&quot;brush:java&quot;&gt;public enum SampleEnum {
 ONLY_INSTANCE();
}&lt;/pre&gt;&lt;br /&gt;
&lt;span class=&quot;Apple-style-span&quot; style=&quot;color: #351c75;&quot;&gt;Now let&#39;s try to create an object of &lt;span class=&quot;Apple-style-span&quot; style=&quot;font-family: &#39;Courier New&#39;, Courier, monospace;&quot;&gt;SampleEnum &lt;/span&gt;using reflection:&lt;/span&gt;&lt;br /&gt;
&lt;pre class=&quot;brush:java&quot;&gt;import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

public class enumTest {
 public static void main(String[] args) throws ClassNotFoundException,
   IllegalArgumentException, SecurityException,
   InstantiationException, IllegalAccessException,
   InvocationTargetException {
  Constructor c1 = Class.forName(&quot;SampleEnum&quot;).getDeclaredConstructors()[0];
  c1.setAccessible(true);
  SampleEnum e1 = (SampleEnum) c1.newInstance(null);
 }
}&lt;/pre&gt;&lt;span class=&quot;Apple-style-span&quot; style=&quot;color: #351c75;&quot;&gt;On running this example, it will throw an exception:&lt;/span&gt;&lt;br /&gt;
&lt;pre class=&quot;brush:java&quot;&gt;Exception in thread &quot;main&quot; java.lang.IllegalArgumentException: Cannot reflectively create enum objects
 at java.lang.reflect.Constructor.newInstance(Constructor.java:511)
 at enumTest.main(enumTest.java:11)&lt;/pre&gt;&lt;span class=&quot;Apple-style-span&quot; style=&quot;color: #351c75;&quot;&gt;Clearly, you can&#39;t create an object of &lt;span class=&quot;Apple-style-span&quot; style=&quot;font-family: &#39;Courier New&#39;, Courier, monospace;&quot;&gt;Enum &lt;/span&gt;type.&lt;/span&gt;&lt;br /&gt;
&lt;span class=&quot;Apple-style-span&quot; style=&quot;color: #351c75;&quot;&gt;&lt;br /&gt;
&lt;/span&gt;&lt;br /&gt;
&lt;span class=&quot;Apple-style-span&quot; style=&quot;color: #351c75;&quot;&gt;Hence, we can conclude that best way to implement a Singleton pattern is by using &lt;span class=&quot;Apple-style-span&quot; style=&quot;font-family: &#39;Courier New&#39;, Courier, monospace;&quot;&gt;Enum&lt;/span&gt;. It is &lt;b&gt;simple, straightforward and unbreakable&lt;/b&gt;.&lt;/span&gt;&lt;br /&gt;
&lt;span class=&quot;Apple-style-span&quot; style=&quot;color: #351c75;&quot;&gt;&lt;br /&gt;
&lt;/span&gt;&lt;br /&gt;
&lt;span class=&quot;Apple-style-span&quot; style=&quot;color: #351c75;&quot;&gt;Further, in my next post, I will discuss about Singleton pattern in Multithreaded environment.&lt;/span&gt;</description><link>http://hellotojavaworld.blogspot.com/2010/11/singleton-pattern-am-i-implementing-it.html</link><author>noreply@blogger.com (Vineet Mangal)</author><thr:total>15</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-7189178189432269741.post-1623163920458060930</guid><pubDate>Fri, 19 Nov 2010 10:49:00 +0000</pubDate><atom:updated>2010-11-20T10:53:24.806+05:30</atom:updated><category domain="http://www.blogger.com/atom/ns#">Java</category><category domain="http://www.blogger.com/atom/ns#">JVM</category><title>Runtime.addShutdownHook()</title><description>&lt;b&gt;&lt;span class=&quot;Apple-style-span&quot; style=&quot;color: #0b5394;&quot;&gt;Preface:&lt;/span&gt;&lt;/b&gt;&lt;br /&gt;
Every Java Program can attach a shutdown hook to JVM, i.e. piece of instructions that JVM should execute before going down.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;&lt;span class=&quot;Apple-style-span&quot; style=&quot;color: #0b5394;&quot;&gt;Problem:&lt;/span&gt;&lt;/b&gt;&lt;br /&gt;
A program may require to execute some pieces of instructions when application goes down. An application may go down because of several reasons:&lt;br /&gt;
&lt;ul&gt;&lt;li&gt;Because all of its threads have completed execution&lt;/li&gt;
&lt;li&gt;Because of call to &lt;span class=&quot;Apple-style-span&quot; style=&quot;font-family: &#39;Courier New&#39;, Courier, monospace;&quot;&gt;System.exit()&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;Because user hit &lt;span class=&quot;Apple-style-span&quot; style=&quot;font-family: &#39;Courier New&#39;, Courier, monospace;&quot;&gt;CNTRL-C&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;System level shutdown or User Log-Off&lt;/li&gt;
&lt;/ul&gt;&lt;b&gt;&lt;span class=&quot;Apple-style-span&quot; style=&quot;color: #0b5394;&quot;&gt;Few scenarios where this requirement fits are:&lt;/span&gt;&lt;/b&gt;&lt;br /&gt;
&lt;ul&gt;&lt;li&gt;Saving application state, e.g. when you exits from most of the IDEs, they remember the last view&lt;/li&gt;
&lt;li&gt;Closing some database connections&lt;/li&gt;
&lt;li&gt;Send a message to System Administrator that application is shutting down.&lt;/li&gt;
&lt;/ul&gt;&lt;b&gt;&lt;span class=&quot;Apple-style-span&quot; style=&quot;color: #0b5394;&quot;&gt;Solution:&lt;/span&gt;&lt;/b&gt;&lt;br /&gt;
Shutdown Hook comes to rescue in all such scenarios. Application attach a shutdown hook to thereself, that JVM runs when application goes down.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;&lt;span class=&quot;Apple-style-span&quot; style=&quot;color: #0b5394;&quot;&gt;Concept at Abstract level:&lt;/span&gt;&lt;/b&gt;&lt;br /&gt;
Write all the instructions(java code) in a thread&#39;s run method and call &lt;span class=&quot;Apple-style-span&quot; style=&quot;font-family: &#39;Courier New&#39;, Courier, monospace;&quot;&gt;java.lang.Runtime.addShutdownHook(Thread t)&lt;/span&gt;. This method will then register this thread with JVM&#39;s shutdown hook. At the time of shutting down, JVM will run these hooks in parallel (Thread will be started only at the time of shut down by JVM itself).&lt;br /&gt;
&lt;br /&gt;
&lt;span class=&quot;Apple-style-span&quot; style=&quot;color: #351c75;&quot;&gt;Sample code:&lt;/span&gt;&lt;br /&gt;
&lt;pre class=&quot;brush:java&quot;&gt;public class AddShutdownHookSample {
 public void attachShutDownHook(){
  Runtime.getRuntime().addShutdownHook(new Thread() {
   @Override
   public void run() {
    System.out.println(&quot;Inside Add Shutdown Hook&quot;);
   }
  });
  System.out.println(&quot;Shut Down Hook Attached.&quot;);
 }&lt;/pre&gt;&lt;pre class=&quot;brush:java&quot;&gt;public static void main(String[] args) {
  AddShutdownHookSample sample = new AddShutdownHookSample();
  sample.attachShutDownHook();
  System.out.println(&quot;Last instruction of Program....&quot;);
  System.exit(0);
 }}&lt;/pre&gt;&lt;br /&gt;
&lt;span class=&quot;Apple-style-span&quot; style=&quot;color: #351c75;&quot;&gt;Output is:&lt;/span&gt;&lt;br /&gt;
&lt;pre class=&quot;brush:text&quot;&gt;Shut Down Hook Attached.
Last instruction of Program....
Inside Add Shutdown Hook
&lt;/pre&gt;I think now I am clear with on how to use &lt;span class=&quot;Apple-style-span&quot; style=&quot;font-family: &#39;Courier New&#39;, Courier, monospace;&quot;&gt;addShutDownHook&lt;/span&gt;. One can attach as many shutdown hooks as he wants, but beware, these hooks will be run in parallel, so keep concurrency in mind, so that no deadlock or race condition exists.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;&lt;span class=&quot;Apple-style-span&quot; style=&quot;color: #0b5394;&quot;&gt;Are you going to implement it in your application:&lt;/span&gt;&lt;/b&gt;&lt;br /&gt;
There are few more things that should be kept in mind while using this method:&lt;br /&gt;
&lt;ul&gt;&lt;li&gt;&lt;span class=&quot;Apple-style-span&quot; style=&quot;color: blue;&quot;&gt;Number of Shutdown hooks:&lt;/span&gt; There is no limitations on number of shutdown hooks, one can attach as many shutdown hooks as he wants. See the modified version of run method above,&lt;br /&gt;
&lt;pre class=&quot;brush:java&quot;&gt;public void attachShutDownHook(){  
  for(int i =0; i&amp;lt;10;i++){
   Runtime.getRuntime().addShutdownHook(new Thread() {
    @Override
    public void run() {    
     System.out.println(&quot;Inside Add Shutdown Hook : &quot; + Thread.currentThread().getName()) ;
    }
   }); 
  }&lt;/pre&gt;&lt;br /&gt;
See, we have attached ten shutdown hooks here.&lt;br /&gt;
&lt;/li&gt;
&lt;li&gt;&lt;span class=&quot;Apple-style-span&quot; style=&quot;color: blue;&quot;&gt;When to attach Shutdown hook:&lt;/span&gt; Anytime!!!&amp;nbsp;One can attach a shutdown hook at any instance of time, but before JVM starts shutting down. If one tries to register a shutdown hook after JVM starts shutting down, then it will throw an&amp;nbsp;&lt;span class=&quot;Apple-style-span&quot; style=&quot;font-family: &#39;Courier New&#39;, Courier, monospace;&quot;&gt;IllegalStateException &lt;/span&gt;&lt;span class=&quot;Apple-style-span&quot; style=&quot;font-family: inherit;&quot;&gt;with message, &quot;&lt;/span&gt;&lt;span class=&quot;Apple-style-span&quot; style=&quot;font-family: &#39;Courier New&#39;, Courier, monospace;&quot;&gt;Shutdown in progress&quot;&amp;nbsp;&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;&lt;span class=&quot;Apple-style-span&quot; style=&quot;font-family: inherit;&quot;&gt;&lt;span class=&quot;Apple-style-span&quot; style=&quot;color: blue;&quot;&gt;Attaching same hook again:&lt;/span&gt;&lt;b&gt; &lt;/b&gt;One can&#39;t attach same hook again and if it happens, it will throw &amp;nbsp;&lt;/span&gt;&lt;span class=&quot;Apple-style-span&quot; style=&quot;font-family: &#39;Courier New&#39;, Courier, monospace;&quot;&gt;IllegalArgumentException&lt;/span&gt;&amp;nbsp;with message &quot;&lt;span class=&quot;Apple-style-span&quot; style=&quot;font-family: &#39;Courier New&#39;, Courier, monospace;&quot;&gt;Hook previously registered&lt;/span&gt;&quot;&amp;nbsp;&lt;/li&gt;
&lt;li&gt;&lt;span class=&quot;Apple-style-span&quot; style=&quot;color: blue;&quot;&gt;De-Register a Hook:&lt;/span&gt;&lt;b&gt; &lt;/b&gt;One can de-register a hook as well by simply calling method &lt;span class=&quot;Apple-style-span&quot; style=&quot;font-family: &#39;Courier New&#39;, Courier, monospace;&quot;&gt;Runtime.removeShutdownHook(Thread hook)&lt;/span&gt;&lt;br /&gt;
PS: Most of the time, shutdown hooks are registered using&amp;nbsp;anonymous&amp;nbsp;inner classes, but since we don&#39;t have any reference available for them, we should not use anonymous inner classes for hooks that we may de-register, because we need to pass there reference in &lt;span class=&quot;Apple-style-span&quot; style=&quot;font-family: &#39;Courier New&#39;, Courier, monospace;&quot;&gt;removeShutdownHook(Thread hook)&lt;/span&gt; method.&lt;br /&gt;
&lt;/li&gt;
&lt;li&gt;&lt;span class=&quot;Apple-style-span&quot; style=&quot;color: blue;&quot;&gt;Keep an eye on Concurrency:&lt;/span&gt; In case one have attached more than one shutdown hook, then they will run in parallel and hence pron to all issues related to threads, e.g. deadlocks or race conditions. Java Doc for the method also state that:&lt;br /&gt;
&lt;pre class=&quot;brush:java&quot;&gt;/**
  * A &amp;lt;i&amp;gt;shutdown hook&amp;lt;/i&amp;gt; is simply an initialized but unstarted thread.
  * When the virtual machine begins its shutdown sequence it will start all
  * registered shutdown hooks in some unspecified order and let them run
  * concurrently. When all the hooks have finished it will then run all
  * uninvoked finalizers if finalization-on-exit has been enabled. Finally,
  * the virtual machine will halt. Note that daemon threads will continue to
  * run during the shutdown sequence, as will non-daemon threads if shutdown
  * was initiated by invoking the &amp;lt;tt&amp;gt;{@link #exit exit}&amp;lt;/tt&amp;gt; method.
  */&lt;/pre&gt;&lt;br /&gt;
&lt;/li&gt;
&lt;li&gt;&lt;span class=&quot;Apple-style-span&quot; style=&quot;color: blue;&quot;&gt;Reliability of Shutdown Hook:&lt;/span&gt;&amp;nbsp;JVM tries his best to execute shutdown hooks at the time of going down, but it can&#39;t be guranteed, e.g. when JVM is killed using -kill command on Linux or Terminate Process on windows, then JVM exits instantly or it crashes because of some native code invocation. &lt;/li&gt;
&lt;li&gt;&lt;span class=&quot;Apple-style-span&quot; style=&quot;color: blue;&quot;&gt;Keep an eye on Time Consumption by hooks:&lt;/span&gt;&lt;b&gt;&amp;nbsp;&lt;/b&gt;One of the important thing to note is that shutdown hooks should not be time consuming. Consider the scenario when user logs off from OS, then OS assign very limited time to gracefully shutdown, hence in such scenarios JVM can forcefully exit.&lt;/li&gt;
&lt;/ul&gt;&lt;br /&gt;
&lt;ul&gt;&lt;/ul&gt;&lt;div&gt;&lt;b&gt;&lt;span class=&quot;Apple-style-span&quot; style=&quot;color: #0b5394;&quot;&gt;Conclusion:&lt;/span&gt;&lt;/b&gt;&lt;/div&gt;&lt;div&gt;&lt;span class=&quot;Apple-style-span&quot; style=&quot;font-family: &#39;Courier New&#39;, Courier, monospace;&quot;&gt;Runtime.addShutdownHook(Thread hook)&lt;/span&gt; can be a very handy tool, especially in big applications like server implementations as it provide a generic mechanism for graceful exit from JVM. Still, it should be used with care.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;
&lt;/div&gt;&lt;div&gt;&lt;b&gt;&lt;span class=&quot;Apple-style-span&quot; style=&quot;color: #0b5394;&quot;&gt;References:&amp;nbsp;&lt;/span&gt;&lt;/b&gt;&lt;/div&gt;&lt;div&gt;&lt;a href=&quot;http://download.oracle.com/javase/1.5.0/docs/guide/lang/hook-design.html&quot;&gt;http://download.oracle.com/javase/1.5.0/docs/guide/lang/hook-design.html&lt;/a&gt;&lt;/div&gt;&lt;div&gt;&lt;a href=&quot;http://download.oracle.com/javase/6/docs/api/java/lang/Runtime.html#addShutdownHook(java.lang.Thread)&quot;&gt;http://download.oracle.com/javase/6/docs/api/java/lang/Runtime.html#addShutdownHook(java.lang.Thread)&lt;/a&gt;&lt;/div&gt;</description><link>http://hellotojavaworld.blogspot.com/2010/11/runtimeaddshutdownhook.html</link><author>noreply@blogger.com (Vineet Mangal)</author><thr:total>19</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-7189178189432269741.post-1177641972004115332</guid><pubDate>Sat, 06 Nov 2010 18:29:00 +0000</pubDate><atom:updated>2012-12-12T19:33:14.925+05:30</atom:updated><category domain="http://www.blogger.com/atom/ns#">Java</category><category domain="http://www.blogger.com/atom/ns#">remote debug</category><title>Remote debugging in Java</title><description>&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;
&lt;b&gt;&lt;span class=&quot;Apple-style-span&quot; style=&quot;color: #073763;&quot;&gt;&lt;span class=&quot;Apple-style-span&quot; style=&quot;font-family: Georgia, &#39;Times New Roman&#39;, serif;&quot;&gt;Buzz Word: Remote Debugging&lt;/span&gt;&lt;/span&gt;&lt;/b&gt;&lt;br /&gt;
&lt;span class=&quot;Apple-style-span&quot; style=&quot;font-family: inherit;&quot;&gt;Consider a scenario where you can&#39;t run the application in your development environment, e.g. say your application can run only on a server machine (because it is dependent on some third party interface that are not accessible in your development machine) and you have to resolve a problem (bug). What you can do?&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
The solution is &lt;b&gt;&lt;span class=&quot;Apple-style-span&quot; style=&quot;color: #b45f06;&quot;&gt;Remote debugging&lt;/span&gt;&lt;/b&gt;. Remote debugging is debugging an application by connecting the remotely running application with your development environment ( i.e. you can say to connect with code in your IDE).&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;&lt;span class=&quot;Apple-style-span&quot; style=&quot;color: #073763;&quot;&gt;&lt;span class=&quot;Apple-style-span&quot; style=&quot;font-family: Georgia, &#39;Times New Roman&#39;, serif;&quot;&gt;How it works :&amp;nbsp;Basic concept&lt;/span&gt;&lt;/span&gt;&lt;/b&gt;&lt;br /&gt;
Remote debugging feature is provided by Java specification itself. Java provides this feature using listener binding mechanism. Basic concept is pretty simple and straightforward:&lt;br /&gt;
&lt;ul&gt;
&lt;li&gt;Application to be debugged would attach a socket to itself and then would listen debug instructions on that socket.&lt;/li&gt;
&lt;li&gt;Debugger would bind itself to that socket and then send instructions on that socket.&lt;/li&gt;
&lt;/ul&gt;
&lt;b&gt;&lt;span class=&quot;Apple-style-span&quot; style=&quot;color: #073763;&quot;&gt;&lt;span class=&quot;Apple-style-span&quot; style=&quot;font-family: Georgia, &#39;Times New Roman&#39;, serif;&quot;&gt;Running an application in debug mode:&lt;/span&gt;&lt;/span&gt;&lt;/b&gt;&lt;br /&gt;
As I said earlier, for remote debugging, you need to run that application in debug mode. To run an application in debug mode requires to provide specific jvm arguments to &quot;java&quot; command.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;&lt;span class=&quot;Apple-style-span&quot; style=&quot;font-family: Georgia, &#39;Times New Roman&#39;, serif;&quot;&gt;&lt;span class=&quot;Apple-style-span&quot; style=&quot;color: #073763;&quot;&gt;JVM arguments for DEBUGGING:&lt;/span&gt;&lt;/span&gt;&lt;/b&gt;&lt;br /&gt;
&lt;ul&gt;
&lt;li&gt;For&lt;b&gt; &lt;span class=&quot;Apple-style-span&quot; style=&quot;color: #b45f06;&quot;&gt;JVMs prior to 1.5&lt;/span&gt;&lt;/b&gt;&lt;span class=&quot;Apple-style-span&quot; style=&quot;color: #bf9000;&quot;&gt;:&lt;/span&gt;&lt;br /&gt;
One need to supply two arguments, &lt;b&gt;&lt;span class=&quot;Apple-style-span&quot; style=&quot;color: #b45f06;&quot;&gt;-Xdebug&lt;/span&gt;&lt;/b&gt; and &lt;b&gt;&lt;span class=&quot;Apple-style-span&quot; style=&quot;color: #b45f06;&quot;&gt;-Xrunjdwp&lt;/span&gt;&lt;/b&gt;. -Xdebug tells JVM to run the application in debug mode, while -Xrunjdwp is used to supply debug parameters (It can also be used in JVM 1.5 or 1.6 as well)&lt;br /&gt;
e.g. &lt;span class=&quot;Apple-style-span&quot; style=&quot;font-family: &#39;Courier New&#39;, Courier, monospace;&quot;&gt;&lt;span class=&quot;Apple-style-span&quot; style=&quot;font-size: small;&quot;&gt;&lt;span class=&quot;Apple-style-span&quot; style=&quot;color: #073763;&quot;&gt;&lt;b&gt;-Xdebug -Xrunjdwp:transport=dt_socket,address=8000,server=y,suspend=n&lt;/b&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;For &lt;b&gt;&lt;span class=&quot;Apple-style-span&quot; style=&quot;color: #b45f06;&quot;&gt;JVMs 1.5 and 1.6&lt;/span&gt;&lt;/b&gt;:&lt;br /&gt;
Debug library is passed as &lt;b&gt;&lt;span class=&quot;Apple-style-span&quot; style=&quot;color: #b45f06;&quot;&gt;-agentlib&lt;/span&gt;&lt;/b&gt; argument, along with debug paramters. Native library name for debugging is &lt;b&gt;&lt;span class=&quot;Apple-style-span&quot; style=&quot;color: #b45f06;&quot;&gt;jdwp&lt;/span&gt;&lt;/b&gt;, so one need to supply -agentlib:jdwp along with debug paramters.&lt;br /&gt;
e.g. &lt;span class=&quot;Apple-style-span&quot; style=&quot;font-family: &#39;Courier New&#39;, Courier, monospace;&quot;&gt;&lt;span class=&quot;Apple-style-span&quot; style=&quot;font-size: small;&quot;&gt;&lt;b&gt;&lt;span class=&quot;Apple-style-span&quot; style=&quot;color: #073763;&quot;&gt;-agentlib:jdwp=transport=dt_socket,address=8000,server=y,suspend=n&lt;/span&gt;&lt;/b&gt;&lt;/span&gt;&lt;/span&gt;&lt;br /&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;b&gt;&lt;span class=&quot;Apple-style-span&quot; style=&quot;font-family: Georgia, &#39;Times New Roman&#39;, serif;&quot;&gt;&lt;span class=&quot;Apple-style-span&quot; style=&quot;color: #073763;&quot;&gt;Detail of debug parameters:&lt;/span&gt;&lt;/span&gt;&lt;/b&gt;&lt;br /&gt;
&lt;ul&gt;
&lt;li&gt;&lt;b&gt;Name&lt;/b&gt;: &lt;span class=&quot;Apple-style-span&quot; style=&quot;color: #20124d;&quot;&gt;&lt;b&gt;&lt;span class=&quot;Apple-style-span&quot; style=&quot;font-family: &#39;Courier New&#39;, Courier, monospace;&quot;&gt;&lt;span class=&quot;Apple-style-span&quot; style=&quot;font-size: small;&quot;&gt;help&lt;/span&gt;&lt;/span&gt;&lt;/b&gt;&lt;/span&gt;&lt;br /&gt;
&lt;b&gt; Is Optional&lt;/b&gt; : Yes&lt;br /&gt;
&lt;b&gt; Default Value&lt;/b&gt;: N/A. This parameter doesn&#39;t have any value at all.&lt;br /&gt;
&lt;b&gt; Description&lt;/b&gt;: It prints all the available options on the console and exits the JVM.&lt;br /&gt;
&lt;b&gt; Example&lt;/b&gt;: &lt;span class=&quot;Apple-style-span&quot; style=&quot;font-size: small;&quot;&gt;&lt;span class=&quot;Apple-style-span&quot; style=&quot;font-family: &#39;Courier New&#39;, Courier, monospace;&quot;&gt;&lt;b&gt;&lt;span class=&quot;Apple-style-span&quot; style=&quot;color: #073763;&quot;&gt;java -agentlib:jdwp=help&lt;/span&gt;&lt;/b&gt;&lt;/span&gt;&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiiVo2ZA7I3qnXF4hcoh5UsLluMDnTZUDize0fBxN6O8S7wJbLszwXamdOQbPws2-4XbkGhMAWVO5NouzZygFSSwMFH6uR69cn0fNz4xUZZOm_IrEEMELDq-IORsq83kL0x5o2YUqYiMig/s1600/help.jpg&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;167&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiiVo2ZA7I3qnXF4hcoh5UsLluMDnTZUDize0fBxN6O8S7wJbLszwXamdOQbPws2-4XbkGhMAWVO5NouzZygFSSwMFH6uR69cn0fNz4xUZZOm_IrEEMELDq-IORsq83kL0x5o2YUqYiMig/s400/help.jpg&quot; width=&quot;400&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;/li&gt;
&lt;li&gt;&lt;b&gt;Name&lt;/b&gt;: &lt;b&gt;&lt;span class=&quot;Apple-style-span&quot; style=&quot;font-size: small;&quot;&gt;&lt;span class=&quot;Apple-style-span&quot; style=&quot;font-family: &#39;Courier New&#39;, Courier, monospace;&quot;&gt;&lt;span class=&quot;Apple-style-span&quot; style=&quot;color: #073763;&quot;&gt;transport&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/b&gt;&lt;br /&gt;
&lt;b&gt; Is Optional&lt;/b&gt;: No (It is a required field)&lt;br /&gt;
&lt;b&gt; Default Value&lt;/b&gt;: No default value specified in specifications. Totally depends upon native lib provided by JVM implementation.&lt;br /&gt;
&lt;b&gt; Description&lt;/b&gt;: Transport protocol implementation used for communication between debugger and application. Sun JVM ships two implementations, Socket Transport and Shared Memory Transport. Value for Socket Transport is &quot;dt_socket&quot;, while that of Shared Memory Transport is &quot;dt_shmem&quot;.&lt;br /&gt;
Shared Memory is available only on Microsoft Windows. &lt;br /&gt;
&lt;/li&gt;
&lt;li&gt;&lt;b&gt;Name&lt;/b&gt;: &lt;b&gt;&lt;span class=&quot;Apple-style-span&quot; style=&quot;font-size: small;&quot;&gt;&lt;span class=&quot;Apple-style-span&quot; style=&quot;font-family: &#39;Courier New&#39;, Courier, monospace;&quot;&gt;&lt;span class=&quot;Apple-style-span&quot; style=&quot;color: #073763;&quot;&gt;server&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/b&gt;&lt;br /&gt;
&lt;b&gt; Is Optional&lt;/b&gt;: Yes&lt;br /&gt;
&lt;b&gt; Default Value&lt;/b&gt;: n&lt;br /&gt;
&lt;b&gt; Description&lt;/b&gt;: Tells whether JVM will be used as Server or as client in reference to JVM-Debugger communication. If JVM will act as server, then debugger will attach itself to this JVM, otherwise if JVM will act as a client, then it will attach itself to debugger.&lt;br /&gt;
&lt;/li&gt;
&lt;li&gt;&lt;b&gt;Name&lt;/b&gt;: &lt;span class=&quot;Apple-style-span&quot; style=&quot;font-family: &#39;Courier New&#39;, Courier, monospace;&quot;&gt;&lt;span class=&quot;Apple-style-span&quot; style=&quot;font-size: small;&quot;&gt;&lt;span class=&quot;Apple-style-span&quot; style=&quot;color: #073763;&quot;&gt;&lt;b&gt;address&lt;/b&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;br /&gt;
&lt;b&gt; Is Optional&lt;/b&gt;: Optional when JVM acts as server and Required when JVM acts as client.&lt;br /&gt;
&lt;b&gt; Description&lt;/b&gt;: Specifies the socket address. &lt;br /&gt;
If JVM is server (i.e. server argument is set to &#39;y&#39;): Then JVM listens the debugger at this socket. If address is not specified, then JVM picks any of available socket, starts listening on this socket and prints its address on console.&lt;br /&gt;
If JVM is client (i.e. server argument is set to &#39;n&#39;): JVM attaches itself to this address to connect itself to debugger.&lt;br /&gt;
&lt;/li&gt;
&lt;li&gt;&lt;b&gt;Name&lt;/b&gt;: &lt;b&gt;&lt;span class=&quot;Apple-style-span&quot; style=&quot;font-family: &#39;Courier New&#39;, Courier, monospace;&quot;&gt;&lt;span class=&quot;Apple-style-span&quot; style=&quot;font-size: small;&quot;&gt;&lt;span class=&quot;Apple-style-span&quot; style=&quot;color: #073763;&quot;&gt;timeout&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/b&gt;&lt;br /&gt;
&lt;b&gt; Is Optional&lt;/b&gt;: Yes&lt;br /&gt;
&lt;b&gt; Description&lt;/b&gt;: As its name signifies, it is the wait time for JVM. If JVM is server, then JVM will wait for &quot;timeout&quot; amount of time for debugger to attach to its socket and if JVM is client, then it will exit if fail to attach to debugger in timeout time.&lt;br /&gt;
&lt;/li&gt;
&lt;li&gt;&lt;b&gt;Name&lt;/b&gt;: &lt;span class=&quot;Apple-style-span&quot; style=&quot;font-family: &#39;Courier New&#39;, Courier, monospace;&quot;&gt;&lt;span class=&quot;Apple-style-span&quot; style=&quot;font-size: small;&quot;&gt;&lt;span class=&quot;Apple-style-span&quot; style=&quot;color: #073763;&quot;&gt;&lt;b&gt;suspend&lt;/b&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;br /&gt;
&lt;b&gt; Is Optional&lt;/b&gt;: yes&lt;br /&gt;
&lt;b&gt; Default Value&lt;/b&gt;: y&lt;br /&gt;
&lt;b&gt; Description&lt;/b&gt;: Tells JVM to suspend the invocation of application(s) until the debugger and JVM are attached together.&lt;br /&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;br /&gt;
Apart these there are launch, onthrow, onuncaught options as well, details of which can be find at&amp;nbsp;&lt;a href=&quot;http://download.oracle.com/javase/6/docs/technotes/guides/jpda/conninv.html#Invocation&quot;&gt;JPDA&lt;/a&gt;. But these options are seldom used.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Now, lets take simple example to debug a program using eclipse.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;&lt;span class=&quot;Apple-style-span&quot; style=&quot;font-family: Georgia, &#39;Times New Roman&#39;, serif;&quot;&gt;&lt;span class=&quot;Apple-style-span&quot; style=&quot;color: #073763;&quot;&gt;Steps&lt;/span&gt;&lt;/span&gt;&lt;/b&gt;:&lt;br /&gt;
&lt;ul&gt;
&lt;li&gt;Select from eclipse menu, Run-&amp;gt;Debug Configuration, It will open Debug Configuration setup.&lt;/li&gt;
&lt;li&gt;On Debug configuration window, create a new &quot;Remote Java Application&quot; configuration.&lt;/li&gt;
&lt;li&gt;Select the project to be debugged and provide a Name.&lt;/li&gt;
&lt;li&gt;Select connection type, Socket Attach or Socket Listen. Select Socket Attach, if you want to attach the debugger to application, i.e. application is running in Server mode. On the other hand, select Socket Listen, in case you want debugger to listen for JVM to connect, i.e. JVM is running in client mode and debugger is running as server.&lt;/li&gt;
&lt;li&gt;If JVM to be run in Server mode, then first start JVM in debug mode and then start the newly created debugger,&amp;nbsp;&lt;/li&gt;
&lt;li&gt;And if Debugger to be run in Server mode, then first start the debugger and then start JVM.&lt;/li&gt;
&lt;/ul&gt;
&lt;b&gt;&lt;span class=&quot;Apple-style-span&quot; style=&quot;font-family: Georgia, &#39;Times New Roman&#39;, serif;&quot;&gt;&lt;span class=&quot;Apple-style-span&quot; style=&quot;color: #073763;&quot;&gt;Debugging in Action:&lt;/span&gt;&lt;/span&gt;&lt;/b&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgCTh2yIhmx6C1UEGAjChxFo9ab5e8foSVQvGXbh91h7oO-1cFCVmcv6RREJYGxwbDXQQVah23fNE3JZ-tgonjxvGU9uuz_5R8_7CFcqN0rWRGD2DLQqSeHueyUOYRRQQzJw8tvVI1BV4c/s1600/Select+Debug.jpg&quot; imageanchor=&quot;1&quot; style=&quot;clear: left; float: left; margin-bottom: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;296&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgCTh2yIhmx6C1UEGAjChxFo9ab5e8foSVQvGXbh91h7oO-1cFCVmcv6RREJYGxwbDXQQVah23fNE3JZ-tgonjxvGU9uuz_5R8_7CFcqN0rWRGD2DLQqSeHueyUOYRRQQzJw8tvVI1BV4c/s400/Select+Debug.jpg&quot; width=&quot;400&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEilUYho2FM4maIrSl4adbmZU7GKSmZXD940XuVi2r57HY7JSkffPW5zTYGmBaJyupyDHAX1tGyQa3GbGA0k8esgBVueTVeJyVr0n6i0ZlisPbN4GHMaVw7__2N6oNdicKgtmu-BhnmjgnQ/s1600/Setup+Remote+Application.jpg&quot; imageanchor=&quot;1&quot; style=&quot;clear: left; float: left; margin-bottom: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;320&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEilUYho2FM4maIrSl4adbmZU7GKSmZXD940XuVi2r57HY7JSkffPW5zTYGmBaJyupyDHAX1tGyQa3GbGA0k8esgBVueTVeJyVr0n6i0ZlisPbN4GHMaVw7__2N6oNdicKgtmu-BhnmjgnQ/s400/Setup+Remote+Application.jpg&quot; width=&quot;400&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;br /&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgJp53c2I4YGIIksg-Uf_IoURUrCr2bonyn03FonnTkVa1l1FISqe-wuwOE382FIc00MAUripkkMpEN08fGZDx6_jI9rv4NNUuMqVXs3QGgLp6xrh3xKqqypZoUce2InYbpR_WUjHQekpw/s1600/Run+Application+in+Debug+Mode.jpg&quot; imageanchor=&quot;1&quot; style=&quot;clear: left; float: left; margin-bottom: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;86&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgJp53c2I4YGIIksg-Uf_IoURUrCr2bonyn03FonnTkVa1l1FISqe-wuwOE382FIc00MAUripkkMpEN08fGZDx6_jI9rv4NNUuMqVXs3QGgLp6xrh3xKqqypZoUce2InYbpR_WUjHQekpw/s400/Run+Application+in+Debug+Mode.jpg&quot; width=&quot;400&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhdGZVsJybU1cLnQh_ehetiErq3Jf9M-Gw_OGR-WNcDZoqPPb-aVkuCuai7G56ufIerFDON-0SGmCbku9i0ne34DqNgw7a9vXDL81tj1vW5XRnLmIuvKc5T7Dc9H6Ppq_FfiRJo-HPvJ9A/s1600/Start+debugger.jpg&quot; imageanchor=&quot;1&quot; style=&quot;clear: left; float: left; margin-bottom: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;320&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhdGZVsJybU1cLnQh_ehetiErq3Jf9M-Gw_OGR-WNcDZoqPPb-aVkuCuai7G56ufIerFDON-0SGmCbku9i0ne34DqNgw7a9vXDL81tj1vW5XRnLmIuvKc5T7Dc9H6Ppq_FfiRJo-HPvJ9A/s400/Start+debugger.jpg&quot; width=&quot;400&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;br /&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;/div&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;/div&gt;
&lt;br /&gt;
&lt;br /&gt;
In this way one can debug any java application using any standard java debugger.&lt;br /&gt;
&lt;br /&gt;
Later in some post I will try to cover &quot;How to debug&quot; for different kind of java application, e.g. debugging application running in Tomcat or Jboss, debugging a JWS and like that.&lt;/div&gt;
</description><link>http://hellotojavaworld.blogspot.com/2010/11/remote-debugging-in-java.html</link><author>noreply@blogger.com (Vineet Mangal)</author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiiVo2ZA7I3qnXF4hcoh5UsLluMDnTZUDize0fBxN6O8S7wJbLszwXamdOQbPws2-4XbkGhMAWVO5NouzZygFSSwMFH6uR69cn0fNz4xUZZOm_IrEEMELDq-IORsq83kL0x5o2YUqYiMig/s72-c/help.jpg" height="72" width="72"/><thr:total>6</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-7189178189432269741.post-3519009962915267555</guid><pubDate>Tue, 19 Oct 2010 10:40:00 +0000</pubDate><atom:updated>2010-11-20T10:52:13.393+05:30</atom:updated><category domain="http://www.blogger.com/atom/ns#">Immutable</category><category domain="http://www.blogger.com/atom/ns#">Java</category><title>Immutable Objects</title><description>&lt;b&gt;What is Immutable Object&lt;/b&gt;&lt;br /&gt;
An immutable object is something whose state can&#39;t be change after there creation, e.g. String objects. Once you have created a String object, you can&#39;t alter this.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Creating an Immutable object&#39;s class&lt;/b&gt;&lt;br /&gt;
Creating an immutable object&#39;s class can be tricky. Minimal requirement to create an immutable object&#39;s class is, make class and every member variable, &quot;final&quot;.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush:java&quot;&gt;public final class SimpleImmutableClass {
 final int intVal = 5;
 final String sampleString = &quot;Hello&quot;;
 final Integer intObj = Integer.valueOf(10);
}&lt;/pre&gt;&lt;br /&gt;
&lt;span class=&quot;Apple-style-span&quot; style=&quot;font-family: &#39;Courier New&#39;, Courier, monospace;&quot;&gt;SimpleImmutableClass &lt;/span&gt;is a class of mutable object, one can&#39;t change its state, once object is created. But it is too simple case. In real world situation is far more complex, you will rarely find such a simple class that has only primitive or immutable members (actually &lt;span class=&quot;Apple-style-span&quot; style=&quot;font-family: &#39;Courier New&#39;, Courier, monospace;&quot;&gt;String &lt;/span&gt;and &lt;span class=&quot;Apple-style-span&quot; style=&quot;font-family: &#39;Courier New&#39;, Courier, monospace;&quot;&gt;Integer &lt;/span&gt;classes are classes for immutable objects, provided by JDK API stack).&lt;br /&gt;
&lt;br /&gt;
Consider following example, that has mutable objects as members, though every member is final, private and has only getters (to access) and no setters, but still do you think that it is a class that can produce immutable objects.&lt;br /&gt;
&lt;pre class=&quot;brush:java&quot;&gt;public final class NotAnImmutableClass{
private final ArrayList&amp;lt;String&amp;gt; sampleList = new ArrayList&amp;lt;String&amp;gt;();
 private final Date today = new Date();
 
 public ArrayList&amp;lt;String&amp;gt; getSampleList() {
  return sampleList;
 }
 public Date getToday() {
  return today;
 }
}&lt;/pre&gt;&lt;br /&gt;
What do you think about above class, is it really an Immutable object&#39;s class? Unfortunately, a big NO. At first it seems like it is an immutable object&#39;s class, after all, it is a final class, every variable is final and private and to give more assurance, it doesn&#39;t contain any &quot;setter&quot; method. Some may give me a good fight arguing about immutability of the objects of this class.&lt;br /&gt;
But then comes the villain, the very basic of Java, the &quot;Reference&quot;. &amp;nbsp;Consider the following listing:&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush:java&quot;&gt;class PokeIntoSoCalledImmutableClass {
public void poke(){
  NotAnImmutableClass notAnImmutableClass = new NotAnImmutableClass();
  List&amp;lt;String&amp;gt; samples = notAnImmutableClass.getSampleList();
  Date d = notAnImmutableClass.getToday();
  samples.add(&quot;Poked String&quot;);
  d.setYear(111);  
  System.out.println(notAnImmutableClass.getSampleList().size());
  System.out.println(notAnImmutableClass.getToday());
 }
 
}
&lt;/pre&gt;What do you think, the method &amp;nbsp;&lt;span class=&quot;Apple-style-span&quot; style=&quot;font-family: &#39;Courier New&#39;, Courier, monospace;&quot;&gt;poke()&lt;/span&gt; would print? Do you think it would print &quot;0&quot; and &quot;Sun Jun 05 00:00:00 IST 2010&quot;? &amp;nbsp;Answer is a big NO!!!&lt;br /&gt;
&lt;br /&gt;
So, here comes another rule for a class whose objects to be immutable, either it should not have any mutable field (as in our case) or it should not publish (expose) its mutable members.&lt;br /&gt;
&lt;br /&gt;
But again question is, what if we have to expose mutable objects and still we need that our class&#39;s objects are immutable? Well answer is simple but tricky. USE CLONING!!!! If exposed object contains only immutable objects or primitive types, use shallow copy, otherwise use deep copy.&lt;br /&gt;
Correct way to implement Immutable class:&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush:java&quot;&gt;import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class AnImmutableClass {
 private final ArrayList&amp;lt;String&amp;gt; sampleList = new ArrayList&amp;lt;String&amp;gt;();
 private final Date today = new Date(110,5,5);
 
 public ArrayList&amp;lt;String&amp;gt; getSampleList() {
  ArrayList&amp;lt;String&amp;gt; returnList = new ArrayList&amp;lt;String&amp;gt;();
  for(String s : sampleList){   
   returnList.add(s);
  }
  return returnList;
 }
 public Date getToday() {
  return (Date)today.clone();
 }
 
 public static void main(String[] args) {
  PokeIntoSoCalledImmutableClass pokeClass = new PokeIntoSoCalledImmutableClass();
  pokeClass.poke();
 }
 
}

class PokeIntoSoCalledImmutableClass {
 public void poke(){
  AnImmutableClass anImmutableClass = new AnImmutableClass();
  List&amp;lt;String&amp;gt; samples = anImmutableClass.getSampleList();
  Date d = anImmutableClass.getToday();
  samples.add(&quot;Poked String&quot;);
  d.setYear(111);  
  System.out.println(anImmutableClass.getSampleList().size());
  System.out.println(anImmutableClass.getToday());
 }
 
}
&lt;/pre&gt;&lt;br /&gt;
I here conclude with set of rules to make a class whose objects are immutable:&lt;br /&gt;
&lt;ul&gt;&lt;li&gt;&lt;b&gt;Must be final&lt;/b&gt;&lt;/li&gt;
&lt;li&gt;&lt;b&gt;Only final members should be exposed to outer world&lt;/b&gt;&lt;/li&gt;
&lt;li&gt;&lt;b&gt;Exposed members should be immutable&lt;/b&gt;&lt;/li&gt;
&lt;li&gt;&lt;b&gt;If it is require to expose mutable members, then use shallow or deep cloning while exposing them&lt;/b&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;div&gt;&lt;br /&gt;
&lt;/div&gt;&lt;div&gt;&lt;br /&gt;
&lt;/div&gt;</description><link>http://hellotojavaworld.blogspot.com/2010/10/immutable-class.html</link><author>noreply@blogger.com (Vineet Mangal)</author><thr:total>16</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-7189178189432269741.post-6280213918760536091</guid><pubDate>Sun, 30 Aug 2009 15:39:00 +0000</pubDate><atom:updated>2010-11-20T10:53:46.555+05:30</atom:updated><category domain="http://www.blogger.com/atom/ns#">For-each</category><category domain="http://www.blogger.com/atom/ns#">Java</category><title>FOR-EACH Loop</title><description>&lt;a href=&quot;http://technorati.com/faves?sub=addfavbtn&amp;amp;add=http://funinjava.blogspot.com&quot;&gt;&lt;img alt=&quot;Add to Technorati Favorites&quot; src=&quot;http://static.technorati.com/pix/fave/btn-fave2.png&quot; /&gt;&lt;/a&gt;&lt;br /&gt;
Java 5 introduced a lot of new features which were being sought for quite long. It is a total overhaul of the language. Though these features have minimum or no effect on produced bytecode, Bytecode remains unchanged.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;FOR-EACH LOOP:&lt;/b&gt;&lt;br /&gt;
&lt;br /&gt;
It is irritating. I need to traverse all elements in a data structure and for this I have to write a conditional loop as I do in C language. Come on, it is a high level language, it should have natural processing. Most natural way should be,&lt;br /&gt;
&lt;br /&gt;
&quot;FOR EACH ELEMENT IN DATA STRUCTURE, DO SOMETHING&quot;&lt;br /&gt;
&lt;br /&gt;
And it is what, the Sun engineers did. They introduced a &quot;FOR EACH&quot; loop for traversing all the elements in a data structure but with a condition, data structure should implement &quot;Iterable&quot; interface.&lt;br /&gt;
&lt;br /&gt;
PS : There is one exception to it. Arrays can also be iterated in this way.&lt;br /&gt;
&lt;br /&gt;
Syntax for &quot;FOR EACH&quot; loop is:&lt;br /&gt;
&lt;br /&gt;
For(Element e : DATA STRUCTURE (of type element) ){&lt;br /&gt;
&lt;br /&gt;
//do something with e&lt;br /&gt;
&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Let&#39;s illustrate it with some examples.&lt;br /&gt;
&lt;br /&gt;
Let&#39;s define a Java Collection and traverse it. All collections in Java are of type Collection and Collection Interface (java.util.Collection) extends the &quot;Iterable&quot; interface. Hence, all collections in Java are candidate for &quot;FOR EACH LOOP&quot;.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush:java&quot; name=&quot;code&quot;&gt;//Code

//Define a Collection

Collection&amp;lt;String&amp;gt; collection = new ArrayList&amp;lt;String&amp;gt;();

//Add elements in collection

collection.add(&quot;FIRST&quot;);

collection.add(&quot;SECOND&quot;);

collection.add(&quot;THIRD&quot;); 
//Traverse using For each loop 
for(String s : collection) 
{ 
//Print the element 
System.out.println(s); 
} 

//Code End.&lt;/pre&gt;&lt;br /&gt;
Well, Java specification states that any class that implements Iterable interface, is a candidate of &quot;For Each&quot; loop. It means that we can also take advantage of this feature in user defined data structures as well. I googled, but did not find any example for this implementation. So, I am posting an implementation of user defined class that take advantage of this feature.&lt;br /&gt;
&lt;br /&gt;
I have created a class for Linear Link list.&lt;br /&gt;
&lt;pre class=&quot;brush:java&quot; name=&quot;code&quot;&gt;//Code Start
import java.util.Iterator;
/**
 * This class is Java implementation of LinearLinkList. 
 * This class demonstrates the implementation of 
 * for each loop. A data structure must
 * implement Iterable interface in order
 *  to use the for each loop
 * feature of Java 1.5
 *  
 * @author Vineet 
 * @param &amp;lt; T &amp;gt;
 */
public class LinearLinkList&amp;lt; T &amp;gt; implements Iterable&amp;lt; T &amp;gt; {
 /**
  * It represents the header of LinkList. 
  * It is the first node of LinkList.
  */
 private Node&amp;lt; T &amp;gt; head = new Node&amp;lt; T &amp;gt;();
 /**
  * Size of LinkList.
  */
 private int size = 0;


 /**
  * Constructs empty link list.
  */
 public LinearLinkList() {
 }


 /**
  * Evaluates the size of link list.
  * 
  * @return size of link list.
  */
 public int size() {
  return size;
 }


 /**
  * Adds an element at the end of list. 
  * If it is empty list, then element is
  * set in head node.
  * 
  * @param element
  */
 public void add(T element) {
  // If it is empty list, set element in header node.
  if (size() == 0) {
   head.element = element;
  }
  // Else, create a node with this element 
  //and add at the end of list.
  else {
   Node&amp;lt; T &amp;gt; node = new Node&amp;lt; T &amp;gt;();
   node.element = element;
   Node&amp;lt; T &amp;gt; temp = head;
   while (temp.nextNode != null) {
    temp = temp.nextNode;
   }
   temp.nextNode = node;
   temp = null;
  }
  size++;
 }


 /**
  * String representation of Link List.
  */
 @Override
 public String toString() {
  StringBuilder str = new StringBuilder();
  Iterator&amp;lt; T &amp;gt; itr = this.iterator();
  while (itr.hasNext()) {
   str.append(itr.next().toString() + &quot;,&quot;);
  }
  str.deleteCharAt(str.lastIndexOf(&quot;,&quot;));


  return str.toString();
 }


 @Override
 public int hashCode() {
  int hash = (int) (31 * Math.random() + 61 * Math.random());
  return hash;
 }


 /**
  * Returns iterator for this list. It enables it to 
  * be candidate of for each loop.
  */
 @Override
 public Iterator&amp;lt; T &amp;gt; iterator() {
  // TODO Auto-generated method stub
  return new Itr();
 }


 /**
  * Finds the element at index position in list.
  * 
  * @param index
  *            position of element to be sought.
  * @return Element at position index
  */
 public T get(int index) {
  Node&amp;lt; T &amp;gt; temp = head;
  while (index &amp;gt; 1) {
   temp = temp.nextNode;
   index--;
  }
  return temp.element;
 }


 /**
  * This class is iterator for this Link List.
  * It enables the navigation of link list.
  * 
  * @author Vineet
  * 
  */
 private class Itr implements Iterator&amp;lt; T &amp;gt; {
  private int cursor = 0;
  private Node&amp;lt; T &amp;gt; temp = head;


  @Override
  public boolean hasNext() {
   return cursor++ &amp;lt; size();
  }


  @Override
  public T next() {
   T element = temp.element;
   temp = temp.nextNode;
   return element;
  }


  @Override
  public void remove() {
  }


 }


 private static class Node&amp;lt; T &amp;gt; {


  T element;
  Node&amp;lt; T &amp;gt; nextNode;


 }


 public static void main(String[] args) {


  LinearLinkList&amp;lt; String &amp;gt; test = new LinearLinkList&amp;lt; String &amp;gt;();
  test.add(&quot;First&quot;);
  test.add(&quot;Second&quot;);
  test.add(&quot;Third&quot;);
  test.add(&quot;Fourth&quot;);
  test.add(&quot;Fifth&quot;);


  // Now it will work with For Each loop
  for (String s : test) {
   System.out.println(s);
  }
  System.out.println(test);
 }


}



//Code Ends
&lt;/pre&gt;</description><link>http://hellotojavaworld.blogspot.com/2009/08/java-15-features.html</link><author>noreply@blogger.com (Vineet Mangal)</author><thr:total>1</thr:total></item></channel></rss>