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

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

Introduction

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

Prototype

public AtomicInteger(int initialValue) 

Source Link

Document

Creates a new AtomicInteger with the given initial value.

Usage

From source file:com.khartec.waltz.jobs.sample.MeasurablesGenerator.java

private static void generateRegions(DSLContext dsl) throws IOException {
    List<String> lines = readLines(OrgUnitGenerator.class.getResourceAsStream("/regions.csv"));

    System.out.println("Deleting existing Regions & Countries ...");
    int deletedCount = dsl.deleteFrom(MEASURABLE)
            .where(MEASURABLE.MEASURABLE_CATEGORY_ID
                    .in(DSL.select(MEASURABLE_CATEGORY.ID).from(MEASURABLE_CATEGORY)
                            .where(MEASURABLE_CATEGORY.EXTERNAL_ID.eq(REGION_CATEGORY_EXTERNAL_ID))))
            .and(MEASURABLE.PROVENANCE.eq("demo")).execute();
    System.out.println("Deleted: " + deletedCount + " existing Regions & Countries");

    Map<String, Map<String, Set<String>>> regionHierarchy = lines.stream().skip(1)
            .map(line -> StringUtils.splitPreserveAllTokens(line, ","))
            .filter(cells -> notEmpty(cells[0]) && notEmpty(cells[6]) && notEmpty(cells[5]))
            .map(cells -> Tuple.tuple(cells[0], cells[6], cells[5]))
            .collect(groupingBy(t -> t.v3, groupingBy(t -> t.v2, mapping(t -> t.v1, toSet()))));

    final long measurableCategoryId = dsl.select(MEASURABLE_CATEGORY.ID).from(MEASURABLE_CATEGORY)
            .where(MEASURABLE_CATEGORY.EXTERNAL_ID.eq(REGION_CATEGORY_EXTERNAL_ID)).fetchAny().value1();

    AtomicInteger insertCount = new AtomicInteger(0);
    regionHierarchy.forEach((region, subRegionMap) -> {
        final long regionId = dsl.insertInto(MEASURABLE)
                .set(createRegion(null, region, measurableCategoryId, false)).returning(MEASURABLE.ID)
                .fetchOne().getId();//  ww  w  . j a v  a2  s . c  om
        insertCount.incrementAndGet();

        subRegionMap.forEach((subRegion, countries) -> {
            final long subRegionId = dsl.insertInto(MEASURABLE)
                    .set(createRegion(regionId, subRegion, measurableCategoryId, true)).returning(MEASURABLE.ID)
                    .fetchOne().getId();
            insertCount.incrementAndGet();

            insertCount.addAndGet(dsl.batchInsert(countries.stream()
                    .map(country -> createRegion(subRegionId, country, measurableCategoryId, true))
                    .collect(toList())).execute().length);
        });
    });

    System.out.println("Inserted: " + insertCount + " Regions & Countries");
}

From source file:com.kakao.kakaolink.KakaoTalkLinkMessageBuilder.java

KakaoTalkLinkMessageBuilder(final String appKey, final String appVer, final JSONObject extra) {
    this.appKey = appKey;
    this.appVer = appVer;
    this.extra = extra;

    this.textType = new AtomicInteger(0);
    this.imageType = new AtomicInteger(0);
    this.buttonType = new AtomicInteger(0);
    this.linkType = new AtomicInteger(0);

    this.linkObjList = new ArrayList<LinkObject>();
}

From source file:com.rationaldevelopers.oss.service.CacheService.java

@Scheduled(fixedRate = 60000)
public void trueUpCache() {
    if (!lock.isLocked()) {
        lock.lock();//from   ww w.  j  av  a  2  s  .co  m
        try {
            LOGGER.info("Running Timed Task");
            final Iterable<SimpleItem> all = simpleItemService.findAll();
            final AtomicInteger itemsUpdated = new AtomicInteger(0);
            StreamSupport.stream(all.spliterator(), false).filter(i -> !cache.containsKey(i.getSid())
                    || cache.containsKey(i.getSid()) && !cache.get(i.getSid()).equals(i)).forEach(i -> {
                        cache.put(i.getSid(), i);
                        itemsUpdated.incrementAndGet();
                    });
            LOGGER.info("Total Items Updated: {}", itemsUpdated.get());
        } finally {
            lock.unlock();
        }
    }
}

From source file:com.epam.reportportal.auth.event.UiAuthenticationFailureEventHandler.java

public UiAuthenticationFailureEventHandler() {
    super();/*from w w  w . jav  a2  s  .  c  o  m*/
    failures = CacheBuilder.newBuilder().maximumSize(MAXIMUM_SIZE)
            .expireAfterWrite(EXPIRATION_SECONDS, TimeUnit.SECONDS)
            .build(new CacheLoader<String, AtomicInteger>() {
                @Override
                public AtomicInteger load(String key) {
                    return new AtomicInteger(0);
                }
            });
}

From source file:org.jtheque.errors.ErrorServiceTest.java

@Test
@DirtiesContext//from ww w .  j  a v a 2s  .co  m
public void listenerRemoved() {
    final AtomicInteger integer = new AtomicInteger(0);

    ErrorListener listener = new ErrorListener() {
        @Override
        public void errorOccurred(Error occuredError) {
            integer.incrementAndGet();
        }
    };

    errorService.addErrorListener(listener);

    errorService.addError(Errors.newError("Test1"));

    errorService.removeErrorListener(listener);

    errorService.addError(Errors.newError("Test2"));

    assertEquals(1, integer.intValue());
}

From source file:com.github.gdrouet.scannerbenchmark.JmhBenchmark.java

/**
 * <p>/*  w  w  w  .ja  va2  s.  co  m*/
 * Looking for type annotated with an annotation with annotation-detector.
 * </p>
 *
 * @throws Exception if test fails
 */
@Benchmark
public void scanAnnotatedTypeWithAnnotationDetector() throws Exception {
    final AtomicInteger count = new AtomicInteger(0);
    final AnnotationDetector.TypeReporter typeReporter = new AnnotationDetector.TypeReporter() {
        @Override
        public void reportTypeAnnotation(final Class<? extends Annotation> annotation, final String className) {
            count.incrementAndGet();
        }

        @SuppressWarnings("unchecked")
        @Override
        public Class<? extends Annotation>[] annotations() {
            return new Class[] { ANNOTATION };
        }
    };

    final AnnotationDetector cf = new AnnotationDetector(typeReporter);
    cf.detect(PACKAGE);
    LOGGER.info("{} classes annotated with {} retrieved with Annotation-Detector", count.get(),
            ANNOTATION.getName());
}

From source file:de.thischwa.pmcms.livecycle.SiteHolder.java

public void clear() {
    poPerID.clear();
    lastID = new AtomicInteger(0);
}

From source file:dk.statsbiblioteket.util.JobControllerTest.java

public void testPopAll() throws Exception {
    final int JOBS = 10;
    final AtomicInteger counter = new AtomicInteger(0);
    JobController<Long> controller = new JobController<Long>(10) {
        @Override/*ww w .  j a  v  a  2 s . c o m*/
        protected void afterExecute(Future<Long> finished) {
            counter.incrementAndGet();
        }
    };
    for (int i = 0; i < JOBS; i++) {
        synchronized (Thread.currentThread()) {
            Thread.currentThread().wait(10);
        }
        controller.submit(new Shout(50));
    }
    int all = controller.popAll().size();

    assertEquals("The total pops should be correct", 10, all);
    assertEquals("The callback count should be correct", 10, counter.get());
}

From source file:com.alibaba.wasp.util.KeyLocker.java

/**
 * Return a lock for the given key. The lock is already locked.
 *
 * @param key/* w w w . j a v  a 2  s .  c  om*/
 */
public ReentrantLock acquireLock(K key) {
    if (key == null)
        throw new IllegalArgumentException("key must not be null");

    Pair<KeyLock<K>, AtomicInteger> lock;
    synchronized (this) {
        lock = locks.get(key);
        if (lock == null) {
            lock = new Pair<KeyLock<K>, AtomicInteger>(new KeyLock<K>(this, key), new AtomicInteger(1));
            locks.put(key, lock);
        } else {
            lock.getSecond().incrementAndGet();
        }
    }
    lock.getFirst().lock();
    return lock.getFirst();
}

From source file:de.codesourcery.eve.skills.ui.utils.ParallelUITasksRunner.java

public static boolean submitParallelTasks(final ApplicationThreadManager threadManager, final UITask parent,
        UITask... children) {/*www.jav a2 s  .  c o m*/
    final AtomicInteger childSuccesses = new AtomicInteger(0);
    final AtomicInteger childFailures = new AtomicInteger(0);

    if (parent == null) {
        throw new IllegalArgumentException("parent task cannot be NULL");
    }

    if (ArrayUtils.isEmpty(children)) {
        throw new IllegalArgumentException("Need to provide at least one child task");
    }
    final CyclicBarrier startBarrier = new CyclicBarrier(children.length + 1) {
        @Override
        public void reset() {
            System.out.println("========== resetting start barrier =========== ");
            super.reset();
        }
    };

    final CountDownLatch childrenTerminated = new CountDownLatch(children.length);

    int submittedChildren = 0;
    for (final UITask child : children) {

        final UITask wrapped = new UITask() {

            @Override
            public void successHook() throws Exception {
                boolean success = false;
                try {
                    child.successHook();
                    success = true;
                } finally {
                    if (success) {
                        childSuccesses.incrementAndGet();
                    } else {
                        childFailures.incrementAndGet();
                    }
                    childrenTerminated.countDown();
                }
            }

            @Override
            public void beforeExecution() {
                child.beforeExecution();
                // note: when this method throws an exception , #failure() is invoked
            }

            @Override
            public void setEnabledHook(boolean yesNo) {
                child.setEnabledHook(yesNo);

            }

            @Override
            public void failureHook(Throwable t) throws Exception {
                try {
                    child.failureHook(t);
                } finally {
                    childFailures.incrementAndGet();
                    childrenTerminated.countDown();
                }
            }

            @Override
            public void cancellationHook() {
                try {
                    child.cancellationHook();
                } finally {
                    childFailures.incrementAndGet();
                    childrenTerminated.countDown();
                }
            }

            @Override
            public String getId() {
                return child.getId();
            }

            @Override
            public void run() throws Exception {
                try {
                    if (log.isTraceEnabled()) {
                        log.trace("run(): Child task " + getId() + " is now waiting.");
                    }
                    startBarrier.await(); // will BrokenBarrierException if any of the child tasks could not be started,
                } catch (InterruptedException e) {
                    log.error("run(): Child task " + getId() + " was interrupted");
                    Thread.currentThread().interrupt();
                } catch (BrokenBarrierException e) {
                    log.error("run(): Child task" + getId() + " aborted, barrier broken.");
                    throw new RuntimeException(
                            "Child task not started because another child task failed submitTask()");
                }

                if (log.isTraceEnabled()) {
                    log.trace("run(): Child task " + getId() + " is now running.");
                }
                child.run();
            }
        };

        if (null == threadManager.submitTask(wrapped, false)) {
            log.error("submitParallelTasks(): Failed to submit child " + child);

            // note: I wait for (submittedChildren-childFailures) because some 
            // child task may have already failed before reaching their run() method
            while (startBarrier.getNumberWaiting() != (submittedChildren - childFailures.get())) {
                log.info("submitParallelTasks(): Waiting for all child tasks to reach barrier ( "
                        + startBarrier.getNumberWaiting() + " waiting)");
                try {
                    java.lang.Thread.sleep(500);
                } catch (Exception e) {
                }
                ;
            }

            startBarrier.reset(); // will cause all child threads waiting on this barrier to terminate
            return false;
        }
        submittedChildren++;
    }

    /*
     * All children are submitted and waiting at the barrier.
     */
    final boolean parentSubmitted = null != threadManager.submitTask("Control thread of " + parent.getId(),
            new Runnable() {

                @Override
                public void run() {
                    try {

                        while (true) {
                            try {
                                log.debug("run(): Parent task " + parent.getId()
                                        + " is waiting for it's children to start...");
                                startBarrier.await(5, TimeUnit.SECONDS);
                                break;
                            } catch (TimeoutException e) {
                                if (childFailures.get() != 0) {
                                    runFailureHookOnEDT(parent,
                                            childFailures.get() + " child tasks of parent task "
                                                    + parent.getId() + " failed to start.");
                                    return;
                                }
                            }
                        }
                    } catch (InterruptedException e) {
                        runFailureHookOnEDT(parent, "Parent task " + parent.getId()
                                + " was interrupted while waiting" + " for it's children to start.");
                        startBarrier.reset(); // let children fail.
                        Thread.currentThread().interrupt();
                        return;
                    } catch (BrokenBarrierException e) {
                        runFailureHookOnEDT(parent,
                                "Parent task " + parent.getId() + " failed to wait for it's children");
                        throw new RuntimeException("Internal error - task " + parent.getId()
                                + " failed to wait for it's children?");
                    }

                    log.debug("run(): Task " + parent.getId() + " is waiting for it's children to finish");
                    try {
                        childrenTerminated.await();
                    } catch (InterruptedException e) {
                        Thread.currentThread().interrupt();
                        runFailureHookOnEDT(parent, "Parent task " + parent.getId()
                                + " was interrupted while waiting for it's children");
                        return;
                    }

                    log.info("run(): All children of parent task " + parent.getId()
                            + " have finished ( success: " + childSuccesses.get() + " / failure: "
                            + childFailures.get() + ")");

                    if (childFailures.get() > 0) {
                        runFailureHookOnEDT(parent, childFailures.get() + " child tasks of parent "
                                + parent.getId() + " have FAILED.");
                        return;
                    }

                    if (null == threadManager.submitTask(parent, false)) {
                        runFailureHookOnEDT(parent, "Failed to submit parent task " + parent.getId());
                        return;
                    }

                }
            }, false);

    if (!parentSubmitted) {
        log.debug("submitParallelTasks(): Failed to submit parent task " + parent.getId()
                + " , terminating child tasks.");
        startBarrier.reset(); // aborts all child tasks with a BrokenBarrierException
    }

    return parentSubmitted;
}