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);
}
}
}
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;
}
};
}
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;
}
});
}
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;
}
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;
}
Aggregations