I just wondered if there's a way to detect a Garbage Collection cycle from within the code/JVM that's being gc'd.
Timing does not play a role. So whether it's an event that occurs sometime before the actual cycle or afterwards is not important. (Having an event DURING the cycle seems highly unlikely and is probably dangerous too, depending on the GC implementation used).
All I could find were apps that can be used in parallel to the running JVM, such as jstat: https://dzone.com/articles/how-monitor-java-garbage with the source code here, for example: https://github.com/eagle518/jdk-source-code/blob/master/jdk5.0_src/j2se/src/share/classes/sun/tools/jstat/Jstat.java
All I see is that they use
MonitoredHost monitoredHost = MonitoredHost.getMonitoredHost(vmId); MonitoredVm monitoredVm = monitoredHost.getMonitoredVm(vmId, interval); So my problem is based on 2 questions. If the second question has a solution, we don't need to answer Q 1:
- my knowledge of MonitoredVm is not not good enough to know how to access the local JVM. Usually there's the VM ID required. How could I address that reliably, or is there another way that I can get the 'local'
MonitoredVm? - and would it even be necessary to use MonitoredVm, or is there anything a lot easier, like one can 'install' a shutdown hook and detect that event (
Runtime.getRuntime().addShutdownHook(hookThread);)? Java Reflection is also a welcome solution!
ArrayLists/HashSets that may grow quite large (simulations with grid logic and lots of moving objects) but the objects also get removed a lot, at some point you wanna shrink them back. You could check that on every removal, but later on it might need to grow in size again. So I thought the GC cycles might be a good indicator of when to check for RAM reaching limits, and then resize the lists with the worst size-to-elements ratio. But if I need polling, I could also just poll the RAM statistics...