sterretje:
Is there any way to tell java to do garbage collection on request and it will do it immediately? I think you can tell it that you want it to do a garbage collection, but I don't think that it will do it immediately.
Basically, in Java that layer of operation of the JRE is none of your business. Of course, system-type code in appservers will do that, and a jre may have launch options and config files, but most of the time for most programming you don't worry about that find of thing and you are not really supposed to.
Having said that - you can manipulate memory and do some extremely interesting things with reference objects. There were three kinds last time I looked at it.
Each reference object holds a reference to some other object, and the reference to that other object may be dropped by the garbage collector it the GC's discretion. However, there is a contract that the GC is supposed t abide by. Each reference may be attached to a queue object which will be notified when the reference is cleared.
SoftReference - the GC is supposed to leave soft references uncleared for as long as it can, and to start clearing them when it begins to run out of memory. You use them to cache things that you can fetch again if you need to, eg: bitmaps.
WeakReference - the GC clears weak references aggressively. However, they may only be cleared when the referenced object is no longer reachable by any live thread (including by a soft reference). Furthermore, if more than one WeakReference can reach an object, then all of those references get cleared as an atomic operation together. This means that when a WeakReference is cleared, the object that it refers to is gone and cannot be retreived by any thread. You use this, for instance, for object/relational mappings where you want to be certain that if a given database record is loaded into memory, there will only be one object present at any time for that primary key.
PhantomReference - Phantom references always come back as having been cleared. However, the queue object will only be notified that the reference has been cleared once the GC has actually recovered the memory for whatever it was pointing at. This might be useful if you are interested in monitoring memory usage. Using a reference queue with phantom references is an alternative to polling System.freeMemory() at intervals.
So … it's possible to do quite sophisticated things. The method is that you subclass these classes to instrument them. But, it's not something that a programmer is usually interested in doing.