Example usage for java.util.concurrent.atomic AtomicLong AtomicLong

List of usage examples for java.util.concurrent.atomic AtomicLong AtomicLong

Introduction

In this page you can find the example usage for java.util.concurrent.atomic AtomicLong AtomicLong.

Prototype

public AtomicLong(long initialValue) 

Source Link

Document

Creates a new AtomicLong with the given initial value.

Usage

From source file:com.zimbra.cs.store.triton.TritonIncomingBlob.java

public TritonIncomingBlob(String id, String baseUrl, BlobBuilder blobBuilder, Object ctx, MessageDigest digest,
        HashType hashType) throws ServiceException, IOException {
    super(id, blobBuilder, ctx);
    this.digest = digest;
    this.hashType = hashType;
    this.baseUrl = baseUrl;
    serverToken = new MozyServerToken();
    uploadUrl = new TritonUploadUrl();
    written = new AtomicLong(0);
}

From source file:com.glaf.core.util.threads.LimitLatch.java

/**
 * Instantiates a LimitLatch object with an initial limit.
 * @param limit - maximum number of concurrent acquisitions of this latch
 *//* w w  w .ja v a 2s  .c  om*/
public LimitLatch(long limit) {
    this.limit = limit;
    this.count = new AtomicLong(0);
    this.sync = new Sync();
}

From source file:org.apache.hadoop.hbase.regionserver.Segment.java

protected Segment(CellSet cellSet, CellComparator comparator, MemStoreLAB memStoreLAB, long size) {
    this.cellSet = cellSet;
    this.comparator = comparator;
    this.minSequenceId = Long.MAX_VALUE;
    this.memStoreLAB = memStoreLAB;
    this.size = new AtomicLong(size);
    this.tagsPresent = false;
    this.timeRangeTracker = new TimeRangeTracker();
}

From source file:com.alibaba.simpleimage.PressureTester.java

public PressureTester(int threadsNum, long total, String rootDir) {
    this.threadsNum = threadsNum;
    this.total = new AtomicLong(total);
    this.countDownLatch = new CountDownLatch(threadsNum);
    if (StringUtils.isNotBlank(rootDir)) {
        sourceDir = new File(rootDir + "/src/test/resources/conf.test/simpleimage");
    } else {//  w w w .  java 2s  .  c o  m
        throw new IllegalArgumentException("root dir must not be null");
    }
}

From source file:org.apache.hadoop.hdfs.TestAutoEditRollWhenAvatarFailover.java

/**
 * Test if we can get block locations after killing primary avatar,
 * failing over to standby avatar (making it the new primary),
 * restarting a new standby avatar, killing the new primary avatar and
 * failing over to the restarted standby.
 * /*from   w ww  . ja  va 2 s .com*/
 * Write logs for a while to make sure automatic rolling are triggered.
 */
@Test
public void testDoubleFailOverWithAutomaticRoll() throws Exception {
    setUp(false, "testDoubleFailOverWithAutomaticRoll");

    // To make sure it's never the case that both primary and standby
    // issue rolling, we use a injection handler. 
    final AtomicBoolean startKeepThread = new AtomicBoolean(true);
    final AtomicInteger countAutoRolled = new AtomicInteger(0);
    final AtomicBoolean needFail = new AtomicBoolean(false);
    final AtomicLong currentThreadId = new AtomicLong(-1);
    final Object waitFor10Rolls = new Object();
    InjectionHandler.set(new InjectionHandler() {
        @Override
        protected void _processEvent(InjectionEventI event, Object... args) {
            if (event == InjectionEvent.FSEDIT_AFTER_AUTOMATIC_ROLL) {
                countAutoRolled.incrementAndGet();
                if (countAutoRolled.get() >= 10) {
                    synchronized (waitFor10Rolls) {
                        waitFor10Rolls.notifyAll();
                    }
                }

                if (!startKeepThread.get()) {
                    currentThreadId.set(-1);
                } else if (currentThreadId.get() == -1) {
                    currentThreadId.set(Thread.currentThread().getId());
                } else if (currentThreadId.get() != Thread.currentThread().getId()) {
                    LOG.warn("[Thread " + Thread.currentThread().getId() + "] expected: " + currentThreadId);
                    needFail.set(true);
                }

                LOG.info("[Thread " + Thread.currentThread().getId() + "] finish automatic log rolling, count "
                        + countAutoRolled.get());

                // Increase the rolling time a little bit once after 7 auto rolls 
                if (countAutoRolled.get() % 7 == 3) {
                    DFSTestUtil.waitNMilliSecond(75);
                }
            }
        }
    });

    FileSystem fs = cluster.getFileSystem();

    // Add some transactions during a period of time before failing over.
    long startTime = System.currentTimeMillis();
    for (int i = 0; i < 100; i++) {
        fs.setTimes(new Path("/"), 0, 0);
        DFSTestUtil.waitNMilliSecond(100);
        if (i % 10 == 0) {
            LOG.info("================== executed " + i + " queries");
        }
        if (countAutoRolled.get() >= 10) {
            LOG.info("Automatic rolled 10 times.");
            long duration = System.currentTimeMillis() - startTime;
            TestCase.assertTrue("Automatic rolled 10 times in just " + duration + " msecs, which is too short",
                    duration > 4500);
            break;
        }
    }
    TestCase.assertTrue("Only " + countAutoRolled + " automatic rolls triggered, which is lower than expected.",
            countAutoRolled.get() >= 10);

    // Tune the rolling timeout temporarily to avoid race conditions
    // only triggered in tests
    cluster.getPrimaryAvatar(0).avatar.namesystem.getFSImage().getEditLog().setTimeoutRollEdits(5000);
    cluster.getStandbyAvatar(0).avatar.namesystem.getFSImage().getEditLog().setTimeoutRollEdits(5000);

    LOG.info("================== killing primary 1");

    cluster.killPrimary();

    // Fail over and make sure after fail over, automatic edits roll still
    // will happen.
    countAutoRolled.set(0);
    startKeepThread.set(false);
    currentThreadId.set(-1);
    LOG.info("================== failing over 1");
    cluster.failOver();
    cluster.getPrimaryAvatar(0).avatar.namesystem.getFSImage().getEditLog().setTimeoutRollEdits(1000);
    LOG.info("================== restarting standby");
    cluster.restartStandby();
    cluster.getStandbyAvatar(0).avatar.namesystem.getFSImage().getEditLog().setTimeoutRollEdits(1000);
    LOG.info("================== Finish restarting standby");

    // Wait for automatic rolling happens if there is no new transaction.
    startKeepThread.set(true);

    startTime = System.currentTimeMillis();
    long waitDeadLine = startTime + 20000;
    synchronized (waitFor10Rolls) {
        while (System.currentTimeMillis() < waitDeadLine && countAutoRolled.get() < 10) {
            waitFor10Rolls.wait(waitDeadLine - System.currentTimeMillis());
        }
    }
    TestCase.assertTrue("Only " + countAutoRolled + " automatic rolls triggered, which is lower than expected.",
            countAutoRolled.get() >= 10);
    long duration = System.currentTimeMillis() - startTime;
    TestCase.assertTrue("Automatic rolled 10 times in just " + duration + " msecs", duration > 9000);

    // failover back 
    countAutoRolled.set(0);
    startKeepThread.set(false);
    currentThreadId.set(-1);

    cluster.getPrimaryAvatar(0).avatar.namesystem.getFSImage().getEditLog().setTimeoutRollEdits(6000);
    cluster.getStandbyAvatar(0).avatar.namesystem.getFSImage().getEditLog().setTimeoutRollEdits(6000);

    LOG.info("================== killing primary 2");
    cluster.killPrimary();
    LOG.info("================== failing over 2");
    cluster.failOver();

    cluster.getPrimaryAvatar(0).avatar.namesystem.getFSImage().getEditLog().setTimeoutRollEdits(1000);

    // Make sure after failover back, automatic rolling can still happen.
    startKeepThread.set(true);

    for (int i = 0; i < 100; i++) {
        fs.setTimes(new Path("/"), 0, 0);
        DFSTestUtil.waitNMilliSecond(200);
        if (i % 10 == 0) {
            LOG.info("================== executed " + i + " queries");
        }
        if (countAutoRolled.get() > 10) {
            LOG.info("Automatic rolled 10 times.");
            duration = System.currentTimeMillis() - startTime;
            TestCase.assertTrue("Automatic rolled 10 times in just " + duration + " msecs, which is too short",
                    duration > 9000);
            break;
        }
    }
    TestCase.assertTrue("Only " + countAutoRolled + " automatic rolls triggered, which is lower than expected.",
            countAutoRolled.get() >= 10);

    InjectionHandler.clear();

    if (needFail.get()) {
        TestCase.fail("Automatic rolling doesn't happen in the same thread when should.");
    }
}

From source file:org.alfresco.repo.cache.DefaultSimpleCache.java

/**
 * Construct a cache using the specified capacity and name.
 * /*from w w  w  .  j  av  a2  s . c  o  m*/
 * @param maxItems The cache capacity.
 */
public DefaultSimpleCache(int maxItems, final String cacheName) {
    if (maxItems < 1) {
        throw new IllegalArgumentException("maxItems must be a positive integer, but was " + maxItems);
    }

    setBeanName(cacheName);

    EvictionListener<K, AbstractMap.SimpleImmutableEntry<K, V>> listener = new EvictionListener<K, AbstractMap.SimpleImmutableEntry<K, V>>() {
        AtomicLong numEvictions = new AtomicLong(0);

        @Override
        public void onEviction(K key, AbstractMap.SimpleImmutableEntry<K, V> value) {
            float hitRatio = ((float) (hits.get())) / readAccesses.get();
            if (numEvictions.get() % 1000 == 0) {
                log.debug("Cache: " + DefaultSimpleCache.this.cacheName + " evictions: "
                        + (numEvictions.getAndIncrement()) + " hitRatio: " + hitRatio);
            }
        }
    };

    // The map will have a bounded size determined by the maxItems member variable.
    map = new ConcurrentLinkedHashMap.Builder<K, AbstractMap.SimpleImmutableEntry<K, V>>()
            .maximumWeightedCapacity(maxItems).concurrencyLevel(32).weigher(Weighers.singleton())
            .listener(listener).build();
}

From source file:org.apache.eagle.alert.engine.sorter.BaseStreamWindow.java

public BaseStreamWindow(long startTime, long endTime, long marginTime) {
    if (startTime >= endTime) {
        throw new IllegalArgumentException(
                "startTime: " + startTime + " >= endTime: " + endTime + ", expected: startTime < endTime");
    }//www .  ja v  a2s  .c om
    if (marginTime > endTime - startTime) {
        throw new IllegalArgumentException("marginTime: " + marginTime + " > endTime: " + endTime
                + " - startTime " + startTime + ", expected: marginTime < endTime - startTime");
    }
    this.startTime = startTime;
    this.endTime = endTime;
    this.margin = marginTime;
    this.expired = new AtomicBoolean(false);
    this.createdTime = System.currentTimeMillis();
    this.lastFlushedStreamTime = new AtomicLong(0);
    this.lastFlushedSystemTime = new AtomicLong(this.createdTime);
}

From source file:edu.umn.msi.tropix.client.request.actions.impl.PersistentActionManagerImpl.java

@PostConstruct
public void init() {
    final Collection<RequestAction> actions = persistentActionService.loadActions();
    long largestId = 0L;
    for (final RequestAction action : actions) {
        final long actionId = action.getActionId();
        if (actionId > largestId) {
            largestId = actionId;//from www. j  av  a2  s. c  om
        }
        execute(action);
    }
    actionCounter = new AtomicLong(largestId + 1);
    countDownLatch.countDown();
}

From source file:com.github.jackygurui.vertxredissonrepository.repository.SaveCustomerCocurrentTest.java

@Test
public void test3SaveCustomerConcurrent(TestContext context) throws Exception {
    Async async = context.async();//ww  w .  jav a2  s  . co m
    JsonNode source = JsonLoader.fromResource("/Customer.json");
    int records = 10000;
    HanyuPinyin.convert("");//warm up
    AtomicLong c = new AtomicLong(0);
    StopWatch sw = new StopWatch();
    sw.start();
    IntStream.rangeClosed(1, records).parallel().forEach(e -> {
        JsonObject clone = new JsonObject(Json.encode(source));
        clone.getJsonObject("personalDetails").put("phoneNumber",
                ((Long.parseLong(clone.getJsonObject("personalDetails").getString("phoneNumber")) + 100 + e)
                        + ""));
        customerRepository.create(Json.encode(clone), r -> {
            AsyncResult<String> result = (AsyncResult<String>) r;
            if (result.failed()) {
                context.fail(result.cause());
                async.complete();
            }
            if (c.incrementAndGet() == records) {
                sw.stop();
                logger.info("time to concurrently save " + records + " customer records: " + sw.getTime());
                async.complete();
            }
        });
    });
}

From source file:org.apache.hadoop.hbase.loadtest.MultiThreadedWriter.java

public void start(long startKey, long endKey, int numThreads) {
    this.startKey = startKey;
    this.endKey = endKey;
    this.numThreads = numThreads;
    currentKey_ = new AtomicLong(this.startKey);

    if (getVerbose()) {
        LOG.debug("Inserting keys [" + this.startKey + ", " + this.endKey + ")");
    }//  www . j  a  va  2s.  c o m

    for (int i = 0; i < this.numThreads; ++i) {
        HBaseWriter writer = new HBaseWriter(this, i);
        writers_.add(writer);
    }
    numThreadsWorking.addAndGet(writers_.size());
    for (HBaseWriter writer : writers_) {
        writer.start();
    }
    startReporter("W");
}