Last active
November 29, 2017 06:51
-
-
Save skel-nl/291abe36aed9a90f9313f9129b4fbd10 to your computer and use it in GitHub Desktop.
This file contains 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
import java.util.Map; | |
import java.util.Random; | |
import java.util.WeakHashMap; | |
/** | |
* @author skel | |
*/ | |
public class WeakHashMapExample1 { | |
private static final Map<String, Entry> map = new WeakHashMap<>(); | |
private static final Random R = new Random(); | |
private static final String ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; | |
private static void put(String value) { | |
map.put(value, new Entry(value)); | |
} | |
public static void main(String[] args) { | |
for (int i = 0; i <= 100_000_000; i++) { | |
if (i % 10_000_000 == 0) { | |
long freeMemoryMb = Runtime.getRuntime().freeMemory() / (1L << 20); | |
long totalMemoryMb = Runtime.getRuntime().totalMemory() / (1L << 20); | |
System.out.printf("Free memory: %dM / %dM\n", freeMemoryMb, totalMemoryMb); | |
} | |
put(nextString(10)); | |
} | |
System.out.println(map.size()); | |
} | |
private static String nextString(int length) { | |
StringBuilder sb = new StringBuilder(length); | |
for (int i = 0; i < length; i++) { | |
sb.append(ALPHABET.charAt(R.nextInt(ALPHABET.length()))); | |
} | |
return sb.toString(); | |
} | |
public static class Entry { | |
private final String value; | |
public Entry(String value) { | |
this.value = value; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment