Skip to content

Commit 81d318c

Browse files
committed
Java21-specific code
1 parent 72258cd commit 81d318c

1 file changed

Lines changed: 62 additions & 0 deletions

File tree

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
package com.evolvedbinary.jnibench.jmhbench.cache;
2+
3+
import static java.lang.foreign.ValueLayout.JAVA_BYTE;
4+
5+
import java.lang.foreign.Arena;
6+
import java.lang.foreign.MemorySegment;
7+
import java.lang.foreign.ValueLayout;
8+
import java.util.stream.IntStream;
9+
10+
public class MemorySegmentCache extends LinkedListAllocationCache<MemorySegment> {
11+
private final Arena arena;
12+
13+
public MemorySegmentCache() {
14+
arena = Arena.ofShared();
15+
}
16+
17+
18+
@Override
19+
MemorySegment allocate(final int valueSize) {
20+
return arena.allocate(valueSize);
21+
}
22+
23+
@Override
24+
void free(final MemorySegment buffer) {
25+
// Nothing to do here, as we override taerdown() directly.
26+
}
27+
28+
@Override
29+
public void tearDown() {
30+
super.tearDown();
31+
arena.close();
32+
}
33+
34+
@Override
35+
protected int byteChecksum(final MemorySegment item) {
36+
return IntStream.range(0, (int) item.byteSize()).map(offset -> item.get(JAVA_BYTE, offset)).sum();
37+
}
38+
39+
@Override
40+
protected int longChecksum(final MemorySegment item) {
41+
return byteChecksum(item);
42+
}
43+
44+
@Override
45+
protected byte[] copyOut(final MemorySegment item) {
46+
// Get a cached byte array of the correct size
47+
byte[] array = byteArrayOfSize((int) item.byteSize());
48+
49+
// Perform bulk copy from native memory to Java heap array
50+
MemorySegment.copy(item, ValueLayout.JAVA_BYTE, 0, array, 0, (int) item.byteSize());
51+
52+
return array;
53+
}
54+
55+
@Override
56+
protected long copyIn(final MemorySegment item, final byte fillByte) {
57+
// Highly optimized bulk fill (native memset equivalent)
58+
item.fill(fillByte);
59+
60+
return fillByte;
61+
}
62+
}

0 commit comments

Comments
 (0)