Cleanup of non-graphical Java Bean

I'm currently working on a non-graphical javabean that manages serial communications with a piece of our companies electronic hardware. One of the properties of the bean is "connected", and this property governs whether or not the bean has acquired control of the serial port.

The problem I have is that when the bean is deleted it remains connected to the serial port, blocking any other connections. I want to try to clean up properly but how can I do this? As far as I can tell non-graphical beans are given no notification that they have been removed from a page.

Note that I am reluctant to make this bean graphical. I want to reserve the possibility of using it on embedded devices that may not have access to graphical libraries such as awt or swing.

Chris.

[798 byte] By [chris_williamson] at [2007-9-26 7:54:52]
# 1

A bean that is deleted is eventually garbage collected. So, an approach would be to override the finalize() method and put your serial port disconnecton code in that method.

Here is a trivial example:

public class MyBean {

protected void finalize() throws Throwable {

// put your code here to disconnect serial port.

super.finalize();

System.out.println("disposed");

}

public static void main(String[] args){

MyBean di = new MyBean();

di= null;//delete the bean.

System.gc();

}

}

larryhr at 2007-7-1 18:09:06 > top of Java-index,Desktop,Developing for the Desktop...
# 2
It doesn't work in my particular case. The development environment keeps a reference to my bean in order to allow the deletion of my bean to be undone. The reference prevents garbage collection.
chris_williamson at 2007-7-1 18:09:07 > top of Java-index,Desktop,Developing for the Desktop...