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;
	}
}

Trackback URI | Comments RSS

Leave a Reply