Posts

Showing posts with the label performance

Speedup Your Collections with Improved Hashing Function from Java7

Java7 has introduced an improved hash function for Map and Map derived implementations ( since 7u6 ). It is applicable for keys of type String . Following collections can make use of this new hash function. HashMap Hashtable HashSet LinkedHashMap LinkedHashSet WeakHashMap ConcurrentHashMap The new hash function improves the performance when there are large number of collisions .  It can be enabled by setting the System property  jdk.map.althashing.threshold . If jdk.map.althashing.threshold=k  , This means that java will use alternative hashing function for maps with capacity greater than k entries. Usage Example - java -Djdk.map.althashing.threshold=512 MyAppMain Why it is disabled by default and caveat before using - This feature is disabled by default to ensure backward compatibility.  The iteration order of keys, values and entries will change after using the new Hash function. According to Java team, many applications have depend...

Prefer ThreadLocalRandom over Random

Java 7 has introduced a new random number generator - ThreadLocalRandom Normally to generate Random numbers, we either do Create an instance of java.util.Random  OR Math.random() - which internally creates an instance of java.util.Random on first invocation.  However in a concurrent applications usage of above leads to contention issues - Random is thread safe for use by multiple threads. But if multiple threads use the same instance of Random, the same seed is shared by multiple threads. It leads to contention between multiple threads and so to performance degradation.  ThreadLocalRandom is solution to above problem. ThreadLocalRandom has a Random instance per thread and safeguards against contention. From the api docs -  Usages of this class should typically be of the form:  ThreadLocalRandom.current().nextX(...)  (where  X  is  Int ,  Long , etc). When all usages are of this form, it is never possible to accidently...