Monday, November 26, 2007

Do you like static imports?

Static imports have been around since Java 1.5, but they are a feature that I have rarely used, or even seen much in code. I guess that's because static imports is not a must have thing, but something that is nice to have. Using static imports takes some pain away from typing code.

For example, instead of writing

System.out.println("some message");

we could statically import System.out and write it as follows:

static import System.out;
public class HelloWorld {
  public static void main(String args[]) {
    out.println("Hello World");

Well using static imports definetely takes the pain away from typing System.out every time. However sometimes using static imports can also reduce the readability of code, because we would have to look at the imports to know if a variable in code was declared within that class itself or imported statically.

Having said that, one place where I would definetely use static imports is in importing enums. Since elements of an enum are always public static final, it makes some sense to statically import all the enum elements so that we do not have to qualify them while using them.

public enum Grade {

package example.staticimport;
import static example.staticimport.Grade.*;
import static java.lang.System.out;

public class GradePrinter {
 public static void main(String args[]) {
       Grade g = getGrade();
       switch(g) {
         case A:
     case B:
             out.println("Very Good");
         case C:
             out.println("You Can Do Better");

/   private static Grade getGrade() {
//return any grade
        return Grade.A;


  • Saturday, November 17, 2007

    Spot the mistake

    Can you spot the mistake in this code?

    // BROKEN - throws NoSuchElementException!

    for (Iterator i = suits.iterator(); i.hasNext(); )
    for (Iterator j = ranks.iterator(); j.hasNext(); )
    sortedDeck.add(new Card(,;

    If not, check this article on the Java for...each loop. 

    Note: This text was originally posted on my earlier blog at

    Sunday, October 28, 2007

    The risk of invoking public methods in Java

    In the past few posts we have discussed how it can be dangerous to extend a class that we do not control, if it has not been designed for subclassing. We understood this concept with a specific example from Josh Bloch's book: Effective Java. In the example we subclassed the HashSet class in the JDK.

    Without repeating the material, I will simply reiterate what I said in my previous post:

    The real problem was the class AbstractCollection which was not designed properly for inheritance. It is a non-final class with a public method addAll(Collection c) which invokes another non-final public method add(Object o).

    Here is a possible implementation of the HashSet class that does not break the DRY principle and is also safe for extending...

    Saturday, October 20, 2007

    Never invoke a public method from another public method

    In the previous post we saw how subclassing from a class not designed for inheritance, can be dangerous. Using composition instead of inheritance would have solved the problem. But what was the crux of the problem? Could such a trap have been avoided? Could AbstractCollection have been implemented so that such a situation would not have arisen in the first place?

    The real problem was the class AbstractCollection which was not designed properly for inheritance. It is a non-final class with a public method addAll(Collection c) which invokes another non-final public method add(Object o).

    How should AbstractCollection have implemented add(Object o) and addAll(Collection c) to prevent such a problem?

    I do not know if this problem has been fixed in OpenJDK. They may have not been able to do so to maintain backwards compatibility. You can check out the sources from their website.

    In the next post we will discuss an idiom for preventing such a situation. 

    Discuss this post in the learning forum.

    Note: This text was originally posted on my earlier blog at

    Tuesday, October 16, 2007

    A Java example showing the dangers of implementation inheritance

    I ended my previous post with a paragraph from Josh Bloch's book, Effective Java. In his book, Josh explains why inheriting classes from a different package (especially inheriting from a class that may not be designed and documented for inheritance) can be dangerous. Below you will find Josh's example (from Effective Java) that explains the concept. Many many thanks to Josh Bloch for graciously giving me permission to reproduce the example here :-)

    The class InstrumentedHashSet is a subclass of HashSet, that maintains a count of the number of objects added. It overrides the add(Object o) and addAll(Collection c) methods from HashSet to maintain a count of objects added to it. These methods increment the count and then delegate responsibility for adding the element to HashSet. The number of objects added can be obtained from the method getAddCount().

    This seems like a reasonable way to count objects added to the Set. Unfortunately it's not. But first let's have a look at the code of InstrumentedHashSet.



    Below is a test case for the addAll(Collection c) method of InstrumentedHashSet. By the way, this test was written by me, so if there is anything wrong with it, it's entirely my fault :-)




    Now let us run the unit test.


    Oops :-( we expected a count of 3, but looks like InstrumentedHashSet is reporting 6. Now, how did that happen???

    Look again at InstrumentedHashSet. The method addAll(Collection c) calls super.addAll(c) after incrementing the count. This ends up invoking a method implemented in AbstractCollection in the JDK (ver 1.6). It has implemented addAll(Collection c) to iterate through the given Collection and invoke add(Object o) for every element in the Collection. Since we have overriden add(Object o), it is our implementation that get's called. The count is added for every element of the Collection in addAll(Collection c) as well as in add(Object o), resulting in the count increasing by 2 for every object. That's the reason we got a count of 6 instead of 3.

    So to summarize. Be very careful when you subclass a class that is not in your control. It might be safer to use composition that inheritance in such situations. It is also equally important to remember that if you create a non-final class with public methods, please design it carefuly to ensure that it does not break a subclass that may extend from it. If there are any caveats, be sure to document them clearly.

    Note: This text was originally posted on my earlier blog at
    Here are the comments from the original post

    AUTHOR: Sanket Daru
    DATE: 10/20/2007 11:40:37 AM
    This was a serious eye opener.

    Learnt a very good OOP lesson.

    Saturday, September 29, 2007

    Inheritance and composition

    • Inheritance is used for
      • Code resuse
      • To support polymorphism
    • Disadvantages of inheritance
      • Difficult to change the interaface of the subclass
      • Superclass is always instantiated
      • Can get complex and unmanageable
    • Composition is used for code reuse
    • Disadvantages of composition
      • We cannot use polymorphism
      • We cannot extend the system by adding subclasses
      • May have a slight performance overhead
    • Usage
      • Inheritance: IS- A
      • Composition: HAS - A

    Example 1:

    public class Car {
      private Engine engine;
      public void start() {}
      public void stop() {}

    public class SUV extends Car{
      public void start() {} //overrides the start method from Car

      public void fourByFourMode() {}

    Example 2:
    public void someMethod() {
      Car c = new SUV();

    Example 3:
    public class Car {
      private Engine engine;
      public void start() {
        //maybe do something more

      public void stop() {}

    I will end this post with the first paragraph from Item 17, of Joshua Bloch's excellent book, Effective Java. In the book this paragraph is followed by a code example that explains this very well, however, I am not sure if I can include the example under fair use. Crying..

    Inheritance is a powerful way to achieve code reuse, but it is not always the best tool for
    the job. Used inappropriately, it leads to fragile software. It is safe to use inheritance within
    a package, where the subclass and the superclass implementation are under the control of the
    same programmers. It is also safe to use inheritance when extending classes specifically
    designed and documented for extension (Item 15). Inheriting from ordinary concrete classes
    across package boundaries, however, is dangerous. As a reminder, this book uses the word
    “inheritance” to mean implementation inheritance (when one class extends another).
    The problems discussed in this item do not apply to interface inheritance (when a class
    implements an interface or where one interface extends another).

    Can you think of a situation where subclassing an existing class can break the semantics of your code, because of a certain undocumented feature of the superclass? Let me give you a hint. Assume a collection class has 2 methods

    add(Object o) - to add the specified object to the collection

    addAll(Collection c) - to add each element of the specified Collection to this collection.

    Now assume that addAll(Collection c) internally invokes add(Object o) for every object in the collection.

    Can you think of a situation that will result in a bug, if we subclass this class and override the above methods to add a functionality that keeps track of how many elements have been added to the collection?


    1. Compostion vs. Inheritance
    2. Composition and interfaces

    Note: This text was originally posted on my earlier blog at

    AUTHOR: Josh Bloch
    DATE: 09/29/2007 10:22:58 PM
    Yes, you can include the example under fair use:)

    AUTHOR: Parag
    DATE: 10/02/2007 09:17:55 AM
    Thanks a lot Josh. I will include the example in the next post.


    Friday, September 21, 2007

    High cohesion

    [Time: 4 mins]

    • Stuff that goes together, stays together
    • Easy to discover relevant code
    • Levels of cohesion
      • packages
      • classes
      • methods
    So in very simple words, cohesion is keeping related stuff together so we can find what we want without too much difficulty.

    Example 1:

    public class Student {

    //cohesive methods

    public void registerForCourse() {}

    public void deregisterFromCourse() {}

    viewTranscripts() {}

    //methods below are not in synch with the responsibilities of the Student class

    //hence cohesion is broken

    submit grades() {}

    submitCourseSchedule() {}




    Note: This text was originally posted on my earlier blog at

    Loose coupling

    [Time: 4:32 mins]

    Loose (or low) coupling means (in a generic sense) that an entity can interact with another entity without being concerned with the internal implementation, and through a stable interface. Low coupling is implemented by using principles of information hiding. When two entities are loosely coupled, internal changes in one of them do not affect the other. The calling method is coupled to the called method and not it's implementation. Since we have already discussed encapsulation and information hiding in detail, I will not repeat it here.

    • Loose coupling is achieved with information hiding
    • And by programming to the interface rather than the implementation

    Example 1: Tightly coupled system

    public void aMethod() {

    ArrayList myList = new ArrayList();



    private void doSomethingWithList(ArrayList list) {


    Example 2: Loosely coupled system

    public void aMethod() {

    myList = new ArrayList();



    private void doSomethingWithList(List list) {


    • Loose coupling contains the scope of change when an implementation is modified

    Note: This text was originally posted on my earlier blog at

    Saturday, September 15, 2007

    Don't repeat yourself

    The code says everything once and only once, which is the essence of good design. -- Martin Fowler

    [Time: 4:44 mins]

    • Repititive code makes maintainance more difficult
      • There are more places to change
      • We may forget to change some of them
      • Increases probability of bugs
    • Types of repitition
      • In methods in a class
      • Accross the entire software

    Example 1: DRY violated
    public class Account {
    public void transferFunds(double amt, Account dest) {
    //transfer funds
    //generate email... create connection
    //create message
    //dispatch email

    public void delete() {
    //delete account
    //generate email... create connection
    //create message
    //dispatch email
    Example 2: DRY honoured
    public class Account {
    public void transferFunds(double amt, Account dest) {
    //transfer funds

    public void delete() {
    //delete account

    public dispatchEmail() {
    //generate email... create connection
    //create message
    //dispatch email


    2. Don't repeat yourself
    3. Once and only once
    4. Code harvesting

    Note: This text was originally posted on my earlier blog at

    Wednesday, September 12, 2007

    Keep it simple

    [Time: 5:37 mins]

    One should not increase, beyond what is necassary, the number of entities required to explain anything - Occams Razor

    • KISS helps keep software manageable
    • The UNIX kernel is an example of a functionally complex software implemented in simple design
    • Intentional complexity
      • Enthusiasm to use design patterns
      • Enthusiasm to make a system uber flexible
      • Feature bloat
    • Unintentional complexity
      • Maintainance quick fixes
      • Laziness in refactoring

    Note: This text was originally posted on my earlier blog at

    Sunday, September 09, 2007

    Software design principles

    Over the next few posts, I will cover some basic software design principles. There are some well known software design principles that serve as guideposts for us in the design process. But here is something to always keep in mind while using design principles to guide us in our design.

    While principles, patterns, heuristics, and guidelines offer valuable advice about how to do things the right way, they don't serve as substitution for thinking on our own. Unfortunately, I think we all too often let these principles, etc. do the thinking for us.

    -- Kirk Knoernschild

    The audiio snippet below is a very simple and brief introduction to software design. Please click on the start arrow to begin the audio. Stay tuned for more on software design in the next few posts posts...

    [Time: 2:20 mins]

    Note: This text was originally posted on my earlier blog at

    Wednesday, September 05, 2007

    A student's perspective on Java

    From some time I have been very keen to publish a post that describes a student's perspective on Java. Over the years Java has gone from a simple easy to learn language to quite a huge beast. The volume of things one has to learn and keep up in Java poses a special challenge to students who wih to learn the language.

    I would like to post experiences of how various students coped with the challenge of learning Java.

    In this post, Sanket Daru, a student in one of my Java classes at SCIT describes his experience with Java. I am particularly glad to post Sanket's thoughts, since he is one of the brightest and most enthusiastic students, that I have had the pleasure of teaching.

    Q. How did you go about learning Java?

    A. It all began in 2003 during my graduation. We had Java in our curriculum. I attended the Java faculty’s first and second lecture and knew that “maybe he is a genius, but he knows nothing about the heads or tails of teaching.” Convinced and determined never to attend his class again, I went straight to the book-shop, opposite to my college, and grabbed a copy of “Java 2 the Complete Reference” by Herbert Schildt.

    I spent the rest of the semester studying the entire book cover-to-cover not to mention, spending nights at stretch working hard to get my hands-on right and accurate. I used to do a lot of stupid things with Java, by creating dumb applications, but all that gave me good experience and insight into the Java language, its working and above all made me confident that I can develop applications using Java.

    After this, we got a really nice faculty for advanced Java and that faculty provided me the much needed guidance that I missed during the days I started programming in Java.

    Q. What parts did you have a hard time understanding and how you overcame the difficulties?

    A. Collection classes took some time and effort to be understood… I kept on using different collection classes in my dumb applications thereby figuring out each one’s unique working. It’s only through trial and error that one can get the basics straight. For advanced understanding, referring to books and the internet is the best way to progress.

    Also, using advanced frameworks presented its unique challenges to me and till date I am facing some or the other difficulties using some or the other new feature of Java. Today, I rely on the WWW for guidance. I refer to a lot of material that’s available online whenever I hit a road-block. If all fails, I post to the group to get answers from someone who has been there and done that. It helps, the community based learning!

    Till date, multi-threading is something that sends shivers down my spine! I know the basics and have done quite a good work on it but still I am never sure that my multi-threaded application will give me the desired result or not!

    Q. What are the most common mistakes that students often make?

    A. The biggest mistake that I have seen amongst my peers, is that they just read a really good book on Java (or any language for that matter) but never voluntarily venture out to get their hands-on correct. Bookish knowledge gets them the much needed marks/grades but makes them dumb programmers. They know about all the various “fancy” features the language has to offer without knowing even how to get the very “basics” working!

    People who do venture out to get their hands-on correct, get easily dis-heartened when they hit a road-block. One must remember that failures are stepping stones to success and that as long as you don’t fall, you will never know how higher you can go. The internet is rich with resources and everything is served on a platter these days by Google.

    Q. Anything else that you think may help the students?

    A. Always remember that you need a good guide (a teacher) who can help you get your basics straight but if you don’t get one, don’t worry. Be your own guide and venture out into the world of Java on your own. It isn’t that scary. It’s very important to remember that you will learn Java if-and-only-if you venture out into Java world on your own. Hitting road-blocks is a boon, it only helps you in knowing a lot more, and things that you never knew exist are uncovered only when you hit a road-block.

    Note: This text was originally posted on my earlier blog at
    Here are the comments from the original post

    AUTHOR: Tarun Chandel
    DATE: 09/05/2007 01:08:33 PM
    Sanket has given some really good points and his experience on learning Java can be applied to most of the things in life, whether it's technology or any other thing. The one point I really like is that never let a bad teacher affect your enthusiasm for learning.

    I think very few lucky people get really good teachers. I am one of those lucky few to have you as a teacher. On the teacher's day I would like to thank you for making a difference in my and many other's life just by being there in front of the class.

    Wishing you a very happy Teacher's Day!
    AUTHOR: Parag
    DATE: 09/06/2007 09:04:19 AM
    Hi Tarun,

    Thank you for the kind words and good wishes.

    Good luck for everything :-)


    Monday, September 03, 2007

    Compiling Java source files with supplementary characters

    Java source files can also contain supplementary characters as strings as well as identifiers if the character is a string or a digit.

    Here is a video that shows how we can compile Java source files that contain supplementary characters as Strings. Click on the image to download the video.



    Note: This text was originally posted on my earlier blog at

    Thursday, August 30, 2007

    Changes in Java to support supplementary Unicode characters

    Support for supplementary characters might need changes in the Java language as well as the API. A few questions come to mind.

    • How do we support supplementary characters at the primitive level (char is only 16 bits)?
    • How do we support supplementary characters in low level API's (such as the static methods of the Character class) ?
    • How do we support supplementary characters in high level API's that deal with character sequences?
    • How do we support supplementary characters in Java literals?
    • How do we support supplementary characters in Java source files?

    The expert commitee that worked on JSR-204 dealt with all these questions and many more (I'm sure) . After deliberating as well as experimenting with how the changes would affect code, they came up with the following solution.

    The primitive char was left unchanged. It is still 16 bits and no other type has been added to the Java language to support the supplementary range of unicode characters.

     Low level API's, such as static methods of the Character class, accepted the char primitive type before support for supplementary characters was provided in Java. However, since Java 5.0, methods such as isLetter(...) of the Character class provide an overloaded method that accepts an int representing the code point, along with the earlier method that accepted a char.



    High level API's will continue to work "as is" for most developers. They represent character sequences as UTF-16 sequences. Some methods in String and StringBuffer now have parrallel methods to work with code points. Some such methods are codePointAt(...) , codePointBefore(...), and codePointCount(). For example the codePointCount() method returns the number of code points in a String, which may not be the same as the number of characters in the String, if some characters are from the supplementary range and are represented as surrogate pairs.




    Identifiers in Java can contain any letter or digit. Many supplementary characters are letters or digits. To allow supplementary characters to be used in identifiers, the Java compiler and other tools were modified to use different API methods (isJavaIdentifierPart(int), isJavaIdentifierStart(int)).

    Since we need to support supplementary characters all the way, they also need to be supported in Java source files. I will discuss how to include unicode characters in Java source files and get them to compile using the Java compilers -encode option, in the next blog post.

    While I was reading about encoding, I came accross this interesting blog post that describes a situation when an I18N enables Java program ceased to work after the build machine was moved from a Windows box to a Red Hat box. The reason of course was encoding related issues.


    Note: This text was originally posted on my earlier blog at

    Friday, August 17, 2007

    It's been a while since I posted

    It's been a week since I posted last. I am really sorry, this is the second time in succession that I have missed my target of posting at least thrice a week. By way of an excuse, all I have is a lame "it's been a bit crazy at work". I am messing around with a lot of client side technologies, like AJAX and the plethora of libraries that accompany it, and all this without really understanding Javascript well enough.

    One of the libraries I am checking out is DWR (Direct Web Remoting) . It allows Javascript code to invoke Java objects. All this is done by creating proxy objects in Javascript that make AJAX calls to the DWR Servlet, which in turn invokes the Java objects. I personally think, it's a very nice concept, and it also supports reverse AJAX.

    Would you like to know more about DWR? Please comment and let me know. I will then post a series on DWR after completing the current one on Unicode characters.


    On a total tangent, here's a little something from Doc Searls on writing to inform readers


    I don’t think of my what I do here as production of “information” that others “consume”. Nor do I think of it as “one-to-many” or “many-to-many”. I thnk of it as writing that will hopefully inform readers.


    Informing is not the same as “delivering information”. Inform is derived from the verb to form. When you inform me, you form me. You enlarge that which makes me most human: what I know. I am, to some degree, authored by you.

      What we call “authority” is the right we give others to author us, to enlarge us.
      The human need to increase what we know, and to help each other do the same, is what the Net at its best is all about. Yeah, it’s about other things. But it needs to be respected as an accessory to our humanity. And terms like “social media”, forgive me, don’t do that. (At least not for me.


    Note: This text was originally posted on my earlier blog at
    Here are the comments from the original post

    AUTHOR: kishore hariharan
    DATE: 08/29/2007 05:33:38 AM
    hi prof,
    this concerns the simple yet powerful concept of DWR. My current assignment involves working and exploring the same. I and two of my colleauges actually implemented server side push concept using DWR, as the client demanded real time updates for his Stock Trading Application.
    The POC took a while but we managed to finish the implementation with support from JMS.
    There are still a few grey areas on using this:
    - like the number of live connections DWR can handle at an instance.
    -How does DWR actually manage to keep the connections alive is still a mystery. The best we figured was that it sent some heartbeats at frequent intervals. Still not very clear on this.
    -Can it really manage to bypass poweful firewalls.
    These are a few of the questions we are still researching on. The implementation at the moment works great but still awaits the real test of volume testing.

    AUTHOR: Parag
    DATE: 08/30/2007 10:57:23 AM

    These are interesting topics you are researching. I am sure your findings will be of interest to many people.

    Do post them to our forum.


    Friday, August 10, 2007

    Supplemantary character support in Java

    In the last post I wrote that supplementary characters in the Unicode standard are in the range above U+FFFF, which means they need more than 16 bits to represent them. Since the char primitive type in Java is a 16 bit character, we will have to use 2 char's for them.

    I just finished reading some stuff on supplementary character support in Java, and well, there are parts I understood right away and parts that are going to need further reading. I will try to share what I am learning on this blog. However, let us first clarify some terminology.

    Character: Is an abstract minimal unit of text. It doesn't have a fixed shape (that would be a glyph), and it doesn't have a value. "A" is a character, and so is "€", the symbol for the common currency of Germany, France, and numerous other European countries.

    Character Set: Is a collection of characters.

    Unicode is a coded character set that assigns a unique number to every character defined in the Unicode standard.

    A Code Point is the unique number assigned to every Unicode character. Valid Unicode code points are in the range of U+0000 to U+10FFFF. This range is capable of holding more than a million characters, out of which 96,382 have been assigned by the Unicode 4.0 standard.

    Supplementary characters are those characters that have been assigned code points beyond U+FFFF. So essentially they lie in the range of U+10000 - U+10FFFF.

    When these characters are to be stored in a computer system, they have to be stored as a sequence of bits (this is known as UTF-32 encoding). The simplest way store them is to store each character as a 4 byte sequence capable to addressing the entire unicode range. However this will waste a lot of space, because most of the time we deal with characters in the ASCII range of 00 - FF. Some other mechanism is needed to make better use of the computer's memory and storage. Other encodings that exist are UTF-8 and UTF-16, which as their names suggest, use 8-bit and 16-bit sequences.

    A natural question that must have occurred to you is, how do we store characters that go beyond 8 bits or 16 bits in UTF-8 and UTF-16. This is made possible by using multiple blocks. Each block will also have to indicate whether it represents a single character or is part of a series of blocks that represent one character. UTF-8 and UTF-16 help us store characters using less space than UTF-32. The most widely used encoding standard is UTF-8.

    In the next post I will discuss how Java supports the supplementary range in it's API's and in the Virtual Machine.

    Note: This text was originally posted on my earlier blog at

    Wednesday, August 01, 2007

    Catching up with Java 5

    Java 5 (a.k.a Tiger) has been around from a while. But there are still many developer's (including myself) who do not know about and use all it's features.

    So, in an effort to educate myself and help others, I have decided to spend some time everyday reading Java 1.5 Tiger A Developer's Notebook, and share my findings with others on this blog.

    Something I found out today (I know this should have happened long back, but such is the profession of programming :-) ), is that since Java 1.5 there is support for Unicode 4 which supports a supplemantary character set, that goes beyond 16 bits. An interesting implication is that a the char data type may no longer be able to hold all characters, because those in the supplementary range can now take upto 21 bits.

    This means that a string that contains certain characters may have to encode them as 2 char data types. Such a pair of characters that represents one codepoint is known as a surrogate pair. Now a string with n codepoints may no longer be n characters long, because some code points will be encoded using one character, while some will use a surrogate pair.

    A few questions have come to my mind about parsing such strings. How do I determine which codepoint appears in the middle of the String?

    I came across this article that explains support for unicode 4 in Java. I will read it and share any interesting findings on this blog.

    Meanwhile for a more general explanation of unicode, I strongly recommend this excellent article by Joel Spolsky: The absolute minimum every software developer absolutely, positively must know about unicode and character sets (no excuses!)

    • Discuss this post in the learning forum.
    • Check out my learning journal. I am learning JSF at the moment. Do you want to join an experiment in forming an adhoc virtual study group?
    Note: This text was originally posted on my earlier blog at
    Here are the comments from the original post

    AUTHOR: Manjari
    DATE: 08/17/2007 05:33:37 AM
    Thanks for the link to Joel's article on Unicode. I discovered I was blissfully ignorant in that context.
    AUTHOR: Parag
    DATE: 08/18/2007 06:31:12 PM
    You are very welcome Manjari, and thanks for the comment :-)


    Tuesday, July 31, 2007

    Java reference types - an example and questions

    Dr. Heinz Kabutz has an excellent example for Soft, Weak, and Phantom references in one of his newsletters. You can view it here.

    I also created mind maps for the Java garbage collector and Java reference types. You can download the images by clicking on the links below:

    1. Java garbage collector
    2. Reference types in Java 


    Before concluding the series on Reference types in Java, here are some simple questions for you to test your knowledge.

    Q1. Consider the following code:

    String s = new String("abc");
    SoftReference sf = new SoftReference(s); 

    What is the reference type (strong or soft) for "abc" ?

    Q2. What is the main difference between phantom  references and the other (soft and weak) two references?

    Q3. Consider the following code:

    SoftReference sf = new SoftReference("abc"); 
    WeakReference wr = new WeakReference("123"); 

    Which of the two strings will be garbage collected first, when the JVM needs memory?


    Note: This text was originally posted on my earlier blog at

    Sunday, July 29, 2007

    Reference queue

    The garbage collector puts Reference objects in the ReferenceQueue after their referents have been reclaimed (Phantom references are an exception, because they continue to retain a link to their referents even after they are placed on teh ReferenceQueue).

    In most cases when Soft and Weak references are used, we do not care to monitor the ReferenceQueue. However, in case of PhantomReferences, we do want to monitor the ReferenceQueue, because they are used when we wish to do some cleanup activities when the reference is reclaimed. In such cases, a thread which monitors the ReferenceQueue to find out which objects have been reclaimed will be effective. The WeakHashMap class in the JDK however, follows a slightly different strategy as explained here.

    While Soft and Weak references can be created without being associated with a ReferenceQueue, Phantom references must always be associated with a ReferenceQueue.

    The java.lang.ref.ReferenceQueue class gives us three methods to interact with it:

    • poll – Lets us poll the ReferenceQueue to find out if a reference object has been inserted in it.

    • remove – Returns the next object inserted in the reference queue. This is a blocking call, which means that if an object is not available, the method waits until one becomes available.

    • remove(timeout) – Similar to remove, but if an object is not available, it will block only till the timeout. If a reference object is not available to return, them it returns null.

    Note: This text was originally posted on my earlier blog at

    Wednesday, July 25, 2007

    Phantom references

    Phantom references are the weakest of the three reference types. There is however a significant difference between Phantom references and the other reference types. Objects that are referenced by phantom references are put on the reference queue before the memory occupied by their referents is reclaimed, while soft and weak references are enqueued after the memory occupied by their referent is reclaimed.

    Another important difference in the words of Ethan Nicholas is;

    "A phantom reference is quite different than either SoftReference or WeakReference. Its grip on its object is so tenuous that you can't even retrieve the object -- its get() method always returns null. The only use for such a reference is keeping track of when it gets enqueued into a ReferenceQueue, as at that point you know the object to which it pointed is dead. How is that different from WeakReference, though?"

    So what good are Phantom References? Well according to the documentation:

    Phantom references are most often used for scheduling pre-mortem cleanup actions in a more flexible way than is possible with the Java finalization mechanism.

    Now how useful are these? If you have ever used Phantom references, do write about your experience in the comments section.

    • Discuss this post in the learning forum.
    • Check out my learning journal. I am learning JSF at the moment. Do you want to join an experiment in forming an adhoc virtual study group?

    Note: This text was originally posted on my earlier blog at

    Monday, July 23, 2007

    I am 80% addicted to blogging :-

    80%How Addicted to Blogging Are You?

    Free Online Dating from Mingle2

    Note: This text was originally posted on my earlier blog at

    Friday, July 20, 2007

    Weak references

    A weak reference is similar to a soft reference, except that objects that are weakly reachable will be garbage collected before objects that are softly reachable. When the JVM needs memory, it will first reclaim all unused objects, if the reclaimed memory is still not sufficient, then all weakly referenced objects will will be garbage collected, and if it needs even more memory, then it will reclaim memory from softly referenced objects.


    WeakReference wr = new WeakReference(new String(“abc”));




    ReferenceQueue rq = new ReferenceQueue();

    WeakReference wr = new WeakReference(new PhantomReference(new String(“abc”), queue));




    String s = new String(“abc”);

    ReferenceQueue queue = new ReferenceQueue();

    WeakReference wr = new WeakReference(s);

    PhantomReference pr = new PhantomReference(s, queue);

    s = null;



    All of the above are examples of weak references. In the above example we see two new concepts; phantom reference, and reference queue. More about them in the next section.

    Note: This text was originally posted on my earlier blog at

    Sunday, July 15, 2007

    Soft references

    If an object is not referenced by by a strong reference and there is at least one link to that object with a soft reference, then the object is a softly referenced object. Java provides us a class, which is a subclass of java.lang.ref.Reference, called SoftReference. Soft references are created by encapsulating the object which we want to refer, inside a SoftReference object. Some examples of soft references are shown below.

    SoftReference sf = new SoftReference(new String(“abc”));


    SoftReference sf = new SoftReference(new WeakReference(new String(“abc”)));

    String s = new String(“abc”);

    SoftReference sf = new SoftReference(s);

    WeakReference wr = new WeakReference(s);

    s = null;

    In these examples we see another type of reference called a weak reference. The next section talks about weak references.

    Note: This text was originally posted on my earlier blog at

    Tuesday, July 10, 2007

    New series - reference types in Java

    Starting this week, I will post a series of blogs on "Reference Types In Java". So here goes...

    Since version 1.2, Java supports references other than the commonly used strong reference. An object is said to be strongly referenced, when at least one path to the object from the root set of references contains a strong reference. A strong reference is the traditional type of reference which is created by the = operator. The garbage collector considers a strongly referenced object to be in use and will not reclaim it.

    This statement creates a strong reference.

    String s = new String("abc"); 

    The String object holding the value “abc” is strongly referenced because the variable 's' directly refers to it. Java 1.2 supports three more types of references; SoftReference, WeakReference, and PhantomReference. Whenever we want an object to be softly, weakly, or phantomly referenced, we do not directly reference the object using an '=' operator. We instead reference the object through another object. This object is a reference object and encapsulates a reference.

    SoftReference sf = new SoftReference(new String(“abc”));

    he String object “abc” is not strongly referenced because the only path to it is through a Reference object. The String object “abc” will remain live as long as there is sufficient memory in the JVM. But if the garbage collector has finished reclaiming all unused objects, and the program demands more memory, then “abc” will be reclaimed. What happens if we change the code to add a strong reference to the object as well?

    String s = new String(“abc”);

    SoftReference sf = new SoftReference(s);

    Now, is the String object “abc” softly referenced, or is it strongly referenced? It is strongly referenced because there is a path from the root set of references to the String object, which has a strong reference. The variable s has a strong reference to the String object. The garbage collector will not reclaim the object because there is a strong reference to it.

    The Reference object shown in the above diagram, is really an abstract superclass for different types of reference objects in Java; soft references, weak references, and phantom references. Each type denotes the strength of reachability to an object. Before we proceed, remember, the reference type of an object is the weakest type in the strongest link.

    The next few posts will discuss different reference types in more detail.

    • Discuss this post in the learning forum.

    • Check out my learning journal. I am learning JSF at the moment. Do you want to join an experiment in forming an ad hoc virtual study group?

    Note: This text was originally posted on my earlier blog at
    Here are the comments from the original post

    AUTHOR: Sanket Daru
    DATE: 07/16/2007 05:02:18 AM
    Dear Sir,
    In this series, you are taking us through the references, weak, strong, etc... But I have a question...

    Why will I explicitly want my references to be weak or soft??? Can you please guide us through one real life scenario where these references come into use???

    I remember one which you discussed in class about loading registry entries in memory which might end up taking a lot of space and hence it is wiser to make it weak referenced... But still, in day-to-day usage, can you provide some good examples???

    Also, I will like to ask, will it not be beautiful if Java (JVM) will do this work of assigning weak-soft-strong references for us??? The garbage collection series pointed out when and how JVM reclaims the memory, but wouldn't it be nice if JVM also assigned specific reference types on its own during compile or run time as needed??? Just a random thought... Please guide...

    Thank You.

    Sanket Daru.
    AUTHOR: Parag
    DATE: 07/16/2007 09:09:10 AM
    Hi Sanket,

    I have answered your question on the newsgroup.

    Tuesday, July 03, 2007

    A process for teaching a peer taught online course

    Sometime back I wrote a blog on the motivation for conducting online, peer taught courses, and the kind of infrastructure such a course would need.

    Once we have the basic infrastructure in place, it may be useful to define a simple process or a set of guidelines for students as well as mentors to help them as they proceed with the course.

    It is very important to explain the learning methodology and it's benefits to the students and mentors. The students must understand right at the beginning that learning that is spoon fed is the most ineffective way of learning. The core process that they are to follow is learning by doing, and participating with other students, mentors, and practitioners. Traditional lectures would also be needed, but their purpose should be to introduce students to the topics and show them how to build on the knowledge by practicing and participating. The mentors should interact with the students through lectures, online groups, and blogs. The participation will primarily be to help them clarify doubts and to give them direction, and next steps.

    The mentors must also understand that their role is to facilitate learning and not just lecturing. Students need help with next steps, and the faculty must help them by directing to the next task, or next learning item, so that they can discover and construct knowledge themselves. As the students proceed they will have a lot of doubts. The mentors must also help students by solving their doubts. The entire course should be structured as an ongoing conversation that leads to learning and greater clarity. The students must learn by enculturation. They must be encouraged to learn to be software developers rather than learn about software development. This will happen best if the entire focus of the course is programming and participation.

    Students can be graded for their knowledge and participation. Grades can be given for project work, and participation (by posting questions, answers, and blog entries), and a theory paper. A possible breakdown for grading can be 40% for projects, 20% for participation, and 40% for theory. Grading for participation and the project should be given on an ongoing basis. So completing work in a timely manner and participating frequently will earn more grades than completing all the assignments in the last week.

    To support this process, each student will have to have a blog which they will utilize as a learning journal to report their learning, their perspectives, and project progress. The course will also have a class blog where the mentors will publish slides, links to resources, and keep students on the same page. The students will also have access to a newsgroup where they can ask and answer questions. Often it may be possible to supplement the material with screencasts and podcasts prepared by the faculty.

    It would help if the course begins with the faculty explaining competencies that the students are expected to gain in the duration of the course, along with the grading scheme, and various forms of collaboration available to the students. All of these details may also be listed on the class blog (or a Moodle course page) which is open to all the students for viewing and commenting.

    A list of projects can be published at the begining of the course. The projects may be implemented in a language of the students choice. Each project can be broken down into small milestones, such that each milestone can be completed in a week or two. Each platform language/platform can have a panel of mentors for supporting the students learning and interactions.

    It is also possible to define a simple process for teaching and assisting with the interactions and practice. Let's discuss that in the next post.

    Note: This text was originally posted on my earlier blog at
    Here are the comments from the original post

    AUTHOR: Harshal
    DATE: 07/05/2007 07:45:03 AM
    Hey Parag, Very interesting concept. Let us discuss more in this in the bar camp at persistent if you are planning to visit.


    A process for teaching a peer taught, online course - contd

    Once all the grading and other process details are explained to the students, the faculty starts by explaining the first topic in a kickstart fashion and giving a set of resources to the students for further understanding. So, for example, if the topic is “Input/Output in Java”, the faculty will explain the basic architecture of the IO library, they will demonstrate a simple program that reads input from a console and writes to the console. The lecture ends with an introduction of the full capabilities of the library and a list of resources which the students must study to further their understanding. If possible a topic may also be linked to a project milestone. The students will then proceed with their learning by reading the link or maybe viewing screencasts, or listening to podcasts. They should write their learning and perspectives on their blog, and ask doubts on he newsgroup. The mentors will follow the students blogs and help them with their understanding by commenting on the blogs and will help the students further, by answering their questions on the newsgroup. Helping by answering and commenting need not be restricted to mentors. Other students in the class are also encouraged to comment on their classmates blogs and answer their questions. The students also start work on the project from the first week, reporting the progress on their blogs. One member of the group will act as a project leader for each milestone, such that there is a new leader for each milestone. The leader must report progress made on that milestone, problems faced, and how the members are trying to overcome the problems. The mentor may also schedule a classroom or an on line session to have discussions with students and to solve their doubts.

    Each group will be given a CVS account for the project. All project work should be committed to CVS regularly. Mentors will also have access to these projects and can check out the code that students are working on.

    The above process goes on week after week, with the mentor introducing new topics each week, and the students proceeding with studying, working on projects, and participating.

    We should also try and involve industry mentors who will help the students by giving them direction on their projects and also help them with concepts. They can provide their mentoring entirely on the net. These industry mentors should ideally spend an hour, for two days in a week to read the project progress blog of the team they are helping and give them direction. At most they will have to dedicate two hours per week for their mentoring tasks.

    In the duration of the course, the students will learn from lectures, they will also learn by studying from resources given to them by the mentors, by reflecting on what they have studied and blogging about it, and by participating in (online as well as offline) discussions with their friends and mentors. Most importantly they will learn by doing, by working on the projects as software developers.

    Some precautions:

    However, since this methodology is new, it is important that we take continuous feedback from students as well as mentors in the initial stages, so we can fine tune the process wherever needed.

    It is also very important that students abandon the desire to be spoon fed. It is imperative that they take the initiative to learn and participate.

    It may happen that the mentors who had initially volunteered to help students may not be able to dedicate time, due to work pressure or other reasons. From our end, we must make it as easy as possible for the mentors. By allowing them to participate online, we have already eliminated the overhead of traveling. It might also help if each panel has an internal faculty or a regular visiting faculty who can coordinate with the mentors if such issues arise.


    The above methodology and process will enable a much better learning experience for the students. Since much of the interaction is online, we will also be able to attract skilled mentors from the industry, especially senior developers who may not have the time to come to campus to take a class.

    The students will learn real world practices that are adopted by the industry, and they will also be able to use their blog as an extension of their resume.