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:org.apache.hadoop.hbase.http.TestHttpServer.java

/** Test the maximum number of threads cannot be exceeded. */
@Test/*from   w w  w .j  ava2  s.  c o  m*/
public void testMaxThreads() throws Exception {
    int clientThreads = MAX_THREADS * 10;
    Executor executor = Executors.newFixedThreadPool(clientThreads);
    // Run many clients to make server reach its maximum number of threads
    final CountDownLatch ready = new CountDownLatch(clientThreads);
    final CountDownLatch start = new CountDownLatch(1);
    for (int i = 0; i < clientThreads; i++) {
        executor.execute(new Runnable() {
            @Override
            public void run() {
                ready.countDown();
                try {
                    start.await();
                    assertEquals("a:b\nc:d\n", readOutput(new URL(baseUrl, "/echo?a=b&c=d")));
                    int serverThreads = server.webServer.getThreadPool().getThreads();
                    assertTrue("More threads are started than expected, Server Threads count: " + serverThreads,
                            serverThreads <= MAX_THREADS);
                    System.out.println("Number of threads = " + serverThreads
                            + " which is less or equal than the max = " + MAX_THREADS);
                } catch (Exception e) {
                    // do nothing
                }
            }
        });
    }
    // Start the client threads when they are all ready
    ready.await();
    start.countDown();
}

From source file:org.springframework.integration.channel.QueueChannelTests.java

@Test
public void testImmediateReceive() throws Exception {
    final AtomicBoolean messageReceived = new AtomicBoolean(false);
    final QueueChannel channel = new QueueChannel();
    final CountDownLatch latch1 = new CountDownLatch(1);
    final CountDownLatch latch2 = new CountDownLatch(1);
    Executor singleThreadExecutor = Executors.newSingleThreadExecutor();
    Runnable receiveTask1 = new Runnable() {
        @Override/*from www  .  j a  v  a 2 s  .c o  m*/
        public void run() {
            Message<?> message = channel.receive(0);
            if (message != null) {
                messageReceived.set(true);
            }
            latch1.countDown();
        }
    };
    Runnable sendTask = new Runnable() {
        @Override
        public void run() {
            channel.send(new GenericMessage<String>("testing"));
        }
    };
    singleThreadExecutor.execute(receiveTask1);
    latch1.await();
    singleThreadExecutor.execute(sendTask);
    assertFalse(messageReceived.get());
    Runnable receiveTask2 = new Runnable() {
        @Override
        public void run() {
            Message<?> message = channel.receive(0);
            if (message != null) {
                messageReceived.set(true);
            }
            latch2.countDown();
        }
    };
    singleThreadExecutor.execute(receiveTask2);
    latch2.await();
    assertTrue(messageReceived.get());
}

From source file:org.apache.hadoop.hdfs.server.datanode.fsdataset.impl.FsDatasetCache.java

/**
 * Attempt to begin caching a block.//from ww w . jav  a  2 s .  c  o m
 */
synchronized void cacheBlock(long blockId, String bpid, String blockFileName, long length, long genstamp,
        Executor volumeExecutor) {
    ExtendedBlockId key = new ExtendedBlockId(blockId, bpid);
    Value prevValue = mappableBlockMap.get(key);
    if (prevValue != null) {
        LOG.debug("Block with id {}, pool {} already exists in the " + "FsDatasetCache with state {}", blockId,
                bpid, prevValue.state);
        numBlocksFailedToCache.incrementAndGet();
        return;
    }
    mappableBlockMap.put(key, new Value(null, State.CACHING));
    volumeExecutor.execute(new CachingTask(key, blockFileName, length, genstamp));
    LOG.debug("Initiating caching for Block with id {}, pool {}", blockId, bpid);
}

From source file:org.apache.axis2.jaxws.server.dispatcher.JavaBeanDispatcher.java

public void invokeAsync(MessageContext request, EndpointCallback callback) {
    if (log.isDebugEnabled()) {
        log.debug("Invoking service endpoint: " + serviceImplClass.getName());
        log.debug("Invocation pattern: two way, async");
    }/*from   www .ja  v  a  2  s  . c  o m*/

    initialize(request);

    OperationDescription operationDesc = Utils.getOperationDescription(request);

    Object[] methodInputParams = createRequestParameters(request);

    Method target = getJavaMethod(request, serviceImplClass);
    if (log.isDebugEnabled()) {
        // At this point, the OpDesc includes everything we know, including the actual method
        // on the service impl we will delegate to; it was set by getJavaMethod(...) above.
        log.debug("JavaBeanDispatcher about to invoke using OperationDesc: " + operationDesc.toString());
    }

    EndpointInvocationContext eic = (EndpointInvocationContext) request.getInvocationContext();
    ClassLoader cl = getContextClassLoader();

    AsyncInvocationWorker worker = new AsyncInvocationWorker(target, methodInputParams, cl, eic);
    FutureTask task = new FutureTask<AsyncInvocationWorker>(worker);

    ExecutorFactory ef = (ExecutorFactory) FactoryRegistry.getFactory(ExecutorFactory.class);
    Executor executor = ef.getExecutorInstance(ExecutorFactory.SERVER_EXECUTOR);
    // If the property has been set to disable thread switching, then we can 
    // do so by using a SingleThreadedExecutor instance to continue processing
    // work on the existing thread.
    Boolean disable = (Boolean) request.getProperty(ServerConstants.SERVER_DISABLE_THREAD_SWITCH);
    if (disable != null && disable.booleanValue()) {
        if (log.isDebugEnabled()) {
            log.debug("Server side thread switch disabled.  Setting Executor to the SingleThreadedExecutor.");
        }
        executor = new SingleThreadedExecutor();
    }
    executor.execute(task);

    return;
}

From source file:com.mobilesolutionworks.android.http.WorksHttpFutureTask.java

/**
 * Execute specified works http request in parallel.
 *
 * @param request works http request//from  ww  w. j  a  v a2s . com
 * @param handler android handler
 * @param exec    executor so it can be run in serial or other controlled manner
 */
public void execute(WorksHttpRequest request, Handler handler, Executor exec) {
    mWorker = new WorkerRunnable<WorksHttpRequest, Result>() {
        @Override
        public Result call() throws Exception {
            Thread.currentThread()
                    .setUncaughtExceptionHandler(new UncaughtExceptionHandler(mHandler, mParams[0]));

            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
            WorksHttpResponse<Result> response = WorksHttpClient.executeOperation(mContext, mParams[0],
                    WorksHttpFutureTask.this);

            return postResult(mHandler, response);
        }
    };

    mFuture = new FutureTask<Result>(mWorker);

    mWorker.mHandler = handler;
    mWorker.mParams = new WorksHttpRequest[] { request };
    exec.execute(mFuture);
}

From source file:org.apache.axis2.jaxws.server.dispatcher.JavaBeanDispatcher.java

public void invokeOneWay(MessageContext request) {
    if (log.isDebugEnabled()) {
        log.debug("Invoking service endpoint: " + serviceImplClass.getName());
        log.debug("Invocation pattern: one way");
    }/*from   w w w . j a va  2s  .  co  m*/

    initialize(request);

    OperationDescription operationDesc = Utils.getOperationDescription(request);

    Object[] methodInputParams = createRequestParameters(request);

    Method target = getJavaMethod(request, serviceImplClass);
    if (log.isDebugEnabled()) {
        // At this point, the OpDesc includes everything we know, including the actual method
        // on the service impl we will delegate to; it was set by getJavaMethod(...) above.
        log.debug("JavaBeanDispatcher about to invoke using OperationDesc: " + operationDesc.toString());
    }

    EndpointInvocationContext eic = (EndpointInvocationContext) request.getInvocationContext();
    ClassLoader cl = getContextClassLoader();

    AsyncInvocationWorker worker = new AsyncInvocationWorker(target, methodInputParams, cl, eic);
    FutureTask task = new FutureTask<AsyncInvocationWorker>(worker);

    ExecutorFactory ef = (ExecutorFactory) FactoryRegistry.getFactory(ExecutorFactory.class);
    Executor executor = ef.getExecutorInstance(ExecutorFactory.SERVER_EXECUTOR);

    // If the property has been set to disable thread switching, then we can 
    // do so by using a SingleThreadedExecutor instance to continue processing
    // work on the existing thread.
    Boolean disable = (Boolean) request.getProperty(ServerConstants.SERVER_DISABLE_THREAD_SWITCH);
    if (disable != null && disable.booleanValue()) {
        if (log.isDebugEnabled()) {
            log.debug("Server side thread switch disabled.  "
                    + "Setting Executor to the SingleThreadedExecutor.");
        }
        executor = new SingleThreadedExecutor();
    }

    executor.execute(task);
    return;
}

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

@SuppressWarnings("UnnecessaryUnboxing")
static void runTest(Executor executor, DelayedSemaphore ds, Ticker ticker, int threadCount, int acquisitions,
        Acquire acquire, Permits permits, Range<Integer> acquireRange, Release release,
        DelayConstraint constraint) throws InterruptedException {
    checkArgument(threadCount > 0);/*from w  ww  .  jav a2s  .c  o m*/

    DelayTest.DelayTestBuilder builder = DelayTest.builder();
    builder.stop(new AtomicBoolean());
    builder.start(new CountDownLatch(threadCount));
    builder.lock(new ReentrantLock());
    builder.releaseTimes(new long[ds.permits()]);
    builder.acquisitions(acquisitions);
    builder.ticker(ticker).ds(ds);
    builder.acquire(acquire).permits(permits).permits(permits).acquireRange(acquireRange);
    builder.release(release);
    builder.delayConstraint(constraint);
    builder.tests(new MutableInt());
    builder.totalThreads(threadCount);

    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:io.atomix.cluster.messaging.impl.NettyMessagingService.java

@Override
public void registerHandler(String type, BiConsumer<Address, byte[]> handler, Executor executor) {
    handlers.put(type, (message, connection) -> executor
            .execute(() -> handler.accept(message.sender(), message.payload())));
}

From source file:io.atomix.cluster.messaging.impl.NettyMessagingService.java

@Override
public void registerHandler(String type, BiFunction<Address, byte[], byte[]> handler, Executor executor) {
    handlers.put(type, (message, connection) -> executor.execute(() -> {
        byte[] responsePayload = null;
        InternalReply.Status status = InternalReply.Status.OK;
        try {//  www  . j ava  2  s. c  o m
            responsePayload = handler.apply(message.sender(), message.payload());
        } catch (Exception e) {
            log.warn("An error occurred in a message handler: {}", e);
            status = InternalReply.Status.ERROR_HANDLER_EXCEPTION;
        }
        connection.reply(message, status, Optional.ofNullable(responsePayload));
    }));
}

From source file:edu.kit.trufflehog.view.jung.visualization.FXVisualizationViewer.java

synchronized public void refreshLayout() {

    //  logger.debug("refresh");
    final FRLayout2<INode, IConnection> l = new FRLayout2<>(this.layout.getObservableGraph());
    l.setMaxIterations(layout.getGraph().getEdgeCount() * (int) (this.getWidth() / canvas.getScale()));
    // l.setMaxIterations(700);
    this.layout = new ObservableLayout<>(l);
    //TODO make the dimension changeable from settings menu?

    // logger.debug(canvas.getScale() + " " + this.getWidth() + " " + this.getHeight());
    layout.setSize(new Dimension((int) (this.getWidth() / (2 * canvas.getScale())),
            (int) (this.getHeight() / (2 * canvas.getScale()))));

    //layout.set//  ww w.  jav a2  s  . c  om

    final Executor layouter = Executors.newSingleThreadExecutor();

    layouter.execute(() -> {

        while (!layout.done()) {
            layout.step();
            Platform.runLater(this::repaint);
        }

    });

}