SharedHashMap是更低延遲無GC暫停的Map實現

banq發表於2014-04-06


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)
<p class="indent">


其中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];
		}
	}
<p class="indent">


使用程式碼如下:

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);
	}
<p class="indent">


在另外一篇java.util.concurrent.ConcurrentHashMap VS openhft.collections.SharedHashMap對比中,SharedHashMap提供了比ConcurrentHashMap出色高效能,
特別是無GC暫停。

[該貼被banq於2014-04-06 10:34修改過]

相關文章