Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -183,7 +183,8 @@ private D1(State<Entry<K>> state) {
/**
* Creates a fixed-size table holding at most {@code maxCapacity} entries. {@code entryClass} is
* used only to infer {@code TEntry}; entries are created by the {@code creator} functions
* passed to the insertion methods. The table does not resize.
* passed to the insertion methods. The table does not resize; its bucket count is {@link
* ConcurrentHashtable#bucketCountFor(int)}.
*/
@Nonnull
@SuppressWarnings("unchecked")
Expand Down Expand Up @@ -526,7 +527,8 @@ private D2(State<Entry<K1, K2>> state) {
/**
* Creates a fixed-size table holding at most {@code maxCapacity} entries. {@code entryClass} is
* used only to infer {@code TEntry}; entries are created by the {@code creator} functions
* passed to the insertion methods. The table does not resize.
* passed to the insertion methods. The table does not resize; its bucket count is {@link
* ConcurrentHashtable#bucketCountFor(int)}.
*/
@Nonnull
@SuppressWarnings("unchecked")
Expand Down Expand Up @@ -1027,11 +1029,61 @@ private State(AtomicReferenceArray<TEntry> buckets, int maxCapacity) {
/**
* Creates a bucket array for {@code maxCapacity} entries and pairs it with a manager enforcing
* that cap. {@code entryClass} is used only to infer {@code TEntry}.
*
* <p>The array has {@link #bucketCountFor(int) bucketCountFor(maxCapacity)} buckets: one per
* entry for small tables, but bounded by the heap for large ones (see {@link
* #bucketCountFor(int)}).
*/
@Nonnull
public static <TEntry extends Entry<TEntry>> State<TEntry> createBounded(
@Nonnull Class<TEntry> entryClass, int maxCapacity) {
return new State<>(createFixedBuckets(entryClass, maxCapacity), maxCapacity);
return createBounded(entryClass, maxCapacity, bucketCountFor(maxCapacity));
}

/**
* Creates a table of {@code bucketCount} buckets holding at most {@code maxCapacity} entries.
* Chains bear any excess of entries over buckets, so a table sized for its expected population
* still accepts up to its cap, with longer chains. {@code bucketCount} is rounded up to a power
* of two.
*/
@Nonnull
public static <TEntry extends Entry<TEntry>> State<TEntry> createBounded(
@Nonnull Class<TEntry> entryClass, int maxCapacity, int bucketCount) {
return new State<>(createFixedBuckets(entryClass, bucketCount), maxCapacity);
}

/** The fewest buckets {@link #bucketCountFor(int)} limits a table to. */
static final int MIN_HEAP_BOUNDED_BUCKETS = 1 << 10;

/**
* Returns the bucket count {@link #createBounded(Class, int)} uses for {@code maxCapacity}
* entries: {@link #sizeFor(int) sizeFor(maxCapacity)}, but no more than the heap warrants.
*
* <p>The table never resizes, so its bucket array is allocated at full size up front and
* retained, even if the table stays nearly empty. For a large cap on a small heap that is both a
* fixed cost out of proportion to the heap and, under G1, a humongous allocation. So the array is
* kept to at most 1/1024 of the maximum heap and below G1's humongous threshold, and never cut
* below {@value #MIN_HEAP_BOUNDED_BUCKETS} buckets. A table filled past its bucket count still
* works, with chains longer than one.
*/
public static int bucketCountFor(int maxCapacity) {
return bucketCountFor(maxCapacity, Runtime.getRuntime().maxMemory());
}

static int bucketCountFor(int maxCapacity, long maxHeapBytes) {
return Math.min(sizeFor(maxCapacity), maxBucketsForHeap(maxHeapBytes));
}

static int maxBucketsForHeap(long maxHeapBytes) {
// G1 aims for about 2,048 regions, a power of two between 1 and 32 MiB, and allocates any
// object of half a region or more as humongous. Leave room for the array header.
final long region =
Math.max(1L << 20, Math.min(1L << 25, Long.highestOneBit(maxHeapBytes >>> 11)));
final long arrayBytes = Math.min(region / 2 - 64, maxHeapBytes >>> 10);
// Compressed references, the default below 32 GiB, take 4 bytes; otherwise 8.
final long referenceBytes = maxHeapBytes < (32L << 30) ? 4 : 8;
final long buckets = Long.highestOneBit(Math.max(1, arrayBytes / referenceBytes));
return (int) Math.max(MIN_HEAP_BOUNDED_BUCKETS, Math.min(MAX_BUCKETS, buckets));
}

/** Live entries in {@code state}; see {@link SizeManager#estimateSize()}. Lock-free. */
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,64 @@ public static final int hashCode(@Nullable Object obj) {
return obj != null ? obj.hashCode() : 0;
}

/**
* Mixes a 32-bit value so that every input bit affects every output bit: the MurmurHash3 {@code
* fmix32} finalizer, the 32-bit counterpart of {@link LongHashingUtils#mix(long)}. Use it to
* combine hashes whose raw values are correlated, such as the entries of an {@linkplain
* #unorderedEntryHash unordered hash}.
*
* @param h the value to mix.
* @return the mixed value.
*/
public static int mix(int h) {
h ^= h >>> 16;
h *= 0x85EBCA6B;
h ^= h >>> 13;
h *= 0xC2B2AE35;
return h ^ (h >>> 16);
}

/**
* One entry's share of a 32-bit order-independent hash of a map: add the shares of all entries
* (and the size) to get a hash that doesn't depend on iteration order. Each share is mixed, so
* entries can't cancel each other the way {@link java.util.Map#hashCode}'s {@code key ^ value}
* terms do. No entry object is needed.
*
* <p>32 bits collide sooner than 64: distinct maps are likely to collide somewhere past about 65k
* of them. That is fine for a table that also checks equality; where the hash is a key's
* identity, use {@link LongHashingUtils#unorderedEntryHash(long, long)}.
*
* @param keyHash the entry key's hash.
* @param valueHash the entry value's hash, which the caller chooses.
* @return the entry's share, to add to the others.
*/
public static int unorderedEntryHash(int keyHash, int valueHash) {
return mix(keyHash * 0x9E3779B9 + valueHash);
}

/**
* A 32-bit order-independent hash of a map's entries, built from {@link #unorderedEntryHash} with
* the keys' and values' own hash codes: a better-mixed alternative to {@link
* java.util.Map#hashCode} for a key's {@code hashCode()}.
*
* @param map the map; {@code null} hashes like an empty map.
* @return the hash: {@code 0} for an empty map.
*/
public static int unorderedHash(@Nullable java.util.Map<?, ?> map) {
if (map == null || map.isEmpty()) {
return 0;
}
int hash = map.size();
for (final java.util.Map.Entry<?, ?> entry : map.entrySet()) {
final Object key = entry.getKey();
final Object value = entry.getValue();
hash +=
unorderedEntryHash(
key == null ? 0 : key.hashCode(), value == null ? 0 : value.hashCode());
}
return hash;
}

public static final int hash(boolean value) {
return Boolean.hashCode(value);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,57 @@
public final class LongHashingUtils {
private LongHashingUtils() {}

/**
* Mixes a 64-bit value so that every input bit affects every output bit: the SplitMix64
* finalizer. Use it to combine hashes whose raw values are correlated, such as the entries of an
* {@linkplain #unorderedEntryHash unordered hash}; to pick a table slot, a cheaper spread is
* enough.
*
* @param z the value to mix.
* @return the mixed value.
*/
public static long mix(long z) {
z = (z ^ (z >>> 30)) * 0xBF58476D1CE4E5B9L;
z = (z ^ (z >>> 27)) * 0x94D049BB133111EBL;
return z ^ (z >>> 31);
}

/**
* One entry's share of an order-independent hash of a map: add the shares of all entries (and, to
* tell sizes apart cheaply, the size) to get a hash that doesn't depend on iteration order.
*
* <p>Each entry is mixed before it's added. {@link java.util.Map#hashCode}'s sum of {@code key ^
* value} collides easily, because XOR lets one entry's bits cancel another's: {@code {a=0, b=0}}
* and {@code {a=1, b=1}} hash the same under it, but not here. No entry object is needed, so a
* caller can hash a map's contents, or a map it hasn't built yet, without allocating.
*
* @param keyHash the entry key's hash.
* @param valueHash the entry value's hash, which the caller chooses: for example one that also
* tells value types apart.
* @return the entry's share, to add to the others.
*/
public static long unorderedEntryHash(long keyHash, long valueHash) {
return mix(keyHash * 0x9E3779B97F4A7C15L + valueHash);
}

/**
* An order-independent hash of a map's entries, built from {@link #unorderedEntryHash} with the
* keys' and values' own hash codes. Equal maps hash equally whatever their iteration order.
*
* @param map the map; {@code null} hashes like an empty map.
* @return the hash: {@code 0} for an empty map.
*/
public static long unorderedHash(@Nullable java.util.Map<?, ?> map) {
if (map == null || map.isEmpty()) {
return 0L;
}
long hash = map.size();
for (final java.util.Map.Entry<?, ?> entry : map.entrySet()) {
hash += unorderedEntryHash(hash(entry.getKey()), hash(entry.getValue()));
}
return hash;
}

public static final long hash(Object obj) {
return obj == null ? Long.MIN_VALUE : obj.hashCode();
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
package datadog.trace.util;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertTrue;

import javax.annotation.Nonnull;
import org.junit.jupiter.api.Test;
import org.tabletest.junit.TableTest;

/** Exercises how {@link ConcurrentHashtable#createBounded} sizes its bucket array. */
class ConcurrentHashtableSizingTest {
private static final long MIB = 1L << 20;

private static final class TestEntry extends ConcurrentHashtable.Entry<TestEntry> {
final int value;

TestEntry(int value) {
super(value);
this.value = value;
}

@Override
public boolean matches(@Nonnull TestEntry other) {
return value == other.value;
}
}

@TableTest({
"scenario | heapMiB | buckets",
"1/1024 of a small heap | 16 | 4096 ",
"1/1024 of a 128 MiB heap | 128 | 32768 ",
"below the 1 MiB-region threshold | 1024 | 65536 ",
"below the 2 MiB-region threshold | 4096 | 131072 ",
"8-byte references from 32 GiB | 65536 | 1048576",
"below the 32 MiB-region cap | 1048576 | 1048576",
"never below the floor | 1 | 1024 "
})
void boundsTheBucketArrayByTheHeap(final long heapMiB, final int buckets) {
assertEquals(buckets, ConcurrentHashtable.maxBucketsForHeap(heapMiB * MIB));
}

@Test
void anUnboundedHeapStillGetsAFiniteBound() {
assertEquals(1 << 20, ConcurrentHashtable.maxBucketsForHeap(Long.MAX_VALUE));
}

@Test
void smallTablesGetABucketPerEntry() {
assertEquals(8, ConcurrentHashtable.bucketCountFor(8, 128 * MIB));
assertEquals(1024, ConcurrentHashtable.bucketCountFor(1000, 128 * MIB));
}

@Test
void largeTablesAreBoundedByTheHeap() {
assertEquals(32768, ConcurrentHashtable.bucketCountFor(131_072, 128 * MIB));
assertEquals(131_072, ConcurrentHashtable.bucketCountFor(131_072, 4096 * MIB));
}

@Test
void theDefaultSizingUsesThisHeap() {
final int expected =
ConcurrentHashtable.bucketCountFor(1 << 20, Runtime.getRuntime().maxMemory());

assertEquals(expected, ConcurrentHashtable.bucketCountFor(1 << 20));
assertEquals(
expected, ConcurrentHashtable.createBounded(TestEntry.class, 1 << 20).buckets.length());
}

@Test
void aTableWithFewerBucketsThanEntriesFillsToItsCap() {
final ConcurrentHashtable.State<TestEntry> state =
ConcurrentHashtable.createBounded(TestEntry.class, 100, 5);
assertEquals(8, state.buckets.length());

for (int key = 0; key < 100; key++) {
try (ConcurrentHashtable.Reservation<TestEntry> r =
ConcurrentHashtable.tryReserve(state, key)) {
assertNotNull(r.tryGetOrInsertOrNull(key, TestEntry::new), "key " + key);
}
}
assertTrue(ConcurrentHashtable.isFull(state));
assertEquals(100, ConcurrentHashtable.estimateSize(state));

for (int key = 0; key < 100; key++) {
TestEntry found = null;
for (TestEntry e = ConcurrentHashtable.bucketFor(state.buckets, key);
e != null;
e = e.next()) {
if (e.value == key) {
found = e;
}
}
assertNotNull(found, "key " + key);
try (ConcurrentHashtable.Reservation<TestEntry> r =
ConcurrentHashtable.tryReserve(state, key)) {
assertSame(found, r.tryGetOrInsertOrNull(key, TestEntry::new));
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -270,4 +270,53 @@ static final String[] deepClone(String[] strings) {
}
return clones;
}

@org.junit.jupiter.api.Test
public void mixSpreadsNearbyInputs() {
final java.util.Set<Integer> mixed = new java.util.HashSet<>();
for (int i = 0; i < 1_000; i++) {
mixed.add(HashingUtils.mix(i));
}
org.junit.jupiter.api.Assertions.assertEquals(1_000, mixed.size());
org.junit.jupiter.api.Assertions.assertNotEquals(
HashingUtils.mix(1) >>> 16, HashingUtils.mix(2) >>> 16);
}

@org.junit.jupiter.api.Test
public void unorderedHashIgnoresIterationOrder() {
final java.util.Map<String, Object> forward = new java.util.LinkedHashMap<>();
final java.util.Map<String, Object> backward = new java.util.LinkedHashMap<>();
for (int i = 0; i < 20; i++) {
forward.put("k" + i, i);
backward.put("k" + (19 - i), 19 - i);
}

org.junit.jupiter.api.Assertions.assertEquals(
HashingUtils.unorderedHash(forward), HashingUtils.unorderedHash(backward));
}

@org.junit.jupiter.api.Test
public void unorderedHashAvoidsMapHashCodesXorCollisions() {
final java.util.Map<String, Object> zeros = new java.util.HashMap<>();
zeros.put("a", 0);
zeros.put("b", 0);
final java.util.Map<String, Object> ones = new java.util.HashMap<>();
ones.put("a", 1);
ones.put("b", 1);

org.junit.jupiter.api.Assertions.assertEquals(zeros.hashCode(), ones.hashCode());
org.junit.jupiter.api.Assertions.assertNotEquals(
HashingUtils.unorderedHash(zeros), HashingUtils.unorderedHash(ones));
}

@org.junit.jupiter.api.Test
public void unorderedHashOfEmptyNullAndNullEntries() {
org.junit.jupiter.api.Assertions.assertEquals(0, HashingUtils.unorderedHash(null));
org.junit.jupiter.api.Assertions.assertEquals(
0, HashingUtils.unorderedHash(java.util.Collections.emptyMap()));
final java.util.Map<String, Object> nulls = new java.util.HashMap<>();
nulls.put(null, null);
org.junit.jupiter.api.Assertions.assertEquals(
1 + HashingUtils.unorderedEntryHash(0, 0), HashingUtils.unorderedHash(nulls));
}
}
Loading