List of usage examples for java.util.concurrent Executors newCachedThreadPool
public static ExecutorService newCachedThreadPool()
From source file:com.waltz3d.common.httpclient.AsyncHttpClient.java
/** * Creates a new AsyncHttpClient.// w w w .ja v a 2 s . co m */ public AsyncHttpClient() { KeyStore trustStore = null; try { trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); trustStore.load(null, null); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } SSLSocketFactory sf = null; try { sf = new SSLSocketFactoryEx(trustStore); sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); } catch (KeyManagementException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (UnrecoverableKeyException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (NoSuchAlgorithmException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (KeyStoreException e) { // TODO Auto-generated catch block e.printStackTrace(); } BasicHttpParams httpParams = new BasicHttpParams(); ConnManagerParams.setTimeout(httpParams, socketTimeout); ConnManagerParams.setMaxConnectionsPerRoute(httpParams, new ConnPerRouteBean(maxConnections)); ConnManagerParams.setMaxTotalConnections(httpParams, DEFAULT_MAX_CONNECTIONS); HttpConnectionParams.setSoTimeout(httpParams, socketTimeout); HttpConnectionParams.setConnectionTimeout(httpParams, socketTimeout); HttpConnectionParams.setTcpNoDelay(httpParams, true); HttpConnectionParams.setSocketBufferSize(httpParams, DEFAULT_SOCKET_BUFFER_SIZE); HttpProtocolParams.setUseExpectContinue(httpParams, false); HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1); HttpProtocolParams.setUserAgent(httpParams, String.format("android-async-http/%s (http://loopj.com/android-async-http)", VERSION)); SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); schemeRegistry.register(new Scheme("https", sf, 443)); ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(httpParams, schemeRegistry); httpContext = new SyncBasicHttpContext(new BasicHttpContext()); httpClient = new DefaultHttpClient(cm, httpParams); httpClient.addRequestInterceptor(new HttpRequestInterceptor() { @Override public void process(HttpRequest request, HttpContext context) { if (!request.containsHeader(HEADER_ACCEPT_ENCODING)) { request.addHeader(HEADER_ACCEPT_ENCODING, ENCODING_GZIP); } for (String header : clientHeaderMap.keySet()) { request.addHeader(header, clientHeaderMap.get(header)); } } }); httpClient.addResponseInterceptor(new HttpResponseInterceptor() { @Override public void process(HttpResponse response, HttpContext context) { final HttpEntity entity = response.getEntity(); if (entity == null) { return; } final Header encoding = entity.getContentEncoding(); if (encoding != null) { for (HeaderElement element : encoding.getElements()) { if (element.getName().equalsIgnoreCase(ENCODING_GZIP)) { response.setEntity(new InflatingEntity(response.getEntity())); break; } } } } }); httpClient.setHttpRequestRetryHandler(new RetryHandler(DEFAULT_MAX_RETRIES)); threadPool = (ThreadPoolExecutor) Executors.newCachedThreadPool(); // threadPool = new ThreadPoolExecutor(1, 30, 60, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>()); requestMap = new WeakHashMap<Context, List<WeakReference<Future<?>>>>(); clientHeaderMap = new HashMap<String, String>(); }
From source file:hivemall.mix.server.MixServerTest.java
@Test public void test2ClientsZeroOneSparseModelWithMixCanceling() throws InterruptedException { final int port = NetUtils.getAvailablePort(); CommandLine cl = CommandLineUtils.parseOptions( new String[] { "-port", Integer.toString(port), "-sync_threshold", "30" }, MixServer.getOptions()); MixServer server = new MixServer(cl); ExecutorService serverExec = Executors.newSingleThreadExecutor(); serverExec.submit(server);//from w ww.ja v a 2 s. c o m waitForState(server, ServerState.RUNNING); final ExecutorService clientsExec = Executors.newCachedThreadPool(); for (int i = 0; i < 2; i++) { clientsExec.submit(new Runnable() { @Override public void run() { try { invokeClient01("test2ClientsZeroOne", port, false, true); } catch (InterruptedException e) { Assert.fail(e.getMessage()); } } }); } clientsExec.awaitTermination(30, TimeUnit.SECONDS); clientsExec.shutdown(); serverExec.shutdown(); }
From source file:com.intel.hadoopRPCBenchmark.HadoopRPCBenchmarkEngine.java
public void testRPCThoughput() throws Exception { // Start RPC engine enginePreparer.prepareServer();/*from w w w . j a va 2s .c o m*/ startRPCServer(); enginePreparer.prepareClient(); ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newCachedThreadPool(); List<DoThoughputTest> tasks = new ArrayList<DoThoughputTest>(clientNum); long start = System.currentTimeMillis(); for (int i = 0; i <= clientNum; i++) { DoThoughputTest task = new DoThoughputTest(); executor.execute(task); tasks.add(task); } while (true) { long end = System.currentTimeMillis(); if (end - start <= execTime * 1000) { Thread.sleep(1000); } else { break; } } long totalPingCount = 0; for (DoThoughputTest task : tasks) { totalPingCount += task.getPingCount(); } System.out.println("Total ping count: " + totalPingCount); executor.shutdown(); // Stop RPC engine enginePreparer.cleanup(); stopRPCServer(); }
From source file:com.check.v3.asynchttp.AsyncHttpClient.java
/** * Creates a new AsyncHttpClient.//www .ja va 2s . c o m * * @param schemeRegistry SchemeRegistry to be used */ public AsyncHttpClient(SchemeRegistry schemeRegistry) { BasicHttpParams httpParams = new BasicHttpParams(); ConnManagerParams.setTimeout(httpParams, timeout); ConnManagerParams.setMaxConnectionsPerRoute(httpParams, new ConnPerRouteBean(maxConnections)); ConnManagerParams.setMaxTotalConnections(httpParams, DEFAULT_MAX_CONNECTIONS); HttpConnectionParams.setSoTimeout(httpParams, timeout); HttpConnectionParams.setConnectionTimeout(httpParams, timeout); HttpConnectionParams.setTcpNoDelay(httpParams, true); HttpConnectionParams.setSocketBufferSize(httpParams, DEFAULT_SOCKET_BUFFER_SIZE); HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1); HttpProtocolParams.setUserAgent(httpParams, String.format("android-async-http/%s", VERSION)); ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(httpParams, schemeRegistry); threadPool = Executors.newCachedThreadPool(); requestMap = new WeakHashMap<Context, List<WeakReference<Future<?>>>>(); clientHeaderMap = new HashMap<String, String>(); httpContext = new SyncBasicHttpContext(new BasicHttpContext()); httpClient = new DefaultHttpClient(cm, httpParams); httpClient.addRequestInterceptor(new HttpRequestInterceptor() { @Override public void process(HttpRequest request, HttpContext context) { if (!request.containsHeader(HEADER_ACCEPT_ENCODING)) { request.addHeader(HEADER_ACCEPT_ENCODING, ENCODING_GZIP); } for (String header : clientHeaderMap.keySet()) { request.addHeader(header, clientHeaderMap.get(header)); } } }); httpClient.addResponseInterceptor(new HttpResponseInterceptor() { @Override public void process(HttpResponse response, HttpContext context) { final HttpEntity entity = response.getEntity(); if (entity == null) { return; } final Header encoding = entity.getContentEncoding(); if (encoding != null) { for (HeaderElement element : encoding.getElements()) { if (element.getName().equalsIgnoreCase(ENCODING_GZIP)) { response.setEntity(new InflatingEntity(entity)); break; } } } } }); httpClient .setHttpRequestRetryHandler(new RetryHandler(DEFAULT_MAX_RETRIES, DEFAULT_RETRY_SLEEP_TIME_MILLIS)); }
From source file:com.library.loopj.android.http.AsyncHttpClient.java
/** * Creates a new AsyncHttpClient.//from w w w.j ava 2 s . c o m * * @param schemeRegistry SchemeRegistry to be used */ public AsyncHttpClient(SchemeRegistry schemeRegistry) { BasicHttpParams httpParams = new BasicHttpParams(); ConnManagerParams.setTimeout(httpParams, timeout); ConnManagerParams.setMaxConnectionsPerRoute(httpParams, new ConnPerRouteBean(maxConnections)); ConnManagerParams.setMaxTotalConnections(httpParams, DEFAULT_MAX_CONNECTIONS); HttpConnectionParams.setSoTimeout(httpParams, timeout); HttpConnectionParams.setConnectionTimeout(httpParams, timeout); HttpConnectionParams.setTcpNoDelay(httpParams, true); HttpConnectionParams.setSocketBufferSize(httpParams, DEFAULT_SOCKET_BUFFER_SIZE); HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1); HttpProtocolParams.setUserAgent(httpParams, String.format("android-async-http/%s (http://loopj.com/android-async-http)", VERSION)); ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(httpParams, schemeRegistry); threadPool = Executors.newCachedThreadPool(); requestMap = new WeakHashMap(); clientHeaderMap = new HashMap(); httpContext = new SyncBasicHttpContext(new BasicHttpContext()); httpClient = new DefaultHttpClient(cm, httpParams); httpClient.addRequestInterceptor(new HttpRequestInterceptor() { @Override public void process(HttpRequest request, HttpContext context) { if (!request.containsHeader(HEADER_ACCEPT_ENCODING)) { request.addHeader(HEADER_ACCEPT_ENCODING, ENCODING_GZIP); } for (String header : clientHeaderMap.keySet()) { if (request.containsHeader(header)) { Header overwritten = request.getFirstHeader(header); Log.d(LOG_TAG, String.format("Headers were overwritten! (%s | %s) overwrites (%s | %s)", header, clientHeaderMap.get(header), overwritten.getName(), overwritten.getValue())); } request.addHeader(header, clientHeaderMap.get(header)); } } }); httpClient.addResponseInterceptor(new HttpResponseInterceptor() { @Override public void process(HttpResponse response, HttpContext context) { final HttpEntity entity = response.getEntity(); if (entity == null) { return; } final Header encoding = entity.getContentEncoding(); if (encoding != null) { for (HeaderElement element : encoding.getElements()) { if (element.getName().equalsIgnoreCase(ENCODING_GZIP)) { response.setEntity(new InflatingEntity(entity)); break; } } } } }); httpClient.addRequestInterceptor(new HttpRequestInterceptor() { @Override public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException { AuthState authState = (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE); CredentialsProvider credsProvider = (CredentialsProvider) context .getAttribute(ClientContext.CREDS_PROVIDER); HttpHost targetHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST); if (authState.getAuthScheme() == null) { AuthScope authScope = new AuthScope(targetHost.getHostName(), targetHost.getPort()); Credentials creds = credsProvider.getCredentials(authScope); if (creds != null) { authState.setAuthScheme(new BasicScheme()); authState.setCredentials(creds); } } } }, 0); httpClient .setHttpRequestRetryHandler(new RetryHandler(DEFAULT_MAX_RETRIES, DEFAULT_RETRY_SLEEP_TIME_MILLIS)); }
From source file:com.jagornet.dhcp.client.ClientSimulatorV4.java
/** * Start sending DHCPv4 DISCOVERs./* w ww .ja va 2s .co m*/ */ public void start() { DatagramChannelFactory factory = new NioDatagramChannelFactory(Executors.newCachedThreadPool()); server = new InetSocketAddress(serverAddr, serverPort); client = new InetSocketAddress(clientPort); ChannelPipeline pipeline = Channels.pipeline(); pipeline.addLast("logger", new LoggingHandler()); pipeline.addLast("encoder", new DhcpV4ChannelEncoder()); pipeline.addLast("decoder", new DhcpV4ChannelDecoder(client, false)); pipeline.addLast("executor", new ExecutionHandler(new OrderedMemoryAwareThreadPoolExecutor(16, 1048576, 1048576))); pipeline.addLast("handler", this); channel = factory.newChannel(pipeline); channel.bind(client); for (int i = 1; i <= numRequests; i++) { executor.execute(new ClientMachine(i)); } synchronized (syncDone) { long ms = timeout * 1000; try { log.info("Waiting total of " + timeout + " milliseconds for completion"); syncDone.wait(ms); } catch (InterruptedException ex) { log.error("Interrupted", ex); } } log.info("Complete: discoversSent=" + discoversSent + " offersReceived=" + offersReceived + " requestsSent=" + requestsSent + " acksReceived=" + acksReceived + " releasesSent=" + releasesSent + " elapsedTime=" + (endTime - startTime) + "ms"); log.info("Shutting down executor..."); executor.shutdownNow(); log.info("Closing channel..."); channel.close(); log.info("Done."); if ((discoversSent.get() == offersReceived.get()) && (requestsSent.get() == acksReceived.get()) && (releasesSent.get() == numRequests)) { System.exit(0); } else { System.exit(1); } }
From source file:com.messi.languagehelper_ja.http.AsyncHttpClient.java
/** * Creates a new AsyncHttpClient.//from w ww . j a v a 2s .co m * * @param schemeRegistry SchemeRegistry to be used */ public AsyncHttpClient(SchemeRegistry schemeRegistry) { BasicHttpParams httpParams = new BasicHttpParams(); ConnManagerParams.setTimeout(httpParams, timeout); ConnManagerParams.setMaxConnectionsPerRoute(httpParams, new ConnPerRouteBean(maxConnections)); ConnManagerParams.setMaxTotalConnections(httpParams, DEFAULT_MAX_CONNECTIONS); HttpConnectionParams.setSoTimeout(httpParams, timeout); HttpConnectionParams.setConnectionTimeout(httpParams, timeout); HttpConnectionParams.setTcpNoDelay(httpParams, true); HttpConnectionParams.setSocketBufferSize(httpParams, DEFAULT_SOCKET_BUFFER_SIZE); HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1); HttpProtocolParams.setUserAgent(httpParams, userAgent); ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(httpParams, schemeRegistry); threadPool = Executors.newCachedThreadPool(); requestMap = new WeakHashMap<Context, List<RequestHandle>>(); clientHeaderMap = new HashMap<String, String>(); httpContext = new SyncBasicHttpContext(new BasicHttpContext()); httpClient = new DefaultHttpClient(cm, httpParams); httpClient.addRequestInterceptor(new HttpRequestInterceptor() { @Override public void process(HttpRequest request, HttpContext context) { if (!request.containsHeader(HEADER_ACCEPT_ENCODING)) { request.addHeader(HEADER_ACCEPT_ENCODING, ENCODING_GZIP); } for (String header : clientHeaderMap.keySet()) { if (request.containsHeader(header)) { Header overwritten = request.getFirstHeader(header); Log.d(LOG_TAG, String.format("Headers were overwritten! (%s | %s) overwrites (%s | %s)", header, clientHeaderMap.get(header), overwritten.getName(), overwritten.getValue())); } request.addHeader(header, clientHeaderMap.get(header)); } } }); httpClient.addResponseInterceptor(new HttpResponseInterceptor() { @Override public void process(HttpResponse response, HttpContext context) { final HttpEntity entity = response.getEntity(); if (entity == null) { return; } final Header encoding = entity.getContentEncoding(); if (encoding != null) { for (HeaderElement element : encoding.getElements()) { if (element.getName().equalsIgnoreCase(ENCODING_GZIP)) { response.setEntity(new InflatingEntity(entity)); break; } } } } }); httpClient.addRequestInterceptor(new HttpRequestInterceptor() { public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException { AuthState authState = (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE); CredentialsProvider credsProvider = (CredentialsProvider) context .getAttribute(ClientContext.CREDS_PROVIDER); HttpHost targetHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST); if (authState.getAuthScheme() == null) { AuthScope authScope = new AuthScope(targetHost.getHostName(), targetHost.getPort()); Credentials creds = credsProvider.getCredentials(authScope); if (creds != null) { authState.setAuthScheme(new BasicScheme()); authState.setCredentials(creds); } } } }, 0); httpClient .setHttpRequestRetryHandler(new RetryHandler(DEFAULT_MAX_RETRIES, DEFAULT_RETRY_SLEEP_TIME_MILLIS)); }
From source file:com.example.administrator.newsdaily.model.httpclient.AsyncHttpClient.java
/** * Creates a new AsyncHttpClient./*w ww .ja v a2 s. c o m*/ * * @param schemeRegistry SchemeRegistry to be used */ public AsyncHttpClient(SchemeRegistry schemeRegistry) { BasicHttpParams httpParams = new BasicHttpParams(); ConnManagerParams.setTimeout(httpParams, timeout); ConnManagerParams.setMaxConnectionsPerRoute(httpParams, new ConnPerRouteBean(maxConnections)); ConnManagerParams.setMaxTotalConnections(httpParams, DEFAULT_MAX_CONNECTIONS); HttpConnectionParams.setSoTimeout(httpParams, timeout); HttpConnectionParams.setConnectionTimeout(httpParams, timeout); HttpConnectionParams.setTcpNoDelay(httpParams, true); HttpConnectionParams.setSocketBufferSize(httpParams, DEFAULT_SOCKET_BUFFER_SIZE); HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1); HttpProtocolParams.setUserAgent(httpParams, String.format("android-async-http/%s (http://loopj.com/android-async-http)", VERSION)); ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(httpParams, schemeRegistry); threadPool = Executors.newCachedThreadPool(); requestMap = new WeakHashMap<Context, List<RequestHandle>>(); clientHeaderMap = new HashMap<String, String>(); httpContext = new SyncBasicHttpContext(new BasicHttpContext()); httpClient = new DefaultHttpClient(cm, httpParams); httpClient.addRequestInterceptor(new HttpRequestInterceptor() { @Override public void process(HttpRequest request, HttpContext context) { if (!request.containsHeader(HEADER_ACCEPT_ENCODING)) { request.addHeader(HEADER_ACCEPT_ENCODING, ENCODING_GZIP); } for (String header : clientHeaderMap.keySet()) { if (request.containsHeader(header)) { Header overwritten = request.getFirstHeader(header); Log.d(LOG_TAG, String.format("Headers were overwritten! (%s | %s) overwrites (%s | %s)", header, clientHeaderMap.get(header), overwritten.getName(), overwritten.getValue())); } request.addHeader(header, clientHeaderMap.get(header)); } } }); httpClient.addResponseInterceptor(new HttpResponseInterceptor() { @Override public void process(HttpResponse response, HttpContext context) { final HttpEntity entity = response.getEntity(); if (entity == null) { return; } final Header encoding = entity.getContentEncoding(); if (encoding != null) { for (HeaderElement element : encoding.getElements()) { if (element.getName().equalsIgnoreCase(ENCODING_GZIP)) { response.setEntity(new InflatingEntity(entity)); break; } } } } }); httpClient.addRequestInterceptor(new HttpRequestInterceptor() { public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException { AuthState authState = (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE); CredentialsProvider credsProvider = (CredentialsProvider) context .getAttribute(ClientContext.CREDS_PROVIDER); HttpHost targetHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST); if (authState.getAuthScheme() == null) { AuthScope authScope = new AuthScope(targetHost.getHostName(), targetHost.getPort()); Credentials creds = credsProvider.getCredentials(authScope); if (creds != null) { authState.setAuthScheme(new BasicScheme()); authState.setCredentials(creds); } } } }, 0); httpClient .setHttpRequestRetryHandler(new RetryHandler(DEFAULT_MAX_RETRIES, DEFAULT_RETRY_SLEEP_TIME_MILLIS)); }
From source file:oz.hadoop.yarn.api.core.LocalApplicationLaunchTests.java
@Test(timeout = 5000) @Ignore // fix to adgust for API changes public void validateJavaContainerLaunchAndVariableProcessTimeWithForcedShutdown() throws Exception { final YarnApplication<Void> yarnApplication = YarnAssembly .forApplicationContainer(VariableProcessingTime.class, ByteBuffer.wrap("Hello".getBytes())) .containerCount(6).memory(512).withApplicationMaster().maxAttempts(2).priority(2) .build("sample-yarn-application"); ExecutorService executor = Executors.newCachedThreadPool(); executor.execute(new Runnable() { @Override/*from w ww . j a va 2s .c o m*/ public void run() { yarnApplication.launch(); } }); // wait till all 6 are active while (yarnApplication.liveContainers() != 6) { LockSupport.parkNanos(10000); } System.out.println("Running: " + yarnApplication.isRunning()); // wait till some begin to shutdown while (yarnApplication.liveContainers() == 6) { LockSupport.parkNanos(10000); } System.out.println("Running: " + yarnApplication.isRunning()); assertTrue(yarnApplication.isRunning()); yarnApplication.terminate(); assertEquals(0, yarnApplication.liveContainers()); assertFalse(yarnApplication.isRunning()); }
From source file:io.freeswitch.outbound.FreeSwitchClient.java
/** * Attempt to establish an authenticated connection to the nominated * FreeSWITCH ESL server socket. This call will block, waiting for an * authentication handshake to occur, or timeout after the supplied number * of seconds.//from w w w. j a v a 2s . c o m * * @param host can be either ip address or hostname * @param port tcp port that server socket is listening on (set in * event_socket_conf.xml) * @param password server event socket is expecting (set in * event_socket_conf.xml) * @param timeoutSeconds number of seconds to wait for the server socket * before aborting * @throws ConnectionFailure * @throws java.lang.InterruptedException */ public void connect(String host, int port, String password, int timeoutSeconds) throws ConnectionFailure, InterruptedException { // If already connected, disconnect first if (canSend()) { close(); } // Configure this client ClientBootstrap bootstrap = new ClientBootstrap(new NioClientSocketChannelFactory( Executors.newCachedThreadPool(), Executors.newCachedThreadPool())); // Add ESL handler DefaultFreeSwitchClientHandler handler = new DefaultFreeSwitchClientHandler(password, protocolListener); bootstrap.setPipelineFactory(new DefaultFreeSwitchClientPipelineFactory(handler)); // Make the connection attempt. ChannelFuture future = bootstrap.connect(new InetSocketAddress(host, port)); // Wait till attempt succeeds, fails or timeouts if (!future.awaitUninterruptibly(timeoutSeconds, TimeUnit.SECONDS)) { throw new ConnectionFailure("Timeout connecting to " + host + ":" + port); } // But may have failed anyway if (!future.isSuccess()) { log.warn("Failed to connect to [{}:{}]", host, port); channel = null; bootstrap.releaseExternalResources(); throw new ConnectionFailure("Could not connect to " + host + ":" + port, future.getCause()); } channel = future.getChannel(); // Wait for the authentication handshake to call back while (!authenticatorResponded.get()) { try { Thread.sleep(250); } catch (InterruptedException e) { // ignore } } if (!authenticated) { throw new ConnectionFailure("Authentication failed: " + authenticationResponse.replyText()); } }