Search in sources :

Example 91 with Future

use of java.util.concurrent.Future in project atlas by alibaba.

the class Main method processAllFiles.

/**
     * Constructs the output {@link DexFile}, fill it in with all the
     * specified classes, and populate the resources map if required.
     *
     * @return whether processing was successful
     */
private boolean processAllFiles() {
    createDexFile();
    if (args.jarOutput) {
        outputResources = new TreeMap<String, byte[]>();
    }
    anyFilesProcessed = false;
    String[] fileNames = args.fileNames;
    if (args.numThreads > 1) {
        threadPool = Executors.newFixedThreadPool(args.numThreads);
        parallelProcessorFutures = new ArrayList<Future<Void>>();
    }
    try {
        if (args.mainDexListFile != null) {
            // with --main-dex-list
            FileNameFilter mainPassFilter = args.strictNameCheck ? new MainDexListFilter() : new BestEffortMainDexListFilter();
            // forced in main dex
            for (int i = 0; i < fileNames.length; i++) {
                processOne(fileNames[i], mainPassFilter);
            }
            if (dexOutputArrays.size() > 0) {
                throw new DexException("Too many classes in " + Arguments.MAIN_DEX_LIST_OPTION + ", main dex capacity exceeded");
            }
            if (args.minimalMainDex) {
                // start second pass directly in a secondary dex file.
                createDexFile();
            }
            // remaining files
            for (int i = 0; i < fileNames.length; i++) {
                processOne(fileNames[i], new NotFilter(mainPassFilter));
            }
        } else {
            // without --main-dex-list
            for (int i = 0; i < fileNames.length; i++) {
                processOne(fileNames[i], ClassPathOpener.acceptAll);
            }
        }
    } catch (StopProcessing ex) {
    /*
             * Ignore it and just let the error reporting do
             * their things.
             */
    }
    if (args.numThreads > 1) {
        try {
            threadPool.shutdown();
            if (!threadPool.awaitTermination(600L, TimeUnit.SECONDS)) {
                throw new RuntimeException("Timed out waiting for threads.");
            }
        } catch (InterruptedException ex) {
            threadPool.shutdownNow();
            throw new RuntimeException("A thread has been interrupted.");
        }
        try {
            for (Future<?> future : parallelProcessorFutures) {
                future.get();
            }
        } catch (ExecutionException e) {
            Throwable cause = e.getCause();
            // should remain
            if (cause instanceof Error) {
                throw (Error) e.getCause();
            } else {
                throw new AssertionError(e.getCause());
            }
        } catch (InterruptedException e) {
            // any InterruptedException
            throw new AssertionError(e);
        }
    }
    int errorNum = errors.get();
    if (errorNum != 0) {
        dxConsole.err.println(errorNum + " error" + ((errorNum == 1) ? "" : "s") + "; aborting");
        return false;
    }
    if (args.incremental && !anyFilesProcessed) {
        return true;
    }
    if (!(anyFilesProcessed || args.emptyOk)) {
        dxConsole.err.println("no classfiles specified");
        return false;
    }
    if (args.optimize && args.statistics) {
        args.cfOptions.codeStatistics.dumpStatistics(dxConsole.out);
    }
    return true;
}
Also used : DexException(com.taobao.android.dex.DexException) CstString(com.taobao.android.dx.rop.cst.CstString) Future(java.util.concurrent.Future) ExecutionException(java.util.concurrent.ExecutionException) FileNameFilter(com.taobao.android.dx.cf.direct.ClassPathOpener.FileNameFilter)

Example 92 with Future

use of java.util.concurrent.Future in project javaee7-samples by javaee-samples.

the class TestMultipleInterfaceServlet method processRequest.

/**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    try (PrintWriter out = response.getWriter()) {
        out.println("<html>");
        out.println("<head>");
        out.println("<title>Creating contextual proxy (with multiple interfaces)</title>");
        out.println("</head>");
        out.println("<body>");
        out.println("<h1>Creating contextual proxy (with multiple interfaces)</h1>");
        Object proxy = service.createContextualProxy(new MyRunnableWork(), Runnable.class, MyWork.class);
        out.println("Calling MyWork interface<br>");
        ((MyWork) proxy).myWork();
        out.println("Creating Java SE style ExecutorService<br>");
        ExecutorService executor = Executors.newFixedThreadPool(10, factory);
        out.println("Submitting the task<br>");
        Future f = executor.submit((Runnable) proxy);
        out.println("done<br><br>");
        out.println("Check server.log for output from the task.");
        out.println("</body>");
        out.println("</html>");
    }
}
Also used : ExecutorService(java.util.concurrent.ExecutorService) Future(java.util.concurrent.Future) PrintWriter(java.io.PrintWriter)

Example 93 with Future

use of java.util.concurrent.Future in project hibernate-orm by hibernate.

the class ConcurrentWriteTest method testManyUsers.

// Ignoring the test as it's more of a stress-test: this should be enabled manually
@Ignore
@Test
public void testManyUsers() throws Throwable {
    try {
        // setup - create users
        for (int i = 0; i < USER_COUNT; i++) {
            Customer customer = createCustomer(0);
            getCustomerIDs().add(customer.getId());
        }
        assertEquals("failed to create enough Customers", USER_COUNT, getCustomerIDs().size());
        final ExecutorService executor = Executors.newFixedThreadPool(USER_COUNT);
        CyclicBarrier barrier = new CyclicBarrier(USER_COUNT + 1);
        List<Future<Void>> futures = new ArrayList<Future<Void>>(USER_COUNT);
        for (Integer customerId : getCustomerIDs()) {
            Future<Void> future = executor.submit(new UserRunner(customerId, barrier));
            futures.add(future);
            // rampup
            Thread.sleep(LAUNCH_INTERVAL_MILLIS);
        }
        // wait for all threads to finish
        barrier.await(2, TimeUnit.MINUTES);
        log.info("All threads finished, let's shutdown the executor and check whether any exceptions were reported");
        for (Future<Void> future : futures) {
            future.get();
        }
        executor.shutdown();
        log.info("All future gets checked");
    } catch (Throwable t) {
        log.error("Error running test", t);
        throw t;
    }
}
Also used : Customer(org.hibernate.test.cache.infinispan.functional.entities.Customer) ExecutorService(java.util.concurrent.ExecutorService) ArrayList(java.util.ArrayList) Future(java.util.concurrent.Future) CyclicBarrier(java.util.concurrent.CyclicBarrier) Ignore(org.junit.Ignore) Test(org.junit.Test)

Example 94 with Future

use of java.util.concurrent.Future in project hibernate-orm by hibernate.

the class VersionedTest method testCollectionUpdate.

@Test
public void testCollectionUpdate() throws Exception {
    // the first insert puts VersionedEntry(null, null, timestamp), so we have to wait a while to cache the entry
    TIME_SERVICE.advance(1);
    withTxSession(s -> {
        Item item = s.load(Item.class, itemId);
        OtherItem otherItem = new OtherItem();
        otherItem.setName("Other 1");
        s.persist(otherItem);
        item.addOtherItem(otherItem);
    });
    withTxSession(s -> {
        Item item = s.load(Item.class, itemId);
        Set<OtherItem> otherItems = item.getOtherItems();
        assertFalse(otherItems.isEmpty());
        otherItems.remove(otherItems.iterator().next());
    });
    AdvancedCache collectionCache = ((BaseTransactionalDataRegion) sessionFactory().getSecondLevelCacheRegion(Item.class.getName() + ".otherItems")).getCache();
    CountDownLatch putFromLoadLatch = new CountDownLatch(1);
    AtomicBoolean committing = new AtomicBoolean(false);
    CollectionUpdateTestInterceptor collectionUpdateTestInterceptor = new CollectionUpdateTestInterceptor(putFromLoadLatch);
    AnotherCollectionUpdateTestInterceptor anotherInterceptor = new AnotherCollectionUpdateTestInterceptor(putFromLoadLatch, committing);
    collectionCache.addInterceptor(collectionUpdateTestInterceptor, collectionCache.getInterceptorChain().size() - 1);
    collectionCache.addInterceptor(anotherInterceptor, 0);
    TIME_SERVICE.advance(1);
    Future<Boolean> addFuture = executor.submit(() -> withTxSessionApply(s -> {
        collectionUpdateTestInterceptor.updateLatch.await();
        Item item = s.load(Item.class, itemId);
        OtherItem otherItem = new OtherItem();
        otherItem.setName("Other 2");
        s.persist(otherItem);
        item.addOtherItem(otherItem);
        committing.set(true);
        return true;
    }));
    Future<Boolean> readFuture = executor.submit(() -> withTxSessionApply(s -> {
        Item item = s.load(Item.class, itemId);
        assertTrue(item.getOtherItems().isEmpty());
        return true;
    }));
    addFuture.get();
    readFuture.get();
    collectionCache.removeInterceptor(CollectionUpdateTestInterceptor.class);
    collectionCache.removeInterceptor(AnotherCollectionUpdateTestInterceptor.class);
    withTxSession(s -> assertFalse(s.load(Item.class, itemId).getOtherItems().isEmpty()));
}
Also used : BaseTransactionalDataRegion(org.hibernate.cache.infinispan.impl.BaseTransactionalDataRegion) Arrays(java.util.Arrays) VersionedEntry(org.hibernate.cache.infinispan.util.VersionedEntry) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Session(org.hibernate.Session) Caches(org.hibernate.cache.infinispan.util.Caches) AtomicReference(java.util.concurrent.atomic.AtomicReference) Future(java.util.concurrent.Future) PessimisticLockException(org.hibernate.PessimisticLockException) InvocationContext(org.infinispan.context.InvocationContext) AdvancedCache(org.infinispan.AdvancedCache) Map(java.util.Map) BiConsumer(java.util.function.BiConsumer) Item(org.hibernate.test.cache.infinispan.functional.entities.Item) OtherItem(org.hibernate.test.cache.infinispan.functional.entities.OtherItem) Synchronization(javax.transaction.Synchronization) StaleStateException(org.hibernate.StaleStateException) CyclicBarrier(java.util.concurrent.CyclicBarrier) ByRef(org.infinispan.commons.util.ByRef) Set(java.util.Set) Assert.assertTrue(org.junit.Assert.assertTrue) Test(org.junit.Test) Assert.assertNotEquals(org.junit.Assert.assertNotEquals) TimeUnit(java.util.concurrent.TimeUnit) CountDownLatch(java.util.concurrent.CountDownLatch) List(java.util.List) BaseCustomInterceptor(org.infinispan.interceptors.base.BaseCustomInterceptor) Assert.assertNull(org.junit.Assert.assertNull) Flag(org.infinispan.context.Flag) Assert.assertFalse(org.junit.Assert.assertFalse) PutKeyValueCommand(org.infinispan.commands.write.PutKeyValueCommand) Collections(java.util.Collections) Assert.assertEquals(org.junit.Assert.assertEquals) SharedSessionContractImplementor(org.hibernate.engine.spi.SharedSessionContractImplementor) Item(org.hibernate.test.cache.infinispan.functional.entities.Item) OtherItem(org.hibernate.test.cache.infinispan.functional.entities.OtherItem) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) OtherItem(org.hibernate.test.cache.infinispan.functional.entities.OtherItem) BaseTransactionalDataRegion(org.hibernate.cache.infinispan.impl.BaseTransactionalDataRegion) AdvancedCache(org.infinispan.AdvancedCache) CountDownLatch(java.util.concurrent.CountDownLatch) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Test(org.junit.Test)

Example 95 with Future

use of java.util.concurrent.Future in project java-design-patterns by iluwatar.

the class SingletonTest method testMultipleCallsReturnTheSameObjectInDifferentThreads.

/**
   * Test singleton instance in a concurrent setting
   */
@Test(timeout = 10000)
public void testMultipleCallsReturnTheSameObjectInDifferentThreads() throws Exception {
    // Create 10000 tasks and inside each callable instantiate the singleton class
    final List<Callable<S>> tasks = new ArrayList<>();
    for (int i = 0; i < 10000; i++) {
        tasks.add(this.singletonInstanceMethod::get);
    }
    // Use up to 8 concurrent threads to handle the tasks
    final ExecutorService executorService = Executors.newFixedThreadPool(8);
    final List<Future<S>> results = executorService.invokeAll(tasks);
    // wait for all of the threads to complete
    final S expectedInstance = this.singletonInstanceMethod.get();
    for (Future<S> res : results) {
        final S instance = res.get();
        assertNotNull(instance);
        assertSame(expectedInstance, instance);
    }
    // tidy up the executor
    executorService.shutdown();
}
Also used : ArrayList(java.util.ArrayList) ExecutorService(java.util.concurrent.ExecutorService) Future(java.util.concurrent.Future) Callable(java.util.concurrent.Callable) Test(org.junit.Test)

Aggregations

Future (java.util.concurrent.Future)1138 ArrayList (java.util.ArrayList)479 ExecutorService (java.util.concurrent.ExecutorService)445 Test (org.junit.Test)413 ExecutionException (java.util.concurrent.ExecutionException)264 Callable (java.util.concurrent.Callable)206 IOException (java.io.IOException)177 ParallelTest (com.hazelcast.test.annotation.ParallelTest)148 QuickTest (com.hazelcast.test.annotation.QuickTest)148 HashMap (java.util.HashMap)92 List (java.util.List)84 CountDownLatch (java.util.concurrent.CountDownLatch)71 LinkedList (java.util.LinkedList)67 TimeoutException (java.util.concurrent.TimeoutException)63 HashSet (java.util.HashSet)62 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)59 Map (java.util.Map)58 ICompletableFuture (com.hazelcast.core.ICompletableFuture)57 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)53 File (java.io.File)46