a life of coding

Monday, August 04, 2008

Java Static Class Object Fields and Weak References

In browsing the Mozilla Rhino code, I stumbled upon a garbage collection problem that is truly bizarre. Rhino uses thread local storage for the current Context object. TLS uses a weak dictionary, so it is important that there is no strong circular reference to the key. Years ago (CVS r 1.234), the rhino class Context used to have a static reference to the thread local storage object. This was a problem because even when an array is empty, it has a reference to the class of objects it can hold. Thus, the TLS key (the ThreadLocal object itself) is referenced by the Context class, which is referenced by the (empty) Context[].class, which is a value in the TLS map! This circular dependency caused rhino to leak memory whenever a thread that used JavaScript completed. The solution to this was to change the value to an Object[]. When there are Context objects in the array, the reference still exists, however once the array is empty, there is no longer a reference and the TLS weakref dictionary will cut that key/value pair loose.

The comment, original, and fix.

Wow, thats a lot of detail. Here's the summary: if you have static class fields, make sure they don't eventually point to the key of a weak dictionary. If find this unavoidable, you can break the loop by storing a value as an Object and casting any usage of it. You will still have to set this variable to null in order for GC to happen.

1 Comments:

  • Do you still work with those Boulder people? They've changed their website to point to an iPhone app. Have they scaled back or re-focused?

    By Anonymous Anonymous, At 9/21/08 2:02 PM  

Post a Comment



<$I18N$LinksToThisPost>:

Create a Link

<< Home