Garbage collection working for me.

M

Malcolm Ryan

I'm writing a piece of java code which retrieves data from a database
and provides it to various parts of my program. I want to cache used
instances in memory. So as long as there are references to objects
still being used, I would keep them in the cache. This raises all
manner of garbage collection problems - how to keep track of whether
instances are still being used elsewhere in the program.

It occurs to me that Java is already keeping track of this
information, for it's own garbage colllection. What I really want to
do is ask the Java GC the question "If I released this reference,
would you garbage collect this object?". If the answer is yes, I
release the reference. If the answer is no, I hold onto it.

Is there any way of doing this?

Malcolm
 
X

xarax

Malcolm Ryan said:
I'm writing a piece of java code which retrieves data from a database
and provides it to various parts of my program. I want to cache used
instances in memory. So as long as there are references to objects
still being used, I would keep them in the cache. This raises all
manner of garbage collection problems - how to keep track of whether
instances are still being used elsewhere in the program.

It occurs to me that Java is already keeping track of this
information, for it's own garbage colllection. What I really want to
do is ask the Java GC the question "If I released this reference,
would you garbage collect this object?". If the answer is yes, I
release the reference. If the answer is no, I hold onto it.

Is there any way of doing this?

Yes, use java.lang.ref.Reference and friends. Read
the javadoc for the details.
 
S

secret

A WeakHashMap might also do what you need here. The idea being that it will
hold your object without preventing it from being garbage collected.
 

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

Members online

No members online now.

Forum statistics

Threads
474,431
Messages
2,571,677
Members
48,796
Latest member
Greg L.

Latest Threads

Top