Wednesday, October 12, 2005

Why freeing SWT resources follows "the fundamental rules of java"...

From time to time, I see complains like this:
"SWT controls cannot be garbage collected. If SWT were being used in C++ that wasn't a problem. But this design decision for a Java API/Framework is a terrible flaw....This is IBM which is not adhering to the most fundamental rules of Java."
I think, it is a terrible flaw to do resource cleanup using the garbage collector.

Sun uses a similar policy for resources allocated outside the garbage collector. For example in JDK 1.4.2 they changed the policy to free native resources. Originally channels were garbage collected. But now you have to explicitely close them. It was for performance reasons, but th problem is the same: external resources are not seen by the garbage collector, and therefore it cannot trigger a collection if the system runs out of resources.

Just think of a simple object that allocates a megabyte in a native call and holding it in a pointer. The pointer is freed in the finalize method of the object. 1000 of those objects are are nothing to the garbage collector, but it takes 1 GB of your system resources. The simple loop:
for(int i=0;i<5000;i++)
new My1MbObject();
Will not work on most systems, becuase you allocate 5000 "small" objects .....

I think that's a general good rule to close resources that are created outside the garbage collector explicitely.

Therefore it is a good thing, that SWT relys on explicit disposing of native resources.

No comments:

Post a Comment