Re: JavaMemoryModel: A different slant with reference leakage

From: Bill Pugh (
Date: Mon Jan 19 2004 - 14:10:12 EST

At 9:14 PM +1100 1/18/04, Sylvia Else wrote:
>class Util {
> private Delegate internalDelegate;
> private Delegate userDelegate;
> public void setDelegate(Delegate d) {
> userDelegate = d;
> internalDelegate = null;
> }
> public Delegate getDelegate() {
> return userDelegate;
> }
> public void doWork() {
> Delegate d = userDelegate;
> if(d == null) {
> if(internalDelegate == null) {
> internalDelegate = new DelegateImpl();
> d = internalDelegate;
> }
> // Do stuff with d.
> }
>The point of this is that the developer has to use some line of
>reasoning to show that the second implementation is correct. That
>reasoning needs to be straightforward, obvious, and clearly not
>applicable to the first implementation.
>I'll reserve further comment for later.

The only way a reference to a Delegate can be leaked by the above
code is for it to be returned by the getDelegate method, which reads
the userDelegate field. Internally created delegates are never
written to that field (the only heap variable that can contain a
reference to an internal delegate is internalDelegate).

Part of the problem comes from a lack of any formal definition of
what "leak" means, or what occurs in the "Do stuff with d" section.
Assume we prove that the "Do stuff with d" section cannot possibly
write the value contained in d out to the heap. Then, you show:
* the method doWork has only one place where it stores a reference
   to a Delegate (when it allocates a new internal delegate, and stores
   it to internalDelegate).
* the method doWork does not return a reference to an internal Delegate nor
   store it to any location other than internalDelegate.
* No other method reads the value of internalDelegate.

So you are safe. Unless someone gets ReflectPermission or invokes a
native method (but that isn't a JMM issue).

JavaMemoryModel mailing list -

This archive was generated by hypermail 2b29 : Thu Oct 13 2005 - 07:00:56 EDT