I'm working with Java Agent (creating a profiler) using code instrumentation (using Javassist for Instrumentation). I need to run few functions in my Java Agent profiler after the complete execution of java program. Something after the main function, like post-main (like we have premain). Is that possible?
Asked
Active
Viewed 606 times
1
-
1You could add a shutdown runtime hook. – Thorbjørn Ravn Andersen Nov 21 '15 at 12:53
-
Also if you want an existing example, you could look at the source for VisualVM – Thorbjørn Ravn Andersen Nov 21 '15 at 12:56
-
Shall I add shutdown runtime hook in remain function of my Java Agent? Or I instrument that in main function of Java Project through Java Agent? – ammar26 Nov 21 '15 at 16:44
-
I do not know. That is how I would approach it if I didn't want to instrument the main method. Try both. – Thorbjørn Ravn Andersen Nov 22 '15 at 11:12
1 Answers
3
There is no such thing as a postmain method and its semantics would not be clear either. Many programs run until they are killed. This requires the application to terminate and not to run different code.
Java offers shutdown hooks via the Runtime
class that are triggered on an application's termination but which must not perform long-lasting operations. Also, they are not executed if a program is killed.
For a profiler, you would need to process data regularly and you could attempt to flush your buffers on termination without a guarantee.

Holger
- 285,553
- 42
- 434
- 765

Rafael Winterhalter
- 42,759
- 13
- 108
- 192
-
So you are saying if I flush my buffers at termination to some file, there is no guarantee that it will always work? – ammar26 Nov 22 '15 at 11:51
-
1That is correct. A process can be killed what makes a program stop immediately. – Rafael Winterhalter Nov 22 '15 at 11:54
-
-
Of course, there is nothing wrong with processing data regularly *and* attempting a best-effort processing of remaining pending data via shutdown hook. – Holger Nov 24 '15 at 13:46