Tuesday, July 10, 2007

Garbage Collection (with reference objects)

Part III

The Reference Object application programming interface (API) is new in the Java Development Kit (JDK) 1.2. This API allows a program to maintain special references to objects that allow the program to interact with the garbage collector in limited ways.

  • Unlike ordinary references, the reference in a reference object is treated specially by the garbage collector. A reference object encapsulates a reference to some other object, which is called the referent. The referent of a reference object is specified when the reference object is created.
  • Besides strongly reachable and unreachable objects, the Reference Objects API gives you strengths of object reachability. You can have softly, weakly and phantomly reachable objects and gain a limited amount of interaction with the garbage collector according to the strength of the object's reachability.
When an object is reachable from the root set by some chain of ordinary references (no reference objects involved), that object is said to be strongly reachable.

If, however, the only ways to reach an object involve at least one weak reference object, the object is said to be weakly reachable. An object is considered by the garbage collector to be in use if it is strongly reachable. Weakly reachable objects, like unreachable objects, are eligible for collection.




Fig.1: Adding reference objects to the heap

  • Unreachable objects (outside the strongly and weakly reachable areas) are not reachable from the root set.
  • Strongly reachable objects (inside the strongly reachable area to the lower left) are reachable through at least one path that does not go through a reference object.
  • Weakly reachable objects (inside the weakly reachable area shown enclosed with a dashed line to the upper-right) are not strongly reachable through any path, but reachable through at least one path that goes through a weak reference.

The diagram above shows two paths to the object on the heap with the X. It can be reached through the weak reference, and directly from the stack without going through a weak reference object. The object with the X is strongly reachable and not weakly reachable because one path leads to it from the root set without going through a reference object.

The garbage collection behavior for this object is the same as other strongly reachable objects until it is no longer reachable from the root set, at which time it becomes weakly reachable.

Friday, July 6, 2007

Garbage Collection ( Part II )

Garbage Collection process:

The garbage collector's job is
1)To identify objects that are no longer in use (An object is in use if it can be accessed or reached by the program in its current state)
2) Reclaim the memory.

How to identify the unreachable objects?

An executing Java program consists of a set of threads, each of which is actively executing a set of methods (one having called the next). Each of these methods can have arguments or local variables that are references to objects. These references are said to belong to a root set of references that are immediately accessible to the program. Other references in the root set include static reference variables defined in loaded classes, and references registered through the Java Native Interface (JNI) API.

  • All objects referenced by this root set of references are said to be reachable by the program in its current state and must not be collected. Also, those objects might contain references to still other objects, which are also reachable, and so on.
  • All other objects on the heap are considered unreachable, and all unreachable objects are eligible for garbage collection.
  • If an unreachable object has a finalize () method (means Resurrectable state), arrangements are made for the object's finalizer to be called.
  • Unreachable objects with no finalizers and objects whose finalizers have been called are simply reclaimed during garbage collection.

    Garbage collection algorithms vary, but they all have in common the task of identifying the objects that are reachable from the root set and reclaiming the space occupied by any other objects.

    In the diagram, which is a simplified view of the stack and heap for instructional purposes, objects inside the blue square are reachable from the thread root set, while objects outside the square in red) are not.

Thursday, July 5, 2007

Garbage Collection ( Part I )

Why Objects are called Reachable, Resurrectable, and Unreachable?

Prior to the release of Java 2 Platform, Standard Edition (J2SE) 1.2, an object could be in only one of three states

Reachable: An object is reachable if the garbage collector can trace a path from a root-set variable to that object. When the JVM creates an object, that object stays initially reachable as long as a program maintains at least one reference to the object. Assigning null to an object reference variable reduces the object's references by one. For example:

Employee e = new Employee (); Employee e2 = e; e = null;
In the above code fragment, the Employee object is initially reachable through e.
Then it is reachable through e2 as well as through e. After null assigns to e, the
Object is only reachable through e2.

Resurrectable: An object is resurrectable if it is currently unreachable through root-set variables, but has the potential to be made reachable through a garbage collector call to that object's overridden finalize () method. Because finalize ()'s code can make the object reachable, the garbage collector must retrace all paths from root-set variables in an attempt to locate the object after finalize () returns. If the garbage collector cannot find a path to the object, it makes the object unreachable. If a path does exist, the garbage collector makes the object reachable. If the object is made reachable, the garbage collector will not run it’s finalize () method a second time when no more references to that object exist. Instead, the garbage collector makes that object unreachable

Unreachable: An object is unreachable when no path from root-set variables to that object exists and when the garbage collector cannot call that object's finalize() method. The garbage collector is free to reclaim the object's memory from the heap.

Sunday, July 1, 2007

An Introduction To JSON

It’s a bird; it’s a plane, its JSON

A few months ago, I suddenly came across (actually tripped over) a word flying through the web – JSON. It’s pronounced the way it is written, but for people like me who’re trying to figure out how it is pronounced, its Jason. The name is fancy and friendly enough to catch one’s attention.. something like, “Hey JSON, what’s up today?”
Getting into the matter and keeping things short, JSON stands for JavaScript Object Notation. It’s an extremely simple way to represent objects that contain name-value pairs. Here’s a plain example:

{
“myself”:{
“profile”:[
“name”: “Clark Kent”,
“profession”: “Flying Around”
]
}
}
As of now, all you intelligent readers must have guessed what this thing is actually trying to say. The parent object is myself, which contains a child object profile. Now profile contains a list of keys: name and profession, and their corresponding values.
So, now you must have got an idea as to how a JSON text looks like. Let’s add a little extra to it:
{
“messengers”:{
“yahoo”:[
“username”: “cooldude”,
“password”: “p@$$w0rd”
],
“google”:[
“username”: “cooldude001”,
“password”: “$ecr3t”
]
}
}

The above example shows the parent object messengers containing two children – yahoo and google.


Things to be noted here:

  1. The curly brackets ({}) are the containers and they group together a set of related items.
  2. The square brackets {[]} are the array holders.
  3. Name-value pairs are separated by colons.
  4. All array elements and name-value pairs are separated by commas.

And now you can very well understand what the above JSON structure describes.

But beware! Professional programmers use even more complicated JSON structures for their application; not intending to say that they deliberately make it complicated, just that their complex application requires it. It’s a common practice to have nested JSON structures. Let’s have a look at it:

{“myself”:{“profile”:[“name”: “Clark Kent”,
“profession”: “Flying Around”, “messengers”: {“messengers”:{
“yahoo”:[“username”: “cooldude”,“password”: “p@$$w0rd”],
“google”:[ “username”: “cooldude001”,“password”: “$ecr3t”]}}]
}}

Assuming that you have not fainted yet and are still in your senses, lets try to understand what the above structure represents. Let me make it pretty for you:
{
“myself”:{
“profile”:[
“name”: “Clark Kent”,
“profession”: “Flying Around”,
“messengers”: {
“messengers”:{
“yahoo”:[
“username”: “cooldude”,
“password”: “p@$$w0rd”
],
“google”:[
“username”: “cooldude001”,
“password”: “$ecr3t”
]
}
}
]
}
}

So, now you find that this structure is a combination of the previous two structures. There is an extra key-value pair added to the profile of some Mr. Clark Kent.

Lesson to be learnt: You may not always get a pretty JSON structure :-). The ones sent/received by applications over the internet are generally compacted to save bandwidth usage. So before giving up on a JSON structure, be sure to arrange them properly to get a clear understanding of its meaning.

Ok, so what do I do with Mr. JSON?

There are pretty interesting things that you can do with JSON texts. You can parse them in JavaScript and even use them in AJAX calls.
Let’s see how we can use it in JavaScript. Let’s take the simplest example for a clear understanding. You can then build stuff over it yourself:

var myJSON = {
“messengers”:{
“yahoo”:[
“username”: “cooldude”,
“password”: “p@$$w0rd”
],
“google”:[
“username”: “cooldude001”,
“password”: “$ecr3t”
]
}
};

The above statement declares a JSON object myJSON. Now to access any object inside it, you can simply do a:

var yahooUser = myJSON.messengers[0].username;
var yahooPwd = myJSON.messengers[0].password;

Or, you can use a simple loop to iterate through the values:

for(var z = 0; z<myJSON.messengers.length; z++){
alert(“User: ” + myJSON.messengers[z].username +
“, Password: ” + myJSON.messengers[z].password);
}
This will show all the usernames and passwords in the JSON object in an alert dialog.

JSON with AJAX? Sounds Cool..

AJAX (ah, yet another divine technology) too uses JSON. The idea is to prepare the information in JSON format and send it across through AJAX calls. When received at the client end you just need to convert the JSON text into a JSON object using the friendly neighborhood eval() function.
But there is a catch in this methodology. My friends, who managed to stay awake during the Application Security presentation that I gave a few months ago, would be able to understand it better. There is something called as XSS (Cross Site Scripting). And blindly trying to eval() a received text can become a high security loop-hole. I’ll discuss it in details in some another article.
But as of now, if the JSON object is being received as a text from some external source, then it is highly recommended that JSON parsers should be used:
var myObject = myJSONtext.parseJSON(filter);


The optional parameter, filter, is actually a function that you’ll have to provide. This function will be called for each key-value pair in the JSON text. You might want to use it to alter the values depending on some conditions:


myData = text.parseJSON(
function (key, value) {

return key.indexOf('date') >= 0 ? new Date(value) : value;
});


On one hand where you can convert a string to JSON, you can also have a JSON object converted to string:

var myJSONText = myObject.toJSONString();



Nearly Done

JSON is new technology that is catching up quite fast. Some people say that it is an appropriate replacement for XML. Its quite easy to write and understand extremely easy to use. In XML where you need to load a document, painfully loop through it to extract the values before you can use it; in JSON, you just need the JSON string and eval() it.
All in all, JSON is a technology that is sure to make life easy. Using all the above mentioned information, I am sure that you are now pretty much prepared to face JSON in the real world.. :-)

PS: Please do post any corrections for the article that you might find. Suggestions are always welcome.