Garbage Free Check

Roger Riggs roger.riggs at oracle.com
Mon Apr 5 20:26:14 UTC 2021


Hi,

Java does not have a data type with enough resolution to hold a full 
nanosecond value.
Hence the implementation of Instant holding seconds and nanos.

There is an long dormant enhancement request to return micro-seconds as 
a long.
8196003 <https://bugs.openjdk.java.net/browse/JDK-8196003> java.time 
Instant and Duration methods for microseconds

That might be useful if the application gets enough resolution from 
microseconds.
There might be some clever interpolation between System.currentTimeMillis()
and adjusting with System.nanoTime().
Though it would likely not be exactly synchronized with the values from 
Instant.

Regards, Roger


On 4/5/21 3:56 PM, Brian Goetz wrote:
> Project Valhalla will allow Instant to be migrated to a primitive 
> class, which would address your problem.
>
> On 4/2/2021 7:47 PM, Ralph Goers wrote:
>> 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
>



More information about the core-libs-dev mailing list