Log4j 2 supports the notion of a PreciseClock - one that can be initialized to something more precise than a millisecond. At the same time it also supports running with no heap allocations in certain circumstances. I am in the process of moving our master branch to require Java 11 as the minimum. In doing so I am encountering unit test errors while verifying that logging is garbage free. They all occur allocating an Instant.
The code we have simply does public void init(MutableInstant mutableInstant) { Instant instant = java.time.Clock.systemUTC().instant(); mutableInstant.initFromEpochSecond(instant.getEpochSecond(), instant.getNano()); } In our previous tests we had thought the allocation was being eliminated due to escape analysis since the data is being extracted from the Instant and not passed along. However, after upgrading the Google test library and the JDK version it appears that is not the case. Ideally we would really like something like public void init(MutableInstant mutableInstant) { java.time.Clock.systemUTC().initInstant(mutableInstant); } where Mutable instant would implement an interface that has the two set methods.The method would execute the same logic that is in the instant() method but instead of creating a new Instant it would call the set methods for the provided object. This would allow us to either have the MutableInstants in ThreadLocals or some other mechanism to ensure they are thread safe and have no heap allocations. As it stands now I see no way to gain access to the higher precision clock without memory allocation. Do you know of another way to do this? Am I missing something? Ralph