[PATCH] remove redundant initialization of volatile fields with default values

Сергей Цыпанов sergei.tsypanov at yandex.ru
Mon Jun 22 18:23:24 UTC 2020


Hello,

while investigating an issue I've found out that assignment of default value to volatile fields slows down object instantiation.

Consider the benchmark:

@State(Scope.Thread)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@BenchmarkMode(value = Mode.AverageTime)
@Fork(jvmArgsAppend = {"-Xms2g", "-Xmx2g"})
public class VolatileFieldBenchmark {
  @Benchmark
  public Object explicitInit() {
    return new ExplicitInit();
  }

  @Benchmark
  public Object noInit() {
    return new NoInit();
  }

  private static class ExplicitInit {
    private volatile boolean field = false;
  }
  private static class NoInit {
    private volatile boolean field;
  }
}

This gives the following results as of my machine:

Benchmark Mode Cnt Score Error Units
VolatileFieldBenchmark.explicitInit avgt 40 11.087 ± 0.140 ns/op
VolatileFieldBenchmark.noInit avgt 40 3.367 ± 0.131 ns/op

I've looked into source code of java.base and found out several cases where the default value is assigned to volatile field.

Getting rid of such assignements demonstates improvement as of object instantiation, e.g. javax.security.auth.Subject:

           Mode Cnt Score Error Units
before avgt 40 35.933 ± 2.647 ns/op
after avgt 40 30.817 ± 2.384 ns/op

As of testing tier1 and tier2 are both ok after the changes.

Best regards,
Sergey Tsypanov
-------------- next part --------------
A non-text attachment was scrubbed...
Name: volatile.patch
Type: text/x-diff
Size: 6253 bytes
Desc: not available
URL: <https://mail.openjdk.org/pipermail/security-dev/attachments/20200622/8daa68b2/volatile.patch>
-------------- next part --------------
An embedded message was scrubbed...
From: =?utf-8?B?0KHQtdGA0LPQtdC5INCm0YvQv9Cw0L3QvtCy?= <sergei.tsypanov at yandex.ru>
Subject: [PATCH] remove redundant initialization of volatile fields with default values
Date: Fri, 19 Jun 2020 06:57:25 +0200
Size: 11984
URL: <https://mail.openjdk.org/pipermail/security-dev/attachments/20200622/8daa68b2/attachment.eml>


More information about the security-dev mailing list