forked from polis-vk/2024-highload-dht
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMemTable.java
39 lines (32 loc) · 1.24 KB
/
MemTable.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
package ru.vk.itmo.test.kislovdanil.dao;
import ru.vk.itmo.dao.Entry;
import java.lang.foreign.MemorySegment;
import java.util.Comparator;
import java.util.concurrent.ConcurrentSkipListMap;
import java.util.concurrent.atomic.AtomicLong;
/* Basically, ConcurrentSkipList with bytes threshold.
*/
public class MemTable {
private final ConcurrentSkipListMap<MemorySegment, Entry<MemorySegment>> storage;
private final long threshold;
private final AtomicLong size = new AtomicLong(0);
private static long getEntrySize(Entry<MemorySegment> entry) {
long valueSize = entry.value() == null ? 0 : entry.value().byteSize();
return valueSize + entry.key().byteSize();
}
public MemTable(Comparator<MemorySegment> comparator, long threshold) {
this.storage = new ConcurrentSkipListMap<>(comparator);
this.threshold = threshold;
}
public boolean put(Entry<MemorySegment> entry) {
long entrySize = getEntrySize(entry);
if (size.addAndGet(entrySize) - entrySize > threshold) {
return false;
}
storage.put(entry.key(), entry);
return true;
}
public ConcurrentSkipListMap<MemorySegment, Entry<MemorySegment>> getStorage() {
return storage;
}
}