Search in sources :

Example 11 with Executor

use of java.util.concurrent.Executor in project tomcat by apache.

the class AbstractEndpoint method processSocket.

// ---------------------------------------------- Request processing methods
/**
     * Process the given SocketWrapper with the given status. Used to trigger
     * processing as if the Poller (for those endpoints that have one)
     * selected the socket.
     *
     * @param socketWrapper The socket wrapper to process
     * @param event         The socket event to be processed
     * @param dispatch      Should the processing be performed on a new
     *                          container thread
     *
     * @return if processing was triggered successfully
     */
public boolean processSocket(SocketWrapperBase<S> socketWrapper, SocketEvent event, boolean dispatch) {
    try {
        if (socketWrapper == null) {
            return false;
        }
        SocketProcessorBase<S> sc = processorCache.pop();
        if (sc == null) {
            sc = createSocketProcessor(socketWrapper, event);
        } else {
            sc.reset(socketWrapper, event);
        }
        Executor executor = getExecutor();
        if (dispatch && executor != null) {
            executor.execute(sc);
        } else {
            sc.run();
        }
    } catch (RejectedExecutionException ree) {
        getLog().warn(sm.getString("endpoint.executor.fail", socketWrapper), ree);
        return false;
    } catch (Throwable t) {
        ExceptionUtils.handleThrowable(t);
        // This means we got an OOM or similar creating a thread, or that
        // the pool and its queue are full
        getLog().error(sm.getString("endpoint.process.fail"), t);
        return false;
    }
    return true;
}
Also used : ResizableExecutor(org.apache.tomcat.util.threads.ResizableExecutor) Executor(java.util.concurrent.Executor) ThreadPoolExecutor(org.apache.tomcat.util.threads.ThreadPoolExecutor) RejectedExecutionException(java.util.concurrent.RejectedExecutionException)

Example 12 with Executor

use of java.util.concurrent.Executor in project tomcat by apache.

the class TestWebappClassLoaderThreadLocalMemoryLeak method testThreadLocalLeak1.

@Test
public void testThreadLocalLeak1() throws Exception {
    Tomcat tomcat = getTomcatInstance();
    // Need to make sure we see a leak for the right reasons
    tomcat.getServer().addLifecycleListener(new JreMemoryLeakPreventionListener());
    // No file system docBase required
    Context ctx = tomcat.addContext("", null);
    Tomcat.addServlet(ctx, "leakServlet1", "org.apache.tomcat.unittest.TesterLeakingServlet1");
    ctx.addServletMappingDecoded("/leak1", "leakServlet1");
    tomcat.start();
    Executor executor = tomcat.getConnector().getProtocolHandler().getExecutor();
    ((ThreadPoolExecutor) executor).setThreadRenewalDelay(-1);
    // Configure logging filter to check leak message appears
    LogValidationFilter f = new LogValidationFilter("The web application [ROOT] created a ThreadLocal with key of");
    LogManager.getLogManager().getLogger("org.apache.catalina.loader.WebappClassLoaderBase").setFilter(f);
    // Need to force loading of all web application classes via the web
    // application class loader
    loadClass("TesterCounter", (WebappClassLoader) ctx.getLoader().getClassLoader());
    loadClass("TesterLeakingServlet1", (WebappClassLoader) ctx.getLoader().getClassLoader());
    // This will trigger the ThreadLocal creation
    int rc = getUrl("http://localhost:" + getPort() + "/leak1", new ByteChunk(), null);
    // Make sure request is OK
    Assert.assertEquals(HttpServletResponse.SC_OK, rc);
    // Destroy the context
    ctx.stop();
    tomcat.getHost().removeChild(ctx);
    ctx = null;
    // Make sure we have a memory leak
    String[] leaks = ((StandardHost) tomcat.getHost()).findReloadedContextMemoryLeaks();
    Assert.assertNotNull(leaks);
    Assert.assertTrue(leaks.length > 0);
    // Make sure the message was logged
    Assert.assertEquals(1, f.getMessageCount());
}
Also used : Context(org.apache.catalina.Context) Tomcat(org.apache.catalina.startup.Tomcat) Executor(java.util.concurrent.Executor) ThreadPoolExecutor(org.apache.tomcat.util.threads.ThreadPoolExecutor) ByteChunk(org.apache.tomcat.util.buf.ByteChunk) StandardHost(org.apache.catalina.core.StandardHost) JreMemoryLeakPreventionListener(org.apache.catalina.core.JreMemoryLeakPreventionListener) ThreadPoolExecutor(org.apache.tomcat.util.threads.ThreadPoolExecutor) TomcatBaseTest(org.apache.catalina.startup.TomcatBaseTest) Test(org.junit.Test)

Example 13 with Executor

use of java.util.concurrent.Executor in project weave by continuuity.

the class TrackerService method startUp.

@Override
protected void startUp() throws Exception {
    Executor bossThreads = Executors.newFixedThreadPool(NUM_BOSS_THREADS, new ThreadFactoryBuilder().setDaemon(true).setNameFormat("boss-thread").build());
    Executor workerThreads = Executors.newCachedThreadPool(new ThreadFactoryBuilder().setDaemon(true).setNameFormat("worker-thread#%d").build());
    ChannelFactory factory = new NioServerSocketChannelFactory(bossThreads, workerThreads);
    bootstrap = new ServerBootstrap(factory);
    bootstrap.setPipelineFactory(new ChannelPipelineFactory() {

        public ChannelPipeline getPipeline() {
            ChannelPipeline pipeline = Channels.pipeline();
            pipeline.addLast("decoder", new HttpRequestDecoder());
            pipeline.addLast("aggregator", new HttpChunkAggregator(MAX_INPUT_SIZE));
            pipeline.addLast("encoder", new HttpResponseEncoder());
            pipeline.addLast("compressor", new HttpContentCompressor());
            pipeline.addLast("handler", new ReportHandler(resourceReport));
            return pipeline;
        }
    });
    Channel channel = bootstrap.bind(new InetSocketAddress(host, 0));
    bindAddress = (InetSocketAddress) channel.getLocalAddress();
    url = URI.create(String.format("http://%s:%d", host, bindAddress.getPort())).resolve(TrackerService.PATH).toURL();
    channelGroup.add(channel);
}
Also used : NioServerSocketChannelFactory(org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory) HttpContentCompressor(org.jboss.netty.handler.codec.http.HttpContentCompressor) InetSocketAddress(java.net.InetSocketAddress) Channel(org.jboss.netty.channel.Channel) HttpChunkAggregator(org.jboss.netty.handler.codec.http.HttpChunkAggregator) NioServerSocketChannelFactory(org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory) ChannelFactory(org.jboss.netty.channel.ChannelFactory) ServerBootstrap(org.jboss.netty.bootstrap.ServerBootstrap) ChannelPipeline(org.jboss.netty.channel.ChannelPipeline) HttpResponseEncoder(org.jboss.netty.handler.codec.http.HttpResponseEncoder) Executor(java.util.concurrent.Executor) HttpRequestDecoder(org.jboss.netty.handler.codec.http.HttpRequestDecoder) ThreadFactoryBuilder(com.google.common.util.concurrent.ThreadFactoryBuilder) ChannelPipelineFactory(org.jboss.netty.channel.ChannelPipelineFactory)

Example 14 with Executor

use of java.util.concurrent.Executor in project weave by continuuity.

the class DiscoveryServiceTestBase method testCancelChangeListener.

@Test
public void testCancelChangeListener() throws InterruptedException {
    Map.Entry<DiscoveryService, DiscoveryServiceClient> entry = create();
    DiscoveryService discoveryService = entry.getKey();
    DiscoveryServiceClient discoveryServiceClient = entry.getValue();
    String serviceName = "cancel_listener";
    ServiceDiscovered serviceDiscovered = discoveryServiceClient.discover(serviceName);
    // An executor that delay execute a Runnable. It's for testing race because listener cancel and discovery changes.
    Executor delayExecutor = new Executor() {

        @Override
        public void execute(final Runnable command) {
            Thread t = new Thread() {

                @Override
                public void run() {
                    try {
                        TimeUnit.SECONDS.sleep(2);
                        command.run();
                    } catch (InterruptedException e) {
                        throw Throwables.propagate(e);
                    }
                }
            };
            t.start();
        }
    };
    final BlockingQueue<List<Discoverable>> events = new ArrayBlockingQueue<List<Discoverable>>(10);
    Cancellable cancelWatch = serviceDiscovered.watchChanges(new ServiceDiscovered.ChangeListener() {

        @Override
        public void onChange(ServiceDiscovered serviceDiscovered) {
            events.add(ImmutableList.copyOf(serviceDiscovered));
        }
    }, delayExecutor);
    // Wait for the init event call
    Assert.assertNotNull(events.poll(3, TimeUnit.SECONDS));
    // Register a new service endpoint, wait a short while and then cancel the listener
    register(discoveryService, serviceName, "localhost", 1);
    TimeUnit.SECONDS.sleep(1);
    cancelWatch.cancel();
    // The change listener shouldn't get any event, since the invocation is delayed by the executor.
    Assert.assertNull(events.poll(3, TimeUnit.SECONDS));
}
Also used : Cancellable(com.continuuity.weave.common.Cancellable) Executor(java.util.concurrent.Executor) ArrayBlockingQueue(java.util.concurrent.ArrayBlockingQueue) List(java.util.List) ImmutableList(com.google.common.collect.ImmutableList) Map(java.util.Map) Test(org.junit.Test)

Example 15 with Executor

use of java.util.concurrent.Executor in project subsampling-scale-image-view by davemorrissey.

the class SubsamplingScaleImageView method execute.

private void execute(AsyncTask<Void, Void, ?> asyncTask) {
    if (parallelLoadingEnabled && VERSION.SDK_INT >= 11) {
        try {
            Field executorField = AsyncTask.class.getField("THREAD_POOL_EXECUTOR");
            Executor executor = (Executor) executorField.get(null);
            Method executeMethod = AsyncTask.class.getMethod("executeOnExecutor", Executor.class, Object[].class);
            executeMethod.invoke(asyncTask, executor, null);
            return;
        } catch (Exception e) {
            Log.i(TAG, "Failed to execute AsyncTask on thread pool executor, falling back to single threaded executor", e);
        }
    }
    asyncTask.execute();
}
Also used : Field(java.lang.reflect.Field) Executor(java.util.concurrent.Executor) Method(java.lang.reflect.Method)

Aggregations

Executor (java.util.concurrent.Executor)267 Test (org.junit.Test)114 CountDownLatch (java.util.concurrent.CountDownLatch)31 ArrayList (java.util.ArrayList)30 IOException (java.io.IOException)28 List (java.util.List)22 ThreadPoolExecutor (java.util.concurrent.ThreadPoolExecutor)21 Timeouts (org.neo4j.cluster.timeout.Timeouts)15 Map (java.util.Map)13 ExecutorService (java.util.concurrent.ExecutorService)13 RejectedExecutionException (java.util.concurrent.RejectedExecutionException)13 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)13 InstanceId (org.neo4j.cluster.InstanceId)13 Config (org.neo4j.kernel.configuration.Config)13 File (java.io.File)12 HashMap (java.util.HashMap)12 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)12 ObjectInputStreamFactory (org.neo4j.cluster.protocol.atomicbroadcast.ObjectInputStreamFactory)12 ObjectOutputStreamFactory (org.neo4j.cluster.protocol.atomicbroadcast.ObjectOutputStreamFactory)12 HeartbeatContext (org.neo4j.cluster.protocol.heartbeat.HeartbeatContext)12