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 http://www.adaptivelearningonline.net

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 http://www.adaptivelearningonline.net

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 http://www.adaptivelearningonline.net

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 http://www.adaptivelearningonline.net

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 http://www.adaptivelearningonline.net

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 http://www.adaptivelearningonline.net

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 http://www.adaptivelearningonline.net
Here are the comments from the original post

AUTHOR: Sanket Daru
URL: http://sankdadevildaru.blogspot.com
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.
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 http://www.adaptivelearningonline.net
Here are the comments from the original post

AUTHOR: Harshal
URL: http://www.shahharshal.com
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.