Feb 27 2008

Making References unusable

Posted in Java on Wednesday, February 27, 2008 at 15:10

An interesting problem at theserverside.com

If I can comprehend the issue -
You have two or more handles to same object and you want to enforce that no references should use the object, if it was “flushed” by any of the reference during execution.

Proposed Solution
For the given object implement destroy() that will update member variables marking them unusable for next set of execution. We can set some of them to null or introduce a flag that will represent status of the object. Now, the status code will decide, if a method should be executed or a reference should be set to null.

Here is example code…

import java.util.List;
import java.util.ArrayList;

public class TestDestroy
{
	public static void main(String ar[])
	{
		TestObj obj1 = new TestObj(100,true);
		TestObj obj2 = obj1;

		TestObj obj3 = new TestObj(200,true);

		List<TestObj> testObjs = new ArrayList<TestObj>();
		testObjs.add(obj1);
		testObjs.add(obj2);
		testObjs.add(obj3);

		// before destroy
		System.out.println("before destroy...");
		System.out.println("obj1 = "+obj1);
		System.out.println("obj2 = "+obj2);
		for(int i=0;i<testObjs.size();i++)
		{
			TestObj obj = (TestObj)testObjs.get(i);
			System.out.println("obj<"+i+"> = "+obj);
		}

		// destroying obj1
		obj1.destroy();

		// after destroy
		System.out.println("after destroy...");
		System.out.println("obj1 = "+obj1);
		System.out.println("obj2 = "+obj2);
		for(int i=0;i<testObjs.size();i++)
		{
			TestObj obj = (TestObj)testObjs.get(i);
			System.out.println("obj<"+i+"> = "+obj);
		}
	}
}

class TestObj
{
	private int i = -1;
	private boolean isLive = false;

	public TestObj(int i, boolean isLive)
	{
		this.i = i;
		this.isLive = isLive;
	}

	public void destroy()
	{
		this.i = -1;
		this.isLive = false;
	}

	public String toString()
	{
		if(this.isLive)
			return "[ i="+this.i+", isLive="+this.isLive+"]";
		else
			return null;
	}
}

This example may look trivial but we can extend the same idea to implement other methods in given object. For example, we have display() that formats the object data with HTML tags so it can be displayed in any HTML browser. So, our code would look like…

public String display()
{
	if(!this.isLive)
	{
		throw new NullPointerException("Object is set to null by other reference");
	}
	else
	{
		String html = null;

		// code to convert object into HTML representation

		return html;
	}
}

No responses yet

Feb 16 2008

Is Java re-inventing the WHEEL?

Posted in Java on Saturday, February 16, 2008 at 7:21

I was browsing the internet for some information and I stumbled upon this beautiful quote @ http://horstmann.com/

1980: C

printf("%10.2f", x);

1988: C++

cout << setw(10) << setprecision(2) << showpoint << x;

1996: Java

java.text.NumberFormat formatter = java.text.NumberFormat.getNumberInstance();
formatter.setMinimumFractionDigits(2);
formatter.setMaximumFractionDigits(2);
String s = formatter.format(x);
for (int i = s.length(); i < 10; i++)
	System.out.print(’ ‘);
System.out.print(s);

2004: Java

System.out.printf("%10.2f", x);

Now, what does that mean? Isn’t it look like re-inventing the printf?

No responses yet

Feb 13 2008

StringBuffer vs. StringBuilder

Posted in Java on Wednesday, February 13, 2008 at 12:57

Can you predict the output of following snippet:

public class StringTest
{
	public static void main(String ar[])
	{
		StringBuffer sb1 = new StringBuffer(”neo”);
		StringBuffer sb2 = new StringBuffer(”neo”);
		StringBuilder sbld1 = new StringBuilder(”neo”);
		StringBuilder sbld2 = new StringBuilder(”neo”);
		String str = new String(”neo”); 		

		if(sb1.equals(sb2))
			System.out.println(”Both StringBuffers are Equal”);
		else
			System.out.println(”Both StringBuffers are not Equal”);

		if(sbld1.equals(sbld2))
			System.out.println(”Both StringBuilders are Equal”);
		else
			System.out.println(”Both StringBuilders are not Equal”);

		if(str.equals(sb1))
			System.out.println(”String and StringBuffer are Equal”);
		else
			System.out.println(”String and StringBuffer are not Equal”);

		if(str.equals(sb1.toString()))
			System.out.println(”Now…String and StringBuffer are Equal”);
		else
			System.out.println(”Now…String and StringBuffer are not Equal”);
	}
}

If you are thinking it should print the message that is part of if block by evaluating equals() to true, you would be surprised to know the results.

Except the last condition, it evaluates all others as false and it will print “… are not Equal”. Now, looking at the results you may be doubting the implementation of equals() in StringBuffer and StringBuilder. Yes, you are thinking in right direction. Neither of them overrides equals() of Object.

To make it work, one needs to invoke toString() on StringBuffer and StringBuilder objects and then use equals() to compare string representation. It is bit clumsy way to check equality of StringBuffer and StringBuilder objects. I really didn’t understand the rationale behind it.

On the different note, the difference between StringBuffer and StringBuilder is that of thread safety. StringBuffer is thread-safe implementation of mutable sequence of characters. Where as, StringBuilder is not thread-safe. Needless to say that it would be a better idea to use StringBuilder instead of StringBuffer in Java application where objects are created locally [in a certain block of code]. For example, I have been using StringBuffer to produce toString() representation of various objects. I can surely make my program run faster by few milliseconds by replacing StringBuffer with StringBuilder objects [provided toString() is being called significant numbers of times].

No responses yet