Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.j256;
- import java.util.concurrent.ExecutorService;
- import java.util.concurrent.Executors;
- import java.util.concurrent.TimeUnit;
- import java.util.concurrent.atomic.AtomicBoolean;
- import java.util.concurrent.atomic.AtomicIntegerArray;
- import org.junit.Test;
- public class BooleanTester {
- private final static int NUM_ATOMICS = 10;
- private long NUM_CYCLES = 10000000;
- private final AtomicIntegerArray array1 = new AtomicIntegerArray(NUM_ATOMICS);
- private final AtomicBoolean[] array2 = new AtomicBoolean[NUM_ATOMICS];
- {
- for (int i = 0; i < array2.length; i++) {
- array2[i] = new AtomicBoolean();
- }
- }
- @Test
- public void test() throws Exception {
- // warm up hotspot
- NUM_CYCLES = 1000000;
- runTest();
- // really do the test
- NUM_CYCLES = 10000000;
- runTest();
- }
- private void runTest() throws Exception {
- long start = System.currentTimeMillis();
- ExecutorService threadPool = Executors.newCachedThreadPool();
- for (int i = 0; i < 100; i++) {
- threadPool.submit(new AtomicIntegerArrayRunnable());
- }
- threadPool.shutdown();
- threadPool.awaitTermination(Long.MAX_VALUE, TimeUnit.MILLISECONDS);
- System.out.println("AtomicIntegerArrayRunnable in " + (System.currentTimeMillis() - start) + " millis");
- /* ======================== */
- start = System.currentTimeMillis();
- threadPool = Executors.newCachedThreadPool();
- for (int i = 0; i < 100; i++) {
- threadPool.submit(new AtomicBooleanArrayRunnable());
- }
- threadPool.shutdown();
- threadPool.awaitTermination(Long.MAX_VALUE, TimeUnit.MILLISECONDS);
- System.out.println("AtomicBooleanArrayRunnable in " + (System.currentTimeMillis() - start) + " millis");
- }
- private class AtomicIntegerArrayRunnable implements Runnable {
- @Override
- public void run() {
- for (long i = 0; i < NUM_CYCLES; i++) {
- if (i % 2 == 0) {
- array1.compareAndSet((int) (i % NUM_ATOMICS), 0, 1);
- } else {
- array1.compareAndSet((int) (i % NUM_ATOMICS), 1, 0);
- }
- }
- }
- }
- private class AtomicBooleanArrayRunnable implements Runnable {
- @Override
- public void run() {
- for (long i = 0; i < NUM_CYCLES; i++) {
- if (i % 2 == 0) {
- array2[(int) (i % NUM_ATOMICS)].compareAndSet(false, true);
- } else {
- array2[(int) (i % NUM_ATOMICS)].compareAndSet(true, false);
- }
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement