Search in sources :

Example 66 with Callable

use of java.util.concurrent.Callable in project ACS by ACS-Community.

the class HelperTest method testConcurrentChannelRetrieval.

/**
	 * One step up from {@link #testConcurrentChannelCreation()}, here we test concurrent calls to 
	 * {@link Helper#getNotificationChannel(String, String, String)} which are supposed to handle the 
	 * <code>NameAlreadyUsed</code> exception by making those later threads wait until the channel has 
	 * been created for the first thread, then sharing the channel object.
	 */
public void testConcurrentChannelRetrieval() throws Throwable {
    // one channel to be retrieved concurrently
    final String channelName = "testChannelForConcurrentRetrieval";
    final HelperWithChannelCreationSynch helper = new HelperWithChannelCreationSynch(channelName, getContainerServices(), nctx);
    assertChannel(false, channelName);
    class ChannelRetriever implements Callable<EventChannel> {

        private final CountDownLatch synchStart;

        ChannelRetriever(CountDownLatch synchStart) {
            this.synchStart = synchStart;
        }

        public EventChannel call() throws Exception {
            String factoryName = helper.getNotificationFactoryNameForChannel();
            return helper.getNotificationChannel(factoryName, synchStart);
        }
    }
    // we need at least two threads, but more threads may improve collision chances
    final int numCreators = 3;
    assertTrue(numCreators >= 2);
    ExecutorService pool = Executors.newFixedThreadPool(numCreators, getContainerServices().getThreadFactory());
    CountDownLatch synchCreationStart = new CountDownLatch(numCreators);
    List<Future<EventChannel>> results = new ArrayList<Future<EventChannel>>();
    // check the results
    EventChannel uniqueChannel = null;
    try {
        // Run the threads that request the same channel
        for (int i = 0; i < numCreators; i++) {
            results.add(pool.submit(new ChannelRetriever(synchCreationStart)));
        }
        // wait for all threads to finish. Waiting here instead of waiting on the future.get() calls
        // has the advantage that we can exit this method with a fail() without leaving an ongoing channel creation behind.
        pool.shutdown();
        assertTrue(pool.awaitTermination(30, TimeUnit.SECONDS));
        for (Future<EventChannel> future : results) {
            try {
                EventChannel threadResult = future.get();
                // we only get here if threadResult != null, otherwise ex
                if (uniqueChannel != null) {
                    assertTrue(uniqueChannel._is_equivalent(threadResult));
                }
                uniqueChannel = threadResult;
            } catch (ExecutionException ex) {
                throw ex.getCause();
            } catch (AssertionFailedError ex) {
                throw ex;
            } catch (Throwable thr) {
                fail("Unexpected exception " + thr.toString());
            }
        }
        m_logger.info("All concurrent calls to getNotificationChannel got the same channel object.");
    } finally {
        if (uniqueChannel != null) {
            helper.destroyNotificationChannel(NC_KIND.value, uniqueChannel);
        }
    }
}
Also used : ArrayList(java.util.ArrayList) CountDownLatch(java.util.concurrent.CountDownLatch) Callable(java.util.concurrent.Callable) EventChannel(gov.sandia.NotifyMonitoringExt.EventChannel) ExecutorService(java.util.concurrent.ExecutorService) Future(java.util.concurrent.Future) ExecutionException(java.util.concurrent.ExecutionException) AssertionFailedError(junit.framework.AssertionFailedError)

Example 67 with Callable

use of java.util.concurrent.Callable in project spatial-portal by AtlasOfLivingAustralia.

the class AreaReportPDF method getTabulationCallable.

private Callable getTabulationCallable(String fieldId) {
    final String fid = fieldId;
    return new Callable() {

        @Override
        public Object call() throws Exception {
            try {
                JSONParser jp = new JSONParser();
                tabulation.put(fid, jp.parse(Util.readUrl(CommonData.getLayersServer() + "/tabulation/" + fid + "/" + areaPid + ".json")));
            } catch (Exception e) {
                LOGGER.error("failed tabulation: fid=" + fid + ", areaPid=" + areaPid);
            }
            return null;
        }
    };
}
Also used : JSONParser(org.json.simple.parser.JSONParser) Callable(java.util.concurrent.Callable) ParseException(org.json.simple.parser.ParseException)

Example 68 with Callable

use of java.util.concurrent.Callable in project async-http-client by AsyncHttpClient.

the class MultipleHeaderTest method setUpGlobal.

@BeforeClass
public void setUpGlobal() throws Exception {
    serverSocket = ServerSocketFactory.getDefault().createServerSocket(0);
    port1 = serverSocket.getLocalPort();
    executorService = Executors.newFixedThreadPool(1);
    voidFuture = executorService.submit(new Callable<Void>() {

        public Void call() throws Exception {
            Socket socket;
            while ((socket = serverSocket.accept()) != null) {
                InputStream inputStream = socket.getInputStream();
                BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
                String req = reader.readLine().split(" ")[1];
                int i = inputStream.available();
                long l = inputStream.skip(i);
                assertEquals(l, i);
                socket.shutdownInput();
                if (req.endsWith("MultiEnt")) {
                    OutputStreamWriter outputStreamWriter = new OutputStreamWriter(socket.getOutputStream());
                    outputStreamWriter.append("HTTP/1.0 200 OK\n" + "Connection: close\n" + "Content-Type: text/plain; charset=iso-8859-1\n" + "Content-Length: 2\n" + "Content-Length: 1\n" + "\n0\n");
                    outputStreamWriter.flush();
                    socket.shutdownOutput();
                } else if (req.endsWith("MultiOther")) {
                    OutputStreamWriter outputStreamWriter = new OutputStreamWriter(socket.getOutputStream());
                    outputStreamWriter.append("HTTP/1.0 200 OK\n" + "Connection: close\n" + "Content-Type: text/plain; charset=iso-8859-1\n" + "Content-Length: 1\n" + "X-Forwarded-For: abc\n" + "X-Forwarded-For: def\n" + "\n0\n");
                    outputStreamWriter.flush();
                    socket.shutdownOutput();
                }
            }
            return null;
        }
    });
}
Also used : InputStreamReader(java.io.InputStreamReader) InputStream(java.io.InputStream) BufferedReader(java.io.BufferedReader) OutputStreamWriter(java.io.OutputStreamWriter) Callable(java.util.concurrent.Callable) Socket(java.net.Socket) ServerSocket(java.net.ServerSocket) BeforeClass(org.testng.annotations.BeforeClass)

Example 69 with Callable

use of java.util.concurrent.Callable in project graylog2-server by Graylog2.

the class HttpTransport method getBaseChannelHandlers.

@Override
protected LinkedHashMap<String, Callable<? extends ChannelHandler>> getBaseChannelHandlers(MessageInput input) {
    final LinkedHashMap<String, Callable<? extends ChannelHandler>> baseChannelHandlers = super.getBaseChannelHandlers(input);
    if (idleWriterTimeout > 0) {
        // Install read timeout handler to close idle connections after a timeout.
        // This avoids dangling HTTP connections when the HTTP client does not close the connection properly.
        // For details see: https://github.com/Graylog2/graylog2-server/issues/3223#issuecomment-270350500
        baseChannelHandlers.put("read-timeout-handler", () -> new ReadTimeoutHandler(timer, idleWriterTimeout, TimeUnit.SECONDS));
    }
    baseChannelHandlers.put("decoder", () -> new HttpRequestDecoder(DEFAULT_MAX_INITIAL_LINE_LENGTH, DEFAULT_MAX_HEADER_SIZE, maxChunkSize));
    baseChannelHandlers.put("aggregator", () -> new HttpChunkAggregator(maxChunkSize));
    baseChannelHandlers.put("encoder", HttpResponseEncoder::new);
    baseChannelHandlers.put("decompressor", HttpContentDecompressor::new);
    return baseChannelHandlers;
}
Also used : HttpResponseEncoder(org.jboss.netty.handler.codec.http.HttpResponseEncoder) HttpRequestDecoder(org.jboss.netty.handler.codec.http.HttpRequestDecoder) ReadTimeoutHandler(org.jboss.netty.handler.timeout.ReadTimeoutHandler) HttpChunkAggregator(org.jboss.netty.handler.codec.http.HttpChunkAggregator) SimpleChannelHandler(org.jboss.netty.channel.SimpleChannelHandler) ChannelHandler(org.jboss.netty.channel.ChannelHandler) Callable(java.util.concurrent.Callable) HttpContentDecompressor(org.jboss.netty.handler.codec.http.HttpContentDecompressor)

Example 70 with Callable

use of java.util.concurrent.Callable in project graylog2-server by Graylog2.

the class SyslogTcpTransport method getFinalChannelHandlers.

@Override
protected LinkedHashMap<String, Callable<? extends ChannelHandler>> getFinalChannelHandlers(MessageInput input) {
    final LinkedHashMap<String, Callable<? extends ChannelHandler>> finalChannelHandlers = Maps.newLinkedHashMap();
    finalChannelHandlers.putAll(super.getFinalChannelHandlers(input));
    // Replace the "framer" channel handler inserted by the parent.
    finalChannelHandlers.put("framer", new Callable<ChannelHandler>() {

        @Override
        public ChannelHandler call() throws Exception {
            return new SyslogTCPFramingRouterHandler(maxFrameLength, delimiter);
        }
    });
    return finalChannelHandlers;
}
Also used : SyslogTCPFramingRouterHandler(org.graylog2.inputs.syslog.tcp.SyslogTCPFramingRouterHandler) ChannelHandler(org.jboss.netty.channel.ChannelHandler) Callable(java.util.concurrent.Callable)

Aggregations

Callable (java.util.concurrent.Callable)1946 ArrayList (java.util.ArrayList)664 ExecutorService (java.util.concurrent.ExecutorService)630 Test (org.junit.Test)598 Future (java.util.concurrent.Future)482 IOException (java.io.IOException)255 ExecutionException (java.util.concurrent.ExecutionException)247 List (java.util.List)167 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)158 CountDownLatch (java.util.concurrent.CountDownLatch)157 HashMap (java.util.HashMap)120 Map (java.util.Map)117 File (java.io.File)112 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)105 Ignite (org.apache.ignite.Ignite)87 HashSet (java.util.HashSet)80 Set (java.util.Set)55 TimeoutException (java.util.concurrent.TimeoutException)54 Collectors (java.util.stream.Collectors)53 Transaction (org.apache.ignite.transactions.Transaction)52