Reputation: 115
I have created an object whose finalize method has been overridden to save and close the file with some information. That object is weak referenced from another object. I want to save some changes to the object when GC happens. That's why I have overridden the code for finalize.
But, the finalize method is called when an object is about to get garbage collected. That can be at any time after it has become eligible for garbage collection.
I dont want this, I want to call the finalize method as soon as GC happens, and there should not be any lag. Is there any jvm option which I can set to achieve this ?? There is only one other way which I can see is "System.runFinalization()", but that seems tacky?? Is there a more elegant way?
Thanks
Upvotes: 2
Views: 316
Reputation: 533880
I want to call the finalize method as soon as GC happens,
You can't without using internal APIs I wouldn't recommend you use.
there should not be any lag.
There is always lag. Just closing the file will take many milli-seconds. Are you okay with the application freezing while this happens (because the application can freeze while the GC is running)
Is there a more elegant way?
Close the resource when you finish with it if you want to to happen deterministically.
Upvotes: 6