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

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

Introduction

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

Prototype

@HotSpotIntrinsicCandidate
public final native void notifyAll();

Source Link

Document

Wakes up all threads that are waiting on this object's monitor.

Usage

From source file:com.netflix.curator.framework.recipes.locks.TestInterProcessSemaphore.java

@Test
public void testMaxPerSession() throws Exception {
    final int CLIENT_QTY = 10;
    final int LOOP_QTY = 100;
    final Random random = new Random();
    final int SESSION_MAX = random.nextInt(75) + 25;

    List<Future<Object>> futures = Lists.newArrayList();
    ExecutorService service = Executors.newCachedThreadPool();
    final Counter counter = new Counter();
    final AtomicInteger available = new AtomicInteger(SESSION_MAX);
    for (int i = 0; i < CLIENT_QTY; ++i) {
        futures.add(service.submit(new Callable<Object>() {
            @Override//  ww w .  j  a v a 2s  . co  m
            public Object call() throws Exception {
                CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(),
                        new RetryOneTime(1));
                client.start();
                try {
                    InterProcessSemaphoreV2 semaphore = new InterProcessSemaphoreV2(client, "/test",
                            SESSION_MAX);

                    for (int i = 0; i < LOOP_QTY; ++i) {
                        long start = System.currentTimeMillis();
                        int thisQty;
                        synchronized (available) {
                            if ((System.currentTimeMillis() - start) > 10000) {
                                throw new TimeoutException();
                            }
                            while (available.get() == 0) {
                                available.wait(10000);
                            }

                            thisQty = (available.get() > 1) ? (random.nextInt(available.get()) + 1) : 1;

                            available.addAndGet(-1 * thisQty);
                            Assert.assertTrue(available.get() >= 0);
                        }
                        Collection<Lease> leases = semaphore.acquire(thisQty, 10, TimeUnit.SECONDS);
                        Assert.assertNotNull(leases);
                        try {
                            synchronized (counter) {
                                counter.currentCount += thisQty;
                                if (counter.currentCount > counter.maxCount) {
                                    counter.maxCount = counter.currentCount;
                                }
                            }
                            Thread.sleep(random.nextInt(25));
                        } finally {
                            synchronized (counter) {
                                counter.currentCount -= thisQty;
                            }
                            semaphore.returnAll(leases);
                            synchronized (available) {
                                available.addAndGet(thisQty);
                                available.notifyAll();
                            }
                        }
                    }
                } finally {
                    client.close();
                }
                return null;
            }
        }));
    }

    for (Future<Object> f : futures) {
        f.get();
    }

    synchronized (counter) {
        Assert.assertTrue(counter.currentCount == 0);
        Assert.assertTrue(counter.maxCount > 0);
        Assert.assertTrue(counter.maxCount <= SESSION_MAX);
        System.out.println(counter.maxCount);
    }
}

From source file:org.jspresso.hrsample.backend.JspressoUnitOfWorkTest.java

/**
 * Tests in TX collection element update with // optimistic locking.
 *//*from   ww w  . j av  a2  s .c  o m*/
@Test
public void testInTXCollectionElementUpdate() {
    final HibernateBackendController hbc = (HibernateBackendController) getBackendController();

    final AtomicInteger countDown = new AtomicInteger(10);
    ExecutorService es = Executors.newFixedThreadPool(countDown.get());
    List<Future<Set<String>>> futures = new ArrayList<Future<Set<String>>>();
    for (int t = countDown.intValue(); t > 0; t--) {
        futures.add(es.submit(new Callable<Set<String>>() {

            @Override
            public Set<String> call() throws Exception {
                final HibernateBackendController threadHbc = getApplicationContext()
                        .getBean("applicationBackController", HibernateBackendController.class);
                final TransactionTemplate threadTT = threadHbc.getTransactionTemplate();
                threadHbc.start(hbc.getLocale(), hbc.getClientTimeZone());
                threadHbc.setApplicationSession(hbc.getApplicationSession());
                BackendControllerHolder.setThreadBackendController(threadHbc);
                return threadTT.execute(new TransactionCallback<Set<String>>() {

                    /**
                     * {@inheritDoc}
                     */
                    @Override
                    public Set<String> doInTransaction(TransactionStatus status) {
                        DetachedCriteria compCrit = DetachedCriteria.forClass(Company.class);
                        Set<String> names = new HashSet<String>();
                        Company c = (Company) compCrit.getExecutableCriteria(threadHbc.getHibernateSession())
                                .list().iterator().next();

                        synchronized (countDown) {
                            countDown.decrementAndGet();
                            // wait for all threads to arrive here so that we are sure they
                            // have all read the same data.
                            try {
                                countDown.wait();
                            } catch (InterruptedException ex) {
                                throw new BackendException("Test has been interrupted");
                            }
                        }

                        if (c.getName().startsWith("TX_")) {
                            throw new BackendException("Wrong data read from DB");
                        }
                        c.setName("TX_" + Long.toHexString(System.currentTimeMillis()));
                        names.add(c.getName());
                        for (Department d : c.getDepartments()) {
                            d.setName(Long.toHexString(System.currentTimeMillis()));
                            names.add(d.getName());
                        }
                        return names;
                    }
                });
            }
        }));
    }
    while (countDown.get() > 0) {
        try {
            Thread.sleep(200);
        } catch (InterruptedException ex) {
            throw new BackendException("Test has been interrupted");
        }
    }
    synchronized (countDown) {
        countDown.notifyAll();
    }
    int successfullTxCount = 0;
    Set<String> names = new HashSet<String>();
    for (Future<Set<String>> f : futures) {
        try {
            names = f.get();
            successfullTxCount++;
        } catch (Exception ex) {
            if (ex.getCause() instanceof OptimisticLockingFailureException) {
                // safely ignore since this is what we are testing.
            } else {
                throw new BackendException(ex);
            }
        }
    }
    es.shutdown();
    assertTrue("Only 1 TX succeeded", successfullTxCount == 1);

    DetachedCriteria compCrit = DetachedCriteria.forClass(Company.class);
    Company c = hbc.findFirstByCriteria(compCrit, EMergeMode.MERGE_LAZY, Company.class);
    assertTrue("the company name is the one of the successfull TX", names.contains(c.getName()));
    for (Department d : c.getDepartments()) {
        assertTrue("the department name is the one of the successfull TX", names.contains(d.getName()));
    }
}