Skip to content

Commit

Permalink
Use FastThreadLocal for the Mac instances (java-native-access#621)
Browse files Browse the repository at this point in the history
Motivation:

Creating a new Mac instance each time is wasteful. As the method is
expected to be called from the EventLoop we should better cache these in
a FastThreadLocal

Modifications:

Cache instances in FastThreadLocal

Result:

Less overhead
  • Loading branch information
normanmaurer authored Nov 22, 2023
1 parent a59908a commit 0fa01f4
Showing 1 changed file with 10 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
import java.security.SecureRandom;
import java.util.Arrays;

import io.netty.util.concurrent.FastThreadLocal;
import io.netty.util.internal.ObjectUtil;

import javax.crypto.Mac;
Expand All @@ -33,6 +34,13 @@
final class HmacSignQuicConnectionIdGenerator implements QuicConnectionIdGenerator {
static final QuicConnectionIdGenerator INSTANCE = new HmacSignQuicConnectionIdGenerator();

private static final FastThreadLocal<Mac> MACS = new FastThreadLocal<Mac>() {
@Override
protected Mac initialValue() {
return newMac();
}
};

private static final String ALGORITM = "HmacSHA256";
private static final byte[] randomKey = new byte[16];

Expand Down Expand Up @@ -66,11 +74,9 @@ public ByteBuffer newId(ByteBuffer buffer, int length) {
ObjectUtil.checkPositive(buffer.remaining(), "buffer");
ObjectUtil.checkInRange(length, 0, maxConnectionIdLength(), "length");


// TODO: Consider using a ThreadLocal.
Mac mac = newMac();
Mac mac = MACS.get();
mac.reset();
mac.update(buffer);

byte[] signBytes = mac.doFinal();
if (signBytes.length != length) {
signBytes = Arrays.copyOf(signBytes, length);
Expand Down

0 comments on commit 0fa01f4

Please sign in to comment.