Repository navigation
Expand file tree
/
Copy pathCacheOffHeapAdvanced.java
More file actions
69 lines (52 loc) · 1.94 KB
/
Copy pathCacheOffHeapAdvanced.java
File metadata and controls
69 lines (52 loc) · 1.94 KB
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
package examples;
import org.mapdb.*;
import java.util.Random;
/**
* This example shows how-to create off-heap cache,
* where entries expire when maximal store size is reached.
*
* It also shows howto get basic statistics about store size.
*
* It is more advanced version of previous example.
* It uses more settings, bypasses general serialization for best performance
* and discussed other performance tunning
*
*/
public class CacheOffHeapAdvanced {
public static void main(String[] args) {
final double cacheSizeInGB = 1.0;
//first create store
DB db = DBMaker
.newMemoryDirectDB()
.transactionDisable()
//some additional options for DB
// .asyncWriteEnable()
// .cacheSize(100000)
.make();
HTreeMap cache = db
.createHashMap("cache")
.expireStoreSize(cacheSizeInGB)
.counterEnable() //disable this if cache.size() is not used
//use proper serializers to and improve performance
.keySerializer(Serializer.LONG)
.valueSerializer(Serializer.BYTE_ARRAY)
.make();
//generates random key and values
Random r = new Random();
//used to print store statistics
Store store = Store.forDB(db);
// insert some stuff in cycle
for(long counter=1; counter<1e8; counter++){
long key = r.nextLong();
byte[] value = new byte[1000];
r.nextBytes(value);
cache.put(key,value);
if(counter%1e5==0){
System.out.printf("Map size: %,d, counter %,d, curr store size: %,d, store free size: %,d\n",
cache.sizeLong(), counter, store.getCurrSize(), store.getFreeSize());
}
}
// and release memory. Only necessary with `DBMaker.newCacheDirect()`
cache.close();
}
}