Example usage for java.util.concurrent Executor execute

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

Introduction

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

Prototype

void execute(Runnable command);

Source Link

Document

Executes the given command at some time in the future.

Usage

From source file:py.una.pol.karaku.services.client.WSCaller.java

/**
 * Invoca al servicio definido en <code>info</code>, la invocacin se
 * realiza en otro hilo, encapsula todos los
 * {@link WebServiceMessageCallback} definidos en
 * {@link WSSecurityInterceptor#getWebServiceMessageCallback(Info)} para
 * agregar la seguridad.//from  w ww.  ja v a  2  s.  co m
 * <p>
 * Este mtodo es el punto de acceso a todos los servicios de Karaku.
 * </p>
 * 
 * @param request
 *            objeto que ser serializado para realizar la invocacin
 * @param info
 *            informacin acerca del servicio.
 * @param callBack
 *            callBack que ser invocado cuando se reciba la llamada del
 *            servicio.
 */
public <T> void call(final Executor executor, final Object request, final Info info,
        final WSCallBack<T> callBack) {

    if (callBack == null) {
        throw new IllegalArgumentException("CallBack no puede ser nulo");
    }

    executor.execute(new Runnable() {

        @Override
        @SuppressWarnings("unchecked")
        public void run() {

            try {
                log.trace("Calling WebService with uri {}", info.getUrl());
                WebServiceMessageCallback wsmc = interceptor.getWebServiceMessageCallback(info);

                T toRet = (T) template.marshalSendAndReceive(info.getUrl(), request, wsmc);
                log.trace("Web service call ended");
                callBack.onSucess(toRet);
            } catch (Exception e) {
                log.debug("Error in ws", e);
                callBack.onFailure(e);
            }
        }
    });

}

From source file:org.apache.druid.server.initialization.JettyTest.java

@Test
@Ignore // this test will deadlock if it hits an issue, so ignored by default
public void testTimeouts() throws Exception {
    // test for request timeouts properly not locking up all threads
    final Executor executor = Executors.newFixedThreadPool(100);
    final AtomicLong count = new AtomicLong(0);
    final CountDownLatch latch = new CountDownLatch(1000);
    for (int i = 0; i < 10000; i++) {
        executor.execute(new Runnable() {
            @Override//from   ww w  .j  av  a 2s .  c o  m
            public void run() {
                executor.execute(new Runnable() {
                    @Override
                    public void run() {
                        long startTime = System.currentTimeMillis();
                        long startTime2 = 0;
                        try {
                            ListenableFuture<StatusResponseHolder> go = client.go(
                                    new Request(HttpMethod.GET,
                                            new URL("http://localhost:" + port + "/slow/hello")),
                                    new StatusResponseHandler(Charset.defaultCharset()));
                            startTime2 = System.currentTimeMillis();
                            go.get();
                        } catch (Exception e) {
                            e.printStackTrace();
                        } finally {
                            System.out.printf(Locale.ENGLISH,
                                    "Response time client%dtime taken for getting future%dCounter %d%n",
                                    System.currentTimeMillis() - startTime,
                                    System.currentTimeMillis() - startTime2, count.incrementAndGet());
                            latch.countDown();

                        }
                    }
                });
            }
        });
    }

    latch.await();
}

From source file:com.tanmay.blip.networking.XKCDDownloader.java

private void redownloadLastTen() {
    final Gson gson = new Gson();
    final DatabaseManager databaseManager = new DatabaseManager(this);
    try {/*  w  w w. j av  a2 s . c  om*/
        Request todayReq = new Request.Builder().url(LATEST_URL).build();
        Response response = BlipApplication.getInstance().client.newCall(todayReq).execute();
        if (!response.isSuccessful())
            throw new IOException();
        Comic comic = gson.fromJson(response.body().string(), Comic.class);
        final CountDownLatch latch = new CountDownLatch(10);
        final Executor executor = Executors.newFixedThreadPool(5);
        int num = comic.getNum();
        for (int i = num - 9; i <= num; i++) {
            final int index = i;
            executor.execute(new Runnable() {
                @Override
                public void run() {
                    try {
                        String url = String.format(COMICS_URL, index);
                        Request request = new Request.Builder().url(url).build();
                        Response response = BlipApplication.getInstance().client.newCall(request).execute();
                        if (!response.isSuccessful())
                            throw new IOException();
                        String responseBody = response.body().string();
                        Comic comic = null;
                        try {
                            comic = gson.fromJson(responseBody, Comic.class);
                        } catch (JsonSyntaxException e) {
                            Crashlytics.log(1, "XKCDDownloader", e.getMessage() + " POS:" + index);
                        }
                        if (comic != null) {
                            if (databaseManager.comicExists(comic)) {
                                databaseManager.updateComic(comic);
                            } else {
                                databaseManager.addComic(comic);
                            }
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                        LocalBroadcastManager.getInstance(XKCDDownloader.this)
                                .sendBroadcast(new Intent(DOWNLOAD_FAIL));
                    } finally {
                        latch.countDown();
                    }
                }
            });
        }

        try {
            latch.await();
        } catch (InterruptedException e) {
            LocalBroadcastManager.getInstance(XKCDDownloader.this).sendBroadcast(new Intent(DOWNLOAD_FAIL));
        }

        SharedPrefs.getInstance().setLastRedownladTime(System.currentTimeMillis());
        LocalBroadcastManager.getInstance(this).sendBroadcast(new Intent(DOWNLOAD_SUCCESS));

    } catch (IOException e) {
        LocalBroadcastManager.getInstance(this).sendBroadcast(new Intent(DOWNLOAD_FAIL));
    }
}

From source file:com.futureplatforms.kirin.extensions.databases.DatabasesBackend.java

protected void executeEndTransaction(DBTransaction tx, Runnable job) {
    Executor executor = tx.mReadOnly ? mReadOnlyExecutor : mWritingExecutor;
    if (executor != null) {
        executor.execute(job);
    } else {//from www.j  a  v a  2s  .  c  om
        job.run();
    }

}

From source file:org.commonjava.indy.subsys.git.GitManagerConcurrentTest.java

@BMRules(rules = {
        @BMRule(name = "init rendezvous", targetClass = "GitManager", targetMethod = "<init>", targetLocation = "ENTRY", action = "createRendezvous($0, 2, true)"),
        @BMRule(name = "getHeadCommit call", targetClass = "GitManager", targetMethod = "getHeadCommit(File)", targetLocation = "ENTRY", action = "debug(\"getHeadCommit() waiting...\"); rendezvous($0); debug(\"getHeadCommit(): thread proceeding.\")"),
        @BMRule(name = "addAndCommitPaths call", targetClass = "GitManager", targetMethod = "addAndCommitPaths(ChangeSummary,Collection)", targetLocation = "ENTRY", action = "debug(\"addAndCommitPaths() waiting...\"); rendezvous($0); debug(\"addAndCommitPaths(): thread proceeding.\")"), })
@Test/* w  w w . j av a2s . co  m*/
public void addToRepoWhileGettingHeadCommit() throws Exception {
    final int threshold = 2;
    final Executor pool = Executors.newFixedThreadPool(threshold);
    CountDownLatch latch = new CountDownLatch(threshold);

    final File f = new File(cloneDir, String.format("test.txt"));
    FileUtils.write(f, "This is a test");

    final String user = "testAddAndCommit";
    git.addFiles(new ChangeSummary(user, "first commit"), f);
    git.commit();

    pool.execute(() -> {
        try {
            git.getHeadCommit(f);
        } catch (Exception e) {
            e.printStackTrace();
            failed = true;
        } finally {
            latch.countDown();
        }
    });

    pool.execute(() -> {
        try {
            FileUtils.write(f, "This is another test");
            git.addFiles(new ChangeSummary(user, "second commit"), f);
            git.commit();
        } catch (Exception e) {
            e.printStackTrace();
            failed = true;
        } finally {
            latch.countDown();
        }
    });

    latch.await();
    if (failed) {
        fail();
    }

}

From source file:com.tinspx.util.concurrent.TimedSemaphoreTest.java

@SuppressWarnings("UnnecessaryUnboxing")
static void runTest(Executor executor, TimedSemaphore ts, Ticker ticker, int threadCount, int acquisitions,
        Acquire acquire, Permits permits) throws InterruptedException {
    checkArgument(threadCount > 0);//from  w  ww  . j a  v  a  2s.  co m

    DelayTest.DelayTestBuilder builder = DelayTest.builder();
    builder.stop(new AtomicBoolean());
    builder.start(new CountDownLatch(threadCount));
    builder.lock(new ReentrantLock());
    builder.acquisitions(acquisitions);
    builder.ticker(ticker).ts(ts);
    builder.acquire(acquire).permits(permits);
    builder.tests(new MutableInt());
    builder.totalThreads(threadCount);
    builder.history(new History(ts));

    DelayTest[] testers = new DelayTest[threadCount];
    for (int i = 0; i < threadCount; i++) {
        testers[i] = builder.thread(i).build();
        executor.execute(testers[i]);
    }
    for (int i = 0; i < threadCount; i++) {
        testers[i].complete.await();
    }
    String errorMsg = null;
    for (int i = 0; i < threadCount; i++) {
        if (testers[i].fail != null) {
            errorMsg = testers[i].fail;
            System.out.println(errorMsg);
            System.out.println();
        }
    }
    if (errorMsg != null) {
        fail(errorMsg);
    }

    assertEquals(threadCount * acquisitions, builder.tests.getValue().intValue());
    if (++testCount % 10 == 0) {
        System.out.printf("%d, Tests: %s\n", testCount, builder.tests);
    }
}

From source file:com.meidusa.amoeba.mysql.net.MysqlClientConnection.java

protected void messageProcess() {

    Executor executor = null;
    if (isAuthenticatedSeted()) {
        executor = ProxyRuntimeContext.getInstance().getRuntimeContext().getClientSideExecutor();
    } else {/*from   w  w  w. j a  v a 2s. co m*/
        executor = ProxyRuntimeContext.getInstance().getRuntimeContext().getServerSideExecutor();
    }

    executor.execute(new Runnable() {
        public void run() {
            try {
                MysqlClientConnection.this.getMessageHandler().handleMessage(MysqlClientConnection.this);
            } finally {
                ThreadLocalMap.reset();
            }
        }
    });
}

From source file:org.jcurl.core.ui.TaskExecutor.java

/**
 * Delegate to the {@link Executor#execute(Runnable)} of the type parameter.
 * /*from   ww w  .j a va 2s.  co  m*/
 * Keeps a {@link Map} class-&gt;instance.
 * 
 * @param msg
 * @param et
 *            executor to delegate to.
 * @throws RejectedExecutionException
 *             {@link Class#newInstance()} of the type parameter failed.
 */
public void execute(final Runnable msg, final Class<? extends Executor> et) {
    log.debug(et);
    Executor ex;
    try {
        synchronized (et) {
            ex = map.get(et);
            if (ex == null)
                map.put(et, ex = et.newInstance());
        }
    } catch (final InstantiationException e) {
        throw new RejectedExecutionException(e);
    } catch (final IllegalAccessException e) {
        throw new RejectedExecutionException(e);
    }
    ex.execute(msg);
}

From source file:com.magnet.mmx.server.plugin.mmxmgmt.apns.APNSConnectionPoolImplTest.java

@Test
public void testPoolWithMultipleThreads() {
    String testAppId = "multithreadTestApp";
    /**/*from   www .  ja v  a2  s.c  o  m*/
     * create 5 threads each sending to 100 devices
     */
    int deviceCount = 100;
    int threadCount = 5;
    Map<String, String> payload = new LinkedHashMap<String, String>(100);
    for (int i = 0; i < deviceCount; i++) {
        payload.put("device:" + (i + 1), "JSON Payload{}:" + (i + 1));
    }
    objectFactory.clearCounter();
    APNSConnectionPoolImpl pool = APNSConnectionPoolImpl.getInstance();
    //initialize the pool with connections for all apps

    //    for (int i = 0; i < appIds.length; i++) {
    //      APNSConnection conn = pool.getConnection(appIds[i], true);
    //      pool.returnConnection(conn);
    //    }

    CountDownLatch countDownLatch = new CountDownLatch(threadCount);
    Executor executor = Executors.newFixedThreadPool(threadCount, new ThreadFactory() {
        private AtomicInteger counter = new AtomicInteger(1);

        @Override
        public Thread newThread(Runnable r) {
            Thread t = new Thread(r);
            t.setName("TestThread:" + counter.getAndIncrement());
            return t;
        }
    });
    for (int i = 0; i < threadCount; i++) {
        executor.execute(new SimpleAPNSSenderThread(testAppId, true, payload, countDownLatch));
    }
    //wait for the threads to finish
    try {
        countDownLatch.await();
    } catch (InterruptedException e) {
        e.printStackTrace();
        fail(e.getMessage());
    }
    int count = objectFactory.getCreatedCount(new APNSConnectionPoolImpl.APNSConnectionKey(testAppId, true));
    assertEquals("Object got created too many times", MAX_OBJECTS_PER_KEY, count);
}

From source file:fi.jumi.core.testbench.TestBench.java

public void run(SuiteListener suiteListener, Class<?>... testClasses) {
    SingleThreadedActors actors = new SingleThreadedActors(new DynamicEventizerProvider(), actorsFailureHandler,
            actorsMessageListener);/*from w ww. ja  v  a 2  s  .c o  m*/
    ActorThread actorThread = actors.startActorThread();
    Executor testExecutor = actors.getExecutor();

    RunIdSequence runIdSequence = new RunIdSequence();
    ClassLoader classLoader = getClass().getClassLoader();

    ActorRef<TestFileFinderListener> suiteRunner = actorThread.bindActor(TestFileFinderListener.class,
            new SuiteRunner(
                    new DriverFactory(suiteListener, actorThread, outputCapturer, driverFinder, runIdSequence,
                            classLoader),
                    suiteListener, actorThread, testExecutor, new PrintStream(new NullOutputStream())));

    suiteListener.onSuiteStarted();
    testExecutor.execute(new TestFileFinderRunner(new StubTestFileFinder(testClasses), suiteRunner));
    actors.processEventsUntilIdle();
}