huseyin tugrul buyukisik
huseyin tugrul buyukisik

Reputation: 11920

Java garbage collect to hashtable

Does java collect the garbage-signed things as objects?

If yes, can i tell java to direct them to one of my hashtables(accepts objects right?) programmatically?

I am curious about this functionality.I know System.gc() is the command but how can i achieve first question? Can i?

 myTrashBin=System.gc().getObjectList(); //???

If not, may be there could be a way to create this functionality by custom classes.

Last question: how can we override System.gc() ?

Thanks.

Upvotes: 1

Views: 612

Answers (4)

Peter Lawrey
Peter Lawrey

Reputation: 533520

Java uses managed memory. This means the JVM manages it because you don't want to ;)

can i tell java to direct them to one of my hashtables(accepts objects right?) programmatically?

You can progammatically get all the objects which would be cleaned up if they are referenced via a WeakReference.

how can we override System.gc() ?

You can't. In fact its only a hint as its not guaranteed to do anything.

Upvotes: 1

Fritz
Fritz

Reputation: 10045

System.gc() issues a call for the garbage collector but that's all there is to it. It might rise its priority and it might collect your items sooner, but there is no guarantee, as the docs say:

Calling the gc method suggests that the Java Virtual Machine expend effort toward recycling unused objects in order to make the memory they currently occupy available for quick reuse. When control returns from the method call, the Java Virtual Machine has made a best effort to reclaim space from all discarded objects.

You're better off taking other approaches such as the finalize() method or managing a reference counter in your objects so when it hits zero you know it is elegible to be collected. Check this link out.

Upvotes: 1

Massimiliano Peluso
Massimiliano Peluso

Reputation: 26737

I think you can achieve something like that if you implement the Finalize method and writing the code there: maybe adding the object to a custom list

Called by the garbage collector on an object when garbage collection determines that there are no more references to the object

http://docs.oracle.com/javase/6/docs/api/java/lang/Object.html#finalize%28%29

Upvotes: 1

Brian Agnew
Brian Agnew

Reputation: 272287

This isn't under your control. If your objects are unreachable then GC will collect these. System.gc() is nothing more than a hint, and can't be relied upon.

finalize() may be of interest, but read the answers to this question to understand limitations etc. PhantomReferences may also be of interest.

Upvotes: 5

Related Questions