SharedHashMap是开源工具OpenHFT一个子项目,SharedHashMap提供ConcurrentHashMap更低延迟无JVM的GC暂停的实现。两个特点是:
1.所有元素都保存在Java heap之外,这样就不受GC影响,没有GC暂停。
2.所有元素都在一个共享内存区域,对所有进程都是可视的。
SharedHashMap采取的是"no-copy"模型,能够提供off-heap堆内存之外内存空间,让应用程序获得更低延迟更快性能。
它不是普通HashMap,而是一个特殊的,只有在你特殊需要时才使用,如果你想使用JVM堆之外内存可以使用它,如果想持久化Map中项目,也可以使用,特别是你想使用一个大的共享Map时。
使用代码:
SharedHashMapBuilder builder = new SharedHashMapBuilder(); String shmPath = System.getProperty("java.io.tmpdir") + System.getProperty("file.separator") + "SHMTest1"; //Declare as a ConcurrentMap rather than Map if you want to use putIfAbsent() Map<String, SHMTest1Data> theSharedMap = builder.create(new File(shmPath), String.class, SHMTest1Data.class)
|
其中SHMTest1Data类是一个简单的数组实现。代码如下:
public static class SHMTest1Data implements Serializable { private long[] time; public SHMTest1Data(int maxNumberOfProcessesAllowed) { this.time = new long[maxNumberOfProcessesAllowed]; } public int getMaxNumberOfProcessesAllowed() { return this.time.length; } public void setTimeAt(int index, long time) { this.time[index] = time; } public long getTimeAt(int index) { return this.time[index]; } }
|
使用代码如下:
SHMTest1Data data = theSharedMap.get("whatever"); if (data == null) { //From 1.8, we could use putIfAbsent() as that's been added to the Map interface. //Alternatively we can cast to SharedHashMap and use putIfAbsent(). //But for this test just bang it in, doesn't matter if something //else gets in first as you'll see below data = new SHMTest1Data(2); theSharedMap.put("whatever", data); }
|
在另外一篇java.util.concurrent.ConcurrentHashMap VS openhft.collections.SharedHashMap对比中,SharedHashMap提供了比ConcurrentHashMap出色高性能,
特别是无GC暂停。
[该贴被banq于2014-04-06 10:34修改过]