multithreading - Keeping track of references in Java -
in java, there way tell whether or not references being maintained object in other threads (or generally)?
consider 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 multiple threads can claim/release resources such 2 threads can never own same resource @ given moment. happens if thread forgets release() resource? worse yet, if thread calls release() , keeps doing stuff resource?
using weakreference class, it's possible tell when there exist no more strong references given object. however, when happens, object garbage-collected , it's gone. softreference might work, there's still chance our resource gc'd before can put in "available" list.
so here's question: is there way keep track of whether these resources still being used?
ideally, threads claim() resources, use them long want, , resources freed automatically no more references maintained. think elegant, , useful in other situations too.
the answer simple: no
gc works @ vm global level , in current implementation (at least in hotspot) doesn't use reference counting, less reference tracking. means vm doesn't know referenced @ arbitrary points in time.
the gc wrong tool tracking things need released in timely manner; gc may run infrequently (in extreme cases gc may tuned run once every few hours). want resources available other threads owning block scope ends; requirement vastly different lax handling gc.
what want immediate detection things going out of scope per thread. while nice feature, question if ever worth performance impact costs.
the example of resources , thread "forgetting" release / retaining resource after release can dealt convention: use try-finally or maybe abuse try-with-resources blocks make sure life cycle maintained.
to catch accidental leaking of resource, can abuse finalize; again not predicatble when resources finalized (and can cleanup, resurrecting resource should not done; see jls finalize that).
edit: can defend against rouge threads using resource after release stroing owner in resource. resource can runtime checking calling thread indeed current owner.
Comments
Post a Comment