Skip to main content

ReferenceQueue generics probably unusable

3 replies [Last post]
soupdragon
Offline
Joined: 2006-01-07
Points: 0

It seems to me that an error has been made in adding generics to the ReferenceQueue object. In fact I can't see a realistic case where generics can be used.

The mistake was to make the generic type the referent type, rather than the Reference type.

If a ReferenceQueue is actually to do anything effective you're almost always going to need to add some data to the reference object. References on the queue are cleared, so you need some information to specify the side-effect of clearing the reference. For a cache, for example, you need the reference to store the key so it can be removed from the cache. The only contrary case would be if the Reference was, itself, the key.

So the actual Reference objects will look like:

<br />
class StoreReference extends SoftReference {<br />
  private Key k;<br />

Now, of course, when your cleanup thread takes a reference from the queue you need it in a StoreReference variable.

If you declare the ReferenceQueue generically as ReferenceQueue then remove() returns Reference<? extends StoreData>. It seems impossible to cast this to StoreReference (error "Inconvertible types; ").

It seems clear to me that ReferenceQueue should have been defined so that the generic type was the elements it actually contains, so I should have been able to declare it ReferenceQueue.

Could we at least have ReferenceQueue return Reference rather than <? extends T>, which should permit a cast?

Reply viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
tackline
Offline
Joined: 2003-06-19
Points: 0

As the API is designed (which was done way before generics), you can't sensible generify both Reference and ReferenceQueue. A parallel API could support a generified reference queue, but it hardly seems worth it to save a cast.

soupdragon
Offline
Joined: 2006-01-07
Points: 0

I don't see why ReferenceQueue shouldn't have been defined:

[code]
public class ReferenceQueue {
[/code]

garretwilson
Offline
Joined: 2005-09-09
Points: 0

Looks like no one understood your question. The "answer" to a related question here is even less help:

http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4773346

Hee hee! Use another reference queue, indeed. Right. Since a Reference requires the existing JDK ReferenceQueue, I suppose this means you'll need to create your own Reference class from scratch, too---which will mean creating your own JVM as well, to get it to work. Simple stuff!

So if you find someone who understands your question, please let me know what the answer is, too. Good luck.