测试AtomicInteger临界值应用

场景: AtomicInteger原子增长计数,每个线程平均获取资源。到达临界值后,尝试恢复到取模区间0~7。经过测试,200次|500次调用分别出现一例apiCall:8。

 

@Test
    public void test(){
        AtomicInteger apiCallCount = new AtomicInteger();
        ThreadFactory namedThreadFactory = new ThreadFactoryBuilder()
                .setNameFormat("demo-pool-%d").build();
        String[] apikeys="a,b,c,d".split(",");
        //Common Thread Pool
        ExecutorService pool = new ThreadPoolExecutor(1000, 1000,
                0L, TimeUnit.MILLISECONDS,
                new LinkedBlockingQueue<Runnable>(1024), namedThreadFactory, new ThreadPoolExecutor.AbortPolicy());
        CompletionService completionService = new ExecutorCompletionService<>(pool);
        int times=200;
        for(int i = 0; i < times; i++) {
            final int j = i;
            completionService.submit(new Callable() {
                @Override
                public String call() throws Exception {
                    try {
                        String[] tempApiKeys=apikeys;
                        int apiCall = apiCallCount.getAndIncrement();
                        if (apiCall >= 7) {
                            apiCallCount.compareAndSet(apiCall + 1, (apiCall + 1) % tempApiKeys.length);
                        }
                        if (apiCall < 0) {
                            apiCall = apiCall % tempApiKeys.length + tempApiKeys.length - 1;
                        }

                        String apikey = tempApiKeys[apiCall % tempApiKeys.length];
                        System.out.println("apikey:"+ apikey+",apiCall:"+ apiCall+","+j);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    return "OK";
                }

            });
        }

        pool.shutdown();//gracefully shutdown
        for (int i = 0; i < times; i++) {
            Future<String> future = null;
            try {
                future = completionService.take();
                String result = future.get();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }


        }
    }

 

 

apikey:a,apiCall:0,76
apikey:c,apiCall:2,74
apikey:d,apiCall:3,89
apikey:b,apiCall:5,71
apikey:d,apiCall:7,69
apikey:b,apiCall:1,67
apikey:c,apiCall:2,66
apikey:a,apiCall:4,63
apikey:d,apiCall:7,61
apikey:b,apiCall:1,60
apikey:c,apiCall:2,58
apikey:a,apiCall:8,92

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值