WeakReference with null referent

Peter Levart peter.levart at gmail.com
Tue Jul 10 06:59:00 UTC 2018

Hi Mandy,

On 07/10/2018 12:18 AM, mandy chung wrote:
> On 7/9/18 12:59 PM, Per Liden wrote:
>> On 2018-07-09 20:49, mandy chung wrote:
>>> On 7/9/18 11:31 AM, Zheka Kozlov wrote:
>>>> It is possible to create a 
>>>> WeakReference/SoftReference/PhantomReference
>>>> with a null value in which case the Reference will never be 
>>>> enqueued. This
>>>> is quite obvious (since null cannot be weakly/softly/phantom 
>>>> reachable).
>>>> But I think it's worth being mentioned in the JavaDoc. What do you 
>>>> think?
>>> Alternatively, the constructor should require non-null referent and 
>>> throws NPE if null.
>>> I created https://bugs.openjdk.java.net/browse/JDK-8206933 to track 
>>> this.
>> It's not completely obvious to me that throwing NPE or otherwise 
>> blocking this is the right thing to do. Sure, creating a Reference 
>> with a null referent seems pretty useless, but it's also very similar 
>> to creating a Reference and immediately calling its clear() method, 
>> which is perfectly valid (and equally useless).
>> Are you saying we should block this because we can easily detect this 
>> particular case/misuse, as opposed to the immediately-called-clear 
>> case? Or is there some other rationale?
> I don't expect any one wants to create a reference with null referent
> Throwing NPE would be one way to catch if a reference object is created
> with null referent.  I think the compatibility risk is low.
> I agree that Reference::clear is equally useless.  Are you thinking
> something should be done with Reference::clear?
> Mandy

There are situations where being able to create a XxxReference without a 
referent is useful. For example, imagine a doubly-linked list of 
WeakReference subclasses - a special instance without a referent can be 
used as the head of such list that never goes away and simplifies 
insertion/deletion logic, etc...

JDK's java.lang.ref.Cleaner API uses such scheme in its implementation 
(see jdk.internal.ref.CleanerImpl.[Phantom|Weak|Soft]CleanableRef no-arg 

Regards, Peter

More information about the core-libs-dev mailing list