I have a general idea of how the Garbage Collector works in Java, but my reasoning for destroying an object is not because I care about freeing up memory, but because of functio
You have NO CONTROL over Java Garbage Collection -GC- and there is now way that you can force the Java Virtual Machine to destroy an object for you.
You can call System.gc()
[or Runtime.getRuntime().gc()
] but that only suggests the JVM to run the Garbage Collection. The true is that the JVM is not supposed to listen to you for this and the GC execution is not guaranteed. Do not rely on that.
Regarding your design need, put your money in a bank (or a street if you want people to find them) and ask the bank to give you one. Assuming that the bank has only 1, then subsequent calls will return null.
EDIT AFTER DOWNVOTE
I decided to remove some dust from my books and to quote a few lines from the Forcing Garbage Collection section of the 3rd chapter of the SCJP Study Guide. A book that I studied for pure masochism.
The first thing that should be mentioned here is that, contrary to this section's title, garbage collection cannot be forced.
..it's recommended that you never invoke System.gc() in your code - leave it to the JVM.
..it is only possible to suggest to the JVM that it performs garbage collection. However, there are no guarantees the JVM will actually remove all of the unused objects from memory (even if garbage collection is run).
Garbage Collection is a harder concept than it seems...