Example usage for java.util.concurrent ExecutorService execute

List of usage examples for java.util.concurrent ExecutorService execute

Introduction

In this page you can find the example usage for java.util.concurrent ExecutorService execute.

Prototype

void execute(Runnable command);

Source Link

Document

Executes the given command at some time in the future.

Usage

From source file:jcuda.jcublas.kernel.TestMultipleThreads.java

@Test
public void testMultipleThreads() throws InterruptedException {
    int numThreads = 10;
    final INDArray array = Nd4j.rand(3000, 3000);
    final INDArray expected = array.dup().mmul(array).mmul(array).div(array).div(array);
    final AtomicInteger correct = new AtomicInteger();
    final CountDownLatch latch = new CountDownLatch(numThreads);

    ExecutorService executors = Executors.newCachedThreadPool();

    for (int x = 0; x < numThreads; x++) {
        executors.execute(new Runnable() {
            @Override//from   www.j av a  2  s  .c o  m
            public void run() {
                try {
                    int total = 10;
                    int right = 0;
                    for (int x = 0; x < total; x++) {
                        StopWatch watch = new StopWatch();
                        watch.start();
                        INDArray actual = array.dup().mmul(array).mmul(array).div(array).div(array);
                        watch.stop();
                        System.out.println("MMUL took " + watch.getTime());
                        if (expected.equals(actual))
                            right++;
                    }

                    if (total == right)
                        correct.incrementAndGet();
                } finally {
                    latch.countDown();
                }

            }
        });
    }

    latch.await();

    assertEquals(numThreads, correct.get());

}

From source file:de.micromata.genome.gwiki.launcher.GWikiJettyServer.java

public void buildIndex() {

    ExecutorService executor = Executors.newFixedThreadPool(1);
    executor.execute(() -> {
        try {/*from   www .  ja v  a  2s .c om*/
            Thread.sleep(3000);
            wikibootcfg.getWikiSelector().initWiki(wikiServlet, wikibootcfg);
            int maxWait = 20;
            for (int i = 0; i < maxWait; ++i) {
                Thread.sleep(1000);
                GWikiWeb web = GWikiWeb.get();
                if (web != null) {
                    buildIndexInThread();
                    break;
                }
            }
        } catch (InterruptedException ex) {

        }

    });
}

From source file:edu.lternet.pasta.dml.download.DocumentHandler.java

public InputStream downloadDocument() throws Exception {

    log.info("starting the download");

    boolean success = true;

    final String id = docId;
    final EcogridEndPointInterface endpoint = ecogridEndPointInterface;

    ExecutorService service = Executors.newSingleThreadExecutor();
    service.execute(new Runnable() {
        public void run() {
            long startTime = System.currentTimeMillis();

            //get from the ecogrid
            try {
                if (ecogridEndPointInterface instanceof AuthenticatedEcogridEndPointInterface) {
                    AuthenticatedQueryServiceGetToStreamClient authenticatedEcogridClient = new AuthenticatedQueryServiceGetToStreamClient(
                            new URL(((AuthenticatedEcogridEndPointInterface) endpoint)
                                    .getMetacatAuthenticatedEcogridEndPoint()));
                    authenticatedEcogridClient.get(id,
                            ((AuthenticatedEcogridEndPointInterface) endpoint).getSessionId(), outputStream);
                } else {
                    QueryServiceGetToStreamClient ecogridClient = new QueryServiceGetToStreamClient(
                            new URL(endpoint.getMetacatEcogridEndPoint()));
                    ecogridClient.get(id, outputStream);
                }//from ww  w  .  j  a va  2 s  .  c  om
                outputStream.close();
                long endTime = System.currentTimeMillis();
                log.debug((endTime - startTime) + " ms to download: " + docId);
                log.debug("Done downloading id=" + id);

            } catch (Exception e) {
                log.error("Error getting document from ecogrid: " + e.getMessage());
                e.printStackTrace();
            }

        }
    });

    //wait for the download to complete
    service.shutdown();
    service.awaitTermination(0, TimeUnit.SECONDS);

    return inputStream;
}

From source file:org.wso2.carbon.identity.gateway.dao.AsyncSessionDAO.java

private AsyncSessionDAO() {

    //// ww w . j  a  v  a 2 s. c  o m
    String poolSizeConfig = "2";
    if (NumberUtils.isNumber(poolSizeConfig)) {
        poolSize = Integer.parseInt(poolSizeConfig);
        if (logger.isDebugEnabled()) {
            logger.debug("Thread pool size for Session Async DAO: " + poolSizeConfig);
        }
    }
    if (poolSize > 0) {
        ExecutorService threadPool = Executors.newFixedThreadPool(poolSize);
        for (int i = 0; i < poolSize; i++) {
            threadPool.execute(new SessionPersistenceTask(sessionJobs, persistentDAO));
        }
        threadPool = Executors.newFixedThreadPool(poolSize);
        for (int i = 0; i < poolSize; i++) {
            threadPool.execute(new SessionPersistenceTask(sessionJobs, persistentDAO));
        }
    }
}

From source file:org.wso2.carbon.identity.gateway.dao.AsyncGatewayContextDAO.java

private AsyncGatewayContextDAO() {

    ////from ww w.j  a  v a2s . co  m
    String poolSizeConfig = "2";
    if (NumberUtils.isNumber(poolSizeConfig)) {
        poolSize = Integer.parseInt(poolSizeConfig);
        if (logger.isDebugEnabled()) {
            logger.debug("Thread pool size for Session Async DAO: " + poolSizeConfig);
        }
    }
    if (poolSize > 0) {
        ExecutorService threadPool = Executors.newFixedThreadPool(poolSize);
        for (int i = 0; i < poolSize; i++) {
            threadPool.execute(new GatewayContextPersistenceTask(identityContextJobs, persistentDAO));
        }
        threadPool = Executors.newFixedThreadPool(poolSize);
        for (int i = 0; i < poolSize; i++) {
            threadPool.execute(new GatewayContextPersistenceTask(identityContextJobs, persistentDAO));
        }
    }
}

From source file:test.be.fedict.eid.applet.model.AuthenticationSignatureServiceBean.java

public PreSignResult preSign(List<X509Certificate> authnCertificateChain,
        AuthenticationSignatureContext authenticationSignatureContext) {
    LOG.debug("preSign");
    LOG.debug("authn cert chain size: " + authnCertificateChain.size());

    KeyStore proxyKeyStore;//from   www . ja v  a2  s .  c o  m
    final ProxyPrivateKey proxyPrivateKey;
    try {
        proxyKeyStore = KeyStore.getInstance("ProxyBeID");
        proxyKeyStore.load(null);
        proxyPrivateKey = (ProxyPrivateKey) proxyKeyStore.getKey("Signature", null);
    } catch (Exception e) {
        throw new RuntimeException("error loading ProxyBeID keystore");
    }

    FutureTask<String> signTask = new FutureTask<String>(new Callable<String>() {
        public String call() throws Exception {
            final Signature signature = Signature.getInstance("SHA256withRSA");
            signature.initSign(proxyPrivateKey);

            final byte[] toBeSigned = "hello world".getBytes();
            signature.update(toBeSigned);
            final byte[] signatureValue = signature.sign();
            LOG.debug("received signature value");
            return "signature result";
        }

    });
    final ExecutorService executor = Executors.newFixedThreadPool(1);
    executor.execute(signTask);

    authenticationSignatureContext.store("key", proxyPrivateKey);
    authenticationSignatureContext.store("signTask", signTask);

    byte[] digestValue;
    try {
        digestValue = proxyPrivateKey.getDigestInfo().getDigestValue();
    } catch (InterruptedException e) {
        throw new RuntimeException("signature error: " + e.getMessage(), e);
    }
    DigestInfo digestInfo = new DigestInfo(digestValue, "SHA-256", "WS-Security message");
    PreSignResult preSignResult = new PreSignResult(digestInfo, true);
    return preSignResult;
}

From source file:pl.bristleback.server.bristle.message.akka.SingleThreadMessageDispatcher.java

@Override
public void startDispatching() {
    if (dispatcherRunning) {
        throw new IllegalStateException("Dispatcher already running.");
    }/*from w ww .  j a  v a  2s.  c  o m*/
    log.info("Starting single threaded message dispatcher");
    ActorSystem system = ActorSystem.create("BristlebackSystem");
    sendMessageActor = system.actorOf(new Props(new UntypedActorFactory() {
        public UntypedActor create() {
            return new SendMessageActor(getServer());
        }
    }), "MessageDispatcherActor");
    ExecutorService executorService = Executors.newSingleThreadExecutor();
    setDispatcherRunning(true);
    executorService.execute(new Dispatcher());
}

From source file:it.infn.ct.futuregateway.apiserver.inframanager.state.Ready.java

@Override
public final void action(final ExecutorService anExecutorService, final BlockingQueue<Task> aBlockingQueue,
        final Storage aStorage) {
    if (this.task.getNativeId() == null) {
        anExecutorService.execute(new Submitter(this.task, aStorage));
        this.log.debug("Submitted the task: " + this.task.getId());
    } else {//w w  w. ja v a  2  s  . c o m
        this.task.setState(Task.STATE.SCHEDULED);
    }
}

From source file:org.sdw.mapping.RMLmapper.java

/**
 * Calls the interface's execute method with params set
 * @param config : Config of the dataset
 *///from www.  j ava2  s. c o  m
public void parallelExecutor(Configuration config, int numThreads) {
    ExecutorService executor = Executors.newCachedThreadPool();
    for (int i = 0; i < numThreads; i++) {
        executor.execute(new Runnable() {
            @Override
            public void run() {
                execute(config.getString("sourceFile"), config.getString("mappingFile"),
                        config.getString("outputFile"));
            }
        });
    }
}

From source file:org.pircbotx.hooks.managers.ThreadedListenerManager.java

protected void submitEvent(ExecutorService pool, final Listener listener, final Event event) {
    pool.execute(new ManagedFutureTask(listener, event, new Callable<Void>() {
        public Void call() {
            try {
                if (event.getBot() != null)
                    Utils.addBotToMDC(event.getBot());
                listener.onEvent(event);
            } catch (Throwable e) {
                getExceptionHandler().onException(listener, event, e);
            }/*from   w  ww  .  j  a  v  a 2 s. com*/
            return null;
        }
    }));
}