原文地址:http://flychao88.iteye.com/blog/2076419
SharedHashMap是开源工具OpenHFT一个子项目,SharedHashMap提供ConcurrentHashMap更低延迟无JVM的GC暂停的实现。两个特点是:
在另外一篇java.util.concurrent.ConcurrentHashMap VS openhft.collections.SharedHashMap对比中,SharedHashMap提供了比ConcurrentHashMap出色高性能,
原文如下:
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暂停。
******************************原文结束,学习笔记开始**********************************
首先照着例子跑了下代码,发现编译报错。缺少jar。导入:collections-3.1.0.jar,lang-6.4.4.jar。
再运行报错:
(java.lang.NoSuchMethodError: sun.misc.Unsafe.copyMemory(Ljava/lang/Object;JLjava/lang/Object;JJ)
原来是jdk版本太旧,现在是jdk1.6.下载了jdk1.8.发现myeclipse6.5编译有问题。不兼容。没办法,再下载jdk1.7.OK
************************用法结束,整理下问题产生的背景及特点****************************
1堆内存大小限制。
2.GC造成的延迟影响。
另有文章介绍的比较详细:
http://www.infoq.com/cn/articles/Open-JDK-and-HashMap-Off-Heap?utm_campaign=infoq_content&utm_source=infoq&utm_medium=feed&utm_term=global