How can I call methods on items in a ReferenceQueue if type erasure has allowed me to only call Object() methods?

StackOverflow https://stackoverflow.com/questions/18000316

Domanda

I have a reference queue, declared as:

ReferenceQueue<MapChunk> rqueue = new ReferenceQueue<>();

and I have some soft references constructed in the form of

SoftReference ref=new SoftReference<MapChunk>(ourChunk, rqueue);

As per the docs, rqueue is ReferenceQueue<? extends MapChunk>

I wish to call a handler on their garbage collection, which is why I put them into the queue. However, when I begin processing the queue from another thread, I retrieve the object from the queue via

Reference ref=rqueue.poll();
synchronized (chunks) {
    synchronized (MapDatabase.class) {
        chunks.put(ref.get().getPosition(), ref.get());
    }
}

My compiler errors indicate type erasure has occurred and I'm left with ref.get() being an object(due to the raw type of the queue). I can neither call methods on the object that I need nor can I pass it to a method that requires a MapChunk itself. Surely this impedes many uses of the reference queue, and I'm likely doing something wrong in that case. I am certain that I will only get MapChunk objects at runtime, so should I use a cast? Do something else? Not use the reference queue at all?

Edit: If I use Reference<MapChunk> ref=rqueue.poll() I get the following:

cannot convert from Reference<capture#1-of ? extends MapChunk> to Reference<MapChunk>

When I use Reference<? extends MapChunk> ref=rqueue.poll(); the error on that line is resolved, but another error comes up when I try to use ref:

The method addMapChunk(Position, SoftReference<MapChunk>) in the type HashMap<Position,SoftReference<MapChunk>> is not applicable for the arguments (Position, capture#3-of ? extends MapChunk).

Edit: I guess it was simply a buggy error message as the type did convert properly when another bug was fixed.

È stato utile?

Soluzione

If you don't want type erasure, don't erase the type.

Reference<? extends MapChunk> ref = rqueue.poll();
MapChunk mc = ref.get();
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top