Detecting if an object is not reachable and can be collected by GC

G

GeH

Is there any possibility to detect if an object is reachable and can
be collected by the GarbageCollector?

I'm using a cache of weak references to persistent objects. Objects
are then accessed using an ObjectID. If the object is still alive, the
object is retrieved from the cache, if not, it will be fetched from a
database and the referece is returned to the caller.

Now I'm trying to implement a kind of automatic pessimistic locking:
when an object is placed into the cache, to object is locked. The
caller can now modify the object. After a defined period of time, I
would like to search the cache and detect the objects wich are not
referenced any more. These objects can then be unlocked and can be
modified by other users.

One possibility would be to call the GC.Collect(), walk the cache and
find all weak references which have been collected. Using the objectId
it is now possible to unlock the object in the database.
Unfortunatelly calling GC.Collect() is probably not a good idea. Any
other suggestions? As far as I know the GC performs a collect in two
steps: mark and sweep. Is it possible to execute just the mark step
and use the result for detecting if an object is still reachable??

Thanks,
Gerhard.
 
J

John B

GeH said:
Is there any possibility to detect if an object is reachable and can
be collected by the GarbageCollector?

I'm using a cache of weak references to persistent objects. Objects
are then accessed using an ObjectID. If the object is still alive, the
object is retrieved from the cache, if not, it will be fetched from a
database and the referece is returned to the caller.
<...>
One way you could do this would be with reference counting (which the GC
does not do).
I have investigated the same thing in the past and found that there was
no way to determine this.
There should be a bit of info regarding implementing reference counting
on the web but basically, each time something acquires a reference to
your object, you increment the ref count, when they release the
reference, you decrement the ref count.
You could use the IDisposable pattern to do reference counting,
otherwise it'd have to be manual (which idisposable is too).


HTH

JB
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top