Last active
April 22, 2016 08:20
-
-
Save kabutz/08f8585e1640c4305918a4e529151922 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.math.*; | |
import java.util.*; | |
import java.util.concurrent.*; | |
import java.util.function.*; | |
/** | |
* Seems to cause livelock in Java 8 ConcurrentHashMap transfer() | |
* method and ConcurrentModificationException in Java 9 HashMap. | |
*/ | |
public class WeirdComputeIfAbsentBehaviour { | |
public static void main(String... args) { | |
for (int i = 0; i < 30; i++) { | |
System.out.println("i = " + i); | |
show(new HashMap(), i); | |
show(new LinkedHashMap(), i); | |
show(new ConcurrentSkipListMap<>(), i); | |
show(new ConcurrentHashMap<>(), i); | |
} | |
} | |
private static void show(Map<Integer, BigInteger> map, int n) { | |
System.out.println(map.getClass().getSimpleName() + ": " + | |
new FibonacciCached(map).f(n)); | |
} | |
public static class FibonacciCached { | |
private final Map<Integer, BigInteger> cache; | |
public FibonacciCached(Map<Integer, BigInteger> cache) { | |
this.cache = cache; | |
cache.put(0, BigInteger.ZERO); | |
cache.put(1, BigInteger.ONE); | |
} | |
public BigInteger f(int n) { | |
return cache.computeIfAbsent(n, key -> f(n - 1).add(f(n - 2))); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
package livedemo;
import java.util.concurrent.*;
import java.math.BigInteger;
import java.util.Map;
public class FibonacciCached {
private final Map<Integer, CompletionStage> cache;
}