zoukankan      html  css  js  c++  java
  • Prefer ThreadLocalRandom over Random

    Java 7 has introduced a new random number generator - ThreadLocalRandom

    Normally to generate Random numbers, we either do

    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 IntLong, etc). When all usages are of this form, it is never possible to accidently share a ThreadLocalRandom across multiple threads.
    Usage Example - 
     
    //Generate a random number b/w 0 and 10.  0 <= R < 10
    //Using Math.random()
    int r1 = (int)Math.random()*10;
    //Using Random
    Random rand = new Random();
    int r2 = rand.nextInt(10);
    //Using ThreadLocalRandom
    int r3 = ThreadLocalRandom.current().nextInt(10);
    

     http://thoughtfuljava.blogspot.com/2012/09/prefer-threadlocalrandom-over-random.html

    http://www.blogjava.net/yongboy/archive/2012/02/04/369574.html

        public static void main(String[] args) {
            Map<String, Integer> map = new HashMap<>();
            for (int i = 0; i < 10000; i++) {
                int nextInt = ThreadLocalRandom.current().nextInt(10);
                if (nextInt >= 0) {
                    String positive = "positive";
                    Integer current = map.get(positive);
                    map.put(positive, current == null ? 1 : ++current);
                } else {
                    System.out.println(nextInt);
                    String positive = "negative";
                    Integer current = map.get(positive);
                    map.put(positive, current == null ? 1 : ++current);
                }
            }
            System.out.println(map);
    
        }
  • 相关阅读:
    python yield from (一)
    python yield: send, close, throw
    python I/O多路复用 使用http完成http请求
    python I/O复用
    python 进程间通信
    mac 使用express -e ./
    Object.keys使用整理
    MacBook pro管理员变成普通用户无法解锁问题
    MAC应用无法打开或文件损坏的处理方法
    Redis "MISCONF Redis is configured to save RDB snapshots, but is currently not able to persist on disk"问题的解决
  • 原文地址:https://www.cnblogs.com/softidea/p/6639502.html
Copyright © 2011-2022 走看看