In Java, is there any way to tell whether or not references are being maintained to an object in other threads (or generally)?
Consider the following class:
public class ResourcePool<TYPE>
{
private final Queue<Object> emptyLocks = new LinkedBlockingQueue<>();
private final Queue<TYPE> available = new LinkedBlockingQueue<>();
private final Queue<TYPE> claimed = new LinkedBlockingQueue<>();
public void add(TYPE resource)
{
available.add(resource);
}
public TYPE claim() throws InterruptedException
{
if (available.isEmpty())
{
Object lock = new Object();
synchronized (lock)
{
emptyLocks.add(lock);
lock.wait();
}
}
TYPE resource = available.poll();
claimed.add(resource);
return resource;
}
public void release(TYPE resource)
{
if (!claimed.remove(resource)) return;
available.add(resource);
Object lock = emptyLocks.poll();
if (lock != null) synchronized (lock) {lock.notify();}
}
}
The idea here is that multiple threads can claim/release resources such that two threads can never own the same resource at any given moment. But what happens if a thread forgets to release() a resource? Worse yet, what if the thread calls release() and then keeps doing stuff with the resource?
Using the WeakReference class, it's possible to tell when there exist no more strong references to a given object. However, when that happens, the object is garbage-collected and it's gone. SoftReference might work, but then there's still a chance that our resource will be GC'd before we can put it back in the "available" list.
So here's the question: Is there any way to keep track of whether these resources are still actually being used?
Ideally, threads could claim() resources, use them as long as they want, and those resources would be freed up automatically as soon as no more references are maintained. I think that would be very elegant, and useful in other situations too.