Created
July 26, 2020 13:54
-
-
Save imrexhuang/3194097c308e7d5b613e652b466862e9 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package ohcache; | |
import org.caffinitas.ohc.CacheSerializer; | |
import org.caffinitas.ohc.OHCache; | |
import org.caffinitas.ohc.OHCacheBuilder; | |
import java.nio.ByteBuffer; | |
import java.nio.charset.StandardCharsets; | |
import java.util.HashMap; | |
import java.util.Map; | |
import java.util.Scanner; | |
import java.util.UUID; | |
import java.util.stream.IntStream; | |
// 參考 https://www.isaacnote.com/2018/09/ohcache-simple-example.html | |
// 使用到Java Stream語法,需要JDK 8以上版本執行 | |
public class SimpleMain { | |
public static void main(String[] params) { | |
Scanner scanner = new Scanner(System.in); | |
while(scanner.hasNextLine()) { | |
if (scanner.nextLine().trim().equals("GO")) { | |
System.out.println(Runtime.getRuntime().freeMemory()/1024/1024 + "/" + Runtime.getRuntime().totalMemory()/1024/1024); | |
//使用on-heap memory方式處理大量資料 | |
//執行會Exception in thread "main" java.lang.OutOfMemoryError: GC overhead limit exceeded | |
/* | |
Map<String, String> map = new HashMap<String, String>(); | |
map.put("A", "A12345"); | |
System.out.println(map.get("A")); | |
IntStream.range(0, 1000_000_000).forEach(idx -> { | |
map.put(UUID.randomUUID().toString(), UUID.randomUUID().toString()); }); | |
*/ | |
//使用off-heap memory方式處理大量資料 | |
OHCache<String,String> ohc = OHCacheBuilder.<String,String>newBuilder() | |
.keySerializer(new StringSerializer()) | |
.valueSerializer(new StringSerializer()) | |
.build(); | |
ohc.put("A", "A12345"); | |
System.out.println(ohc.get("A")); | |
IntStream.range(0, 1000_000_000).forEach(idx -> { | |
ohc.put(UUID.randomUUID().toString(), UUID.randomUUID().toString()); }); | |
System.out.println(Runtime.getRuntime().freeMemory()/1024/1024 + "/" + Runtime.getRuntime().totalMemory()/1024/1024); | |
} else { | |
System.out.println("input 'GO' then click enter"); | |
} | |
} | |
} //end main | |
private static class StringSerializer implements CacheSerializer<String> { | |
@Override | |
public void serialize(String s, ByteBuffer byteBuffer) { | |
byteBuffer.put(s.getBytes()); | |
} | |
@Override | |
public String deserialize(ByteBuffer byteBuffer) { | |
return StandardCharsets.UTF_8.decode(byteBuffer).toString(); | |
} | |
@Override | |
public int serializedSize(String s) { | |
return s.getBytes().length; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment