Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to specify the right type for ReferenceQueue.remove() in Java?

I have a class with a ReferenceQueue of WeakReferences.

class Example<K,V>
{
    ReferenceQueue<WeakReference<V>> queue = null;
    Thread cleanup = null;
[...]
    Example () {
        queue = new ReferenceQueue<WeakReference<V>>();
        cleanup = new Thread() {
                public void run() {
                    try {
                        for (;;) {
                            WeakReference<V> ref = queue.remove();
[...]

But when I try to compile this I get an "incompatible types" error:

found   : java.lang.ref.Reference<capture#189 of ? extends java.lang.ref.WeakReference<V>>
required: java.lang.ref.WeakReference<V>
                            WeakReference<V> ref = queue.remove();
                                                               ^

I do not understand this, because I have defined the reference queue as a queue of weak references of V and so I expect a weak reference of V as a result of remove().

Is this wrong? How can I fix this?

I tried also Reference<V> as a return value of remove() but that does not help. I tried the cast the result but that turns the error only into a warning.

like image 298
ceving Avatar asked Jul 18 '26 13:07

ceving


1 Answers

You should be using ReferenceQueue<V>, not ReferenceQueue<WeakReference<V>>. You'll need to explicitly cast the references you pull out of the queue to WeakReference<V>.

like image 83
Louis Wasserman Avatar answered Jul 20 '26 01:07

Louis Wasserman