List of usage examples for java.util.concurrent Executors newFixedThreadPool
public static ExecutorService newFixedThreadPool(int nThreads)
From source file:com.taveloper.http.test.PwTest.java
/** * @param args the command line arguments *///from w ww .ja va 2 s . c om public static void main(String[] args) throws IOException, InterruptedException { ExecutorService es = Executors.newFixedThreadPool(1); // ? try { for (int i = 0; i < a.length; i++) { String s1 = a[i]; for (int j = 0; j < a.length; j++) { String s2 = a[j]; Pw pw = new Pw(s1 + s2); es.submit(pw); } } } catch (Exception e) { System.out.println(e.toString()); } if (es.isShutdown()) { } else { Thread.sleep(1000); } }
From source file:com.siva.javamultithreading.MultiThreadExecutor.java
public static void main(String[] args) throws ExecutionException, IOException { //Populate the data List<DomainObject> list = new ArrayList<>(); DomainObject object = null;// www.j a v a2s . c o m for (int i = 0; i < 230000; i++) { object = new DomainObject(); object.setId("ID" + i); object.setName("NAME" + i); object.setComment("COMMENT" + i); list.add(object); } int maxNoOfRows = 40000; int noOfThreads = 1; int remaining = 0; if (list.size() > 40000) { noOfThreads = list.size() / maxNoOfRows; remaining = list.size() % maxNoOfRows; if (remaining > 0) { noOfThreads++; } } List<List<DomainObject>> dos = ListUtils.partition(list, maxNoOfRows); ExecutorService threadPool = Executors.newFixedThreadPool(noOfThreads); CompletionService<HSSFWorkbook> pool = new ExecutorCompletionService<>(threadPool); // Excel creation through multiple threads long startTime = System.currentTimeMillis(); for (List<DomainObject> listObj : dos) { pool.submit(new ExcelChunkSheetWriter(listObj)); } HSSFWorkbook hSSFWorkbook = null; HSSFWorkbook book = new HSSFWorkbook(); HSSFSheet sheet = book.createSheet("Report"); try { for (int i = 0; i < 5; i++) { hSSFWorkbook = pool.take().get(); System.out.println( "sheet row count : sheet.PhysicalNumberOfRows() = " + sheet.getPhysicalNumberOfRows()); int currentCount = sheet.getPhysicalNumberOfRows(); int incomingCount = hSSFWorkbook.getSheetAt(0).getPhysicalNumberOfRows(); if ((currentCount + incomingCount) > 60000) { sheet = book.createSheet("Report" + i); } ExcelUtil.copySheets(book, sheet, hSSFWorkbook.getSheetAt(0)); } } catch (InterruptedException ex) { Logger.getLogger(MultiThreadExecutor.class.getName()).log(Level.SEVERE, null, ex); } catch (ExecutionException ex) { Logger.getLogger(MultiThreadExecutor.class.getName()).log(Level.SEVERE, null, ex); } try { writeFile(book, new FileOutputStream("Report.xls")); } catch (Exception e) { e.printStackTrace(); } //System.out.println("No of Threads : " + noOfThreads + " Size : " + list.size() + " remaining : " + remaining); long endTime = System.currentTimeMillis(); System.out.println("Time taken: " + (endTime - startTime) + " ms"); threadPool.shutdown(); //startProcess(); }
From source file:interoperabilite.webservice.fluent.FluentAsync.java
public static void main(String[] args) throws Exception { // Use pool of two threads ExecutorService threadpool = Executors.newFixedThreadPool(2); Async async = Async.newInstance().use(threadpool); Request[] requests = new Request[] { Request.Get("http://www.google.com/"), Request.Get("http://www.yahoo.com/"), Request.Get("http://www.apache.com/"), Request.Get("http://www.apple.com/") }; Queue<Future<Content>> queue = new LinkedList<Future<Content>>(); // Execute requests asynchronously for (final Request request : requests) { Future<Content> future = async.execute(request, new FutureCallback<Content>() { @Override//w w w . ja v a2s. c om public void failed(final Exception ex) { System.out.println(ex.getMessage() + ": " + request); } @Override public void completed(final Content content) { System.out.println("Request completed: " + request); } @Override public void cancelled() { } }); queue.add(future); } while (!queue.isEmpty()) { Future<Content> future = queue.remove(); try { future.get(); } catch (ExecutionException ex) { } } System.out.println("Done"); threadpool.shutdown(); }
From source file:async.nio2.Main.java
public static void main(String[] args) throws IOException, InterruptedException, ExecutionException { if (args.length == 3) { PORT = Integer.valueOf(args[0]); NO_CLIENTS = Integer.valueOf(args[1]); NO_SAMPLES = Integer.valueOf(args[2]); }//from w ww . ja v a2 s .c o m if (PORT < 0) { System.err.println("Error: port < 0"); System.exit(1); } if (NO_CLIENTS < 1) { System.err.println("Error: #clients < 1"); System.exit(1); } if (NO_SAMPLES < 1) { System.err.println("Error: #samples < 1"); System.exit(1); } AsynchronousChannelGroup groupServer = AsynchronousChannelGroup .withThreadPool(Executors.newFixedThreadPool(1)); AsynchronousChannelGroup groupClient = AsynchronousChannelGroup .withThreadPool(Executors.newFixedThreadPool(1)); Server server = Server.newInstance(new InetSocketAddress("localhost", PORT), groupServer); InetSocketAddress localAddress = server.getLocalAddress(); String hostname = localAddress.getHostName(); int port = localAddress.getPort(); ExecutorService es = Executors.newFixedThreadPool(2); System.out.printf("%03d clients on %s:%d, %03d runs each. All times in s.%n", NO_CLIENTS, hostname, port, NO_SAMPLES); range(0, NO_CLIENTS).unordered().parallel() .mapToObj(i -> CompletableFuture.supplyAsync(newClient(localAddress, groupClient), es).join()) .map(array -> Arrays.stream(array).reduce(new DescriptiveStatistics(), Main::accumulate, Main::combine)) .map(Main::toEvaluationString).forEach(System.out::println); es.shutdown(); es.awaitTermination(5, TimeUnit.SECONDS); groupClient.shutdown(); groupClient.awaitTermination(5, TimeUnit.SECONDS); server.close(); groupServer.shutdown(); groupServer.awaitTermination(5, TimeUnit.SECONDS); }
From source file:org.wso2.carbon.sample.tfl.TflEventDispatcher.java
public static void main(String[] args) { EventDispatcher trafficDisruptionData = new EventDispatcher( "http://localhost:9763/endpoints/GpsDataOverHttpTrafficStream", "tfl-traffic-data.out", 1000); EventDispatcher busTrafficData = new EventDispatcher( "http://localhost:9763/endpoints/BusTrafficCsvReceiver", "tfl-bus-data.out", 50); EventDispatcher busStopData = new EventDispatcher("http://localhost:9763/endpoints/BusTrafficCsvReceiver", "tfl-bus-stop-data.out", 5); EventDispatcher timeTableData = new EventDispatcher("http://localhost:9763/endpoints/TimeTableCsvReceiver", "tfl-timetable-data.out", 5); ExecutorService executorService = Executors.newFixedThreadPool(5); // executorService.submit(trafficDisruptionData); // timeTableData.run(); // busStopData.run(); executorService.submit(busTrafficData); }
From source file:koper.demo.performance.SendDataEventMsgPerf.java
/** * DataEventMsg ?/* w ww . j av a 2s. c o m*/ * @param args ?:??? * ?:?????? sleep */ public static void main(String[] args) throws Exception { ApplicationContext context = new ClassPathXmlApplicationContext("kafka/context-data-message.xml", "kafka/context-data-producer.xml"); Order order = new Order(); order.setId(100); order.setOrderNo("order_no"); order.setCreatedTime("oroder_created_time"); OrderService orderService = (OrderService) context.getBean("orderServiceImpl"); int threadNum = 1; long sleepMs = 1000L; if (args.length >= 1) { threadNum = Integer.parseInt(args[0]); sleepMs = Long.parseLong(args[1]); } final long finalSleepMs = sleepMs; ExecutorService executorService = Executors.newFixedThreadPool(threadNum); for (int i = 0; i < threadNum; ++i) { executorService.execute(() -> { while (true) { orderService.insertOrder(order); try { Thread.sleep(finalSleepMs); } catch (Exception e) { e.printStackTrace(); } } }); } }
From source file:at.tfr.securefs.client.SecurefsClient.java
public static void main(String[] args) throws Exception { SecurefsClient client = new SecurefsClient(); try {// w w w.j a v a 2s. com client.parse(args); if (client.asyncTest) { ExecutorService executor = Executors.newFixedThreadPool(client.threads); for (int i = 0; i < client.threads; i++) { executor.submit(client); } executor.shutdown(); executor.awaitTermination(10, TimeUnit.MINUTES); } else { client.run(); } } catch (Throwable e) { HelpFormatter hf = new HelpFormatter(); hf.printHelp(SecurefsClient.class.getSimpleName(), client.options); e.printStackTrace(); } }
From source file:com.lxf.spider.client.ClientWithRequestFuture.java
public static void main(String[] args) throws Exception { // the simplest way to create a HttpAsyncClientWithFuture HttpClient httpclient = HttpClientBuilder.create().setMaxConnPerRoute(5).setMaxConnTotal(5).build(); ExecutorService execService = Executors.newFixedThreadPool(5); FutureRequestExecutionService requestExecService = new FutureRequestExecutionService(httpclient, execService);//from w w w . j a v a 2s . c om try { // Because things are asynchronous, you must provide a ResponseHandler ResponseHandler<Boolean> handler = new ResponseHandler<Boolean>() { public Boolean handleResponse(HttpResponse response) throws ClientProtocolException, IOException { // simply return true if the status was OK return response.getStatusLine().getStatusCode() == 200; } }; // Simple request ... HttpGet request1 = new HttpGet("http://google.com"); HttpRequestFutureTask<Boolean> futureTask1 = requestExecService.execute(request1, HttpClientContext.create(), handler); Boolean wasItOk1 = futureTask1.get(); System.out.println("It was ok? " + wasItOk1); // Cancel a request try { HttpGet request2 = new HttpGet("http://google.com"); HttpRequestFutureTask<Boolean> futureTask2 = requestExecService.execute(request2, HttpClientContext.create(), handler); futureTask2.cancel(true); Boolean wasItOk2 = futureTask2.get(); System.out.println("It was cancelled so it should never print this: " + wasItOk2); } catch (CancellationException e) { System.out.println("We cancelled it, so this is expected"); } // Request with a timeout HttpGet request3 = new HttpGet("http://google.com"); HttpRequestFutureTask<Boolean> futureTask3 = requestExecService.execute(request3, HttpClientContext.create(), handler); Boolean wasItOk3 = futureTask3.get(10, TimeUnit.SECONDS); System.out.println("It was ok? " + wasItOk3); FutureCallback<Boolean> callback = new FutureCallback<Boolean>() { public void completed(Boolean result) { System.out.println("completed with " + result); } public void failed(Exception ex) { System.out.println("failed with " + ex.getMessage()); } public void cancelled() { System.out.println("cancelled"); } }; // Simple request with a callback HttpGet request4 = new HttpGet("http://google.com"); // using a null HttpContext here since it is optional // the callback will be called when the task completes, fails, or is cancelled HttpRequestFutureTask<Boolean> futureTask4 = requestExecService.execute(request4, HttpClientContext.create(), handler, callback); Boolean wasItOk4 = futureTask4.get(10, TimeUnit.SECONDS); System.out.println("It was ok? " + wasItOk4); } finally { requestExecService.close(); } }
From source file:interoperabilite.webservice.client.ClientWithRequestFuture.java
public static void main(String[] args) throws Exception { // the simplest way to create a HttpAsyncClientWithFuture HttpClient httpclient = HttpClientBuilder.create().setMaxConnPerRoute(5).setMaxConnTotal(5).build(); ExecutorService execService = Executors.newFixedThreadPool(5); FutureRequestExecutionService requestExecService = new FutureRequestExecutionService(httpclient, execService);/* w w w . j a v a 2 s .c o m*/ try { // Because things are asynchronous, you must provide a ResponseHandler ResponseHandler<Boolean> handler = new ResponseHandler<Boolean>() { @Override public Boolean handleResponse(HttpResponse response) throws ClientProtocolException, IOException { // simply return true if the status was OK return response.getStatusLine().getStatusCode() == 200; } }; // Simple request ... HttpGet request1 = new HttpGet("http://httpbin.org/get"); HttpRequestFutureTask<Boolean> futureTask1 = requestExecService.execute(request1, HttpClientContext.create(), handler); Boolean wasItOk1 = futureTask1.get(); System.out.println("It was ok? " + wasItOk1); // Cancel a request try { HttpGet request2 = new HttpGet("http://httpbin.org/get"); HttpRequestFutureTask<Boolean> futureTask2 = requestExecService.execute(request2, HttpClientContext.create(), handler); futureTask2.cancel(true); Boolean wasItOk2 = futureTask2.get(); System.out.println("It was cancelled so it should never print this: " + wasItOk2); } catch (CancellationException e) { System.out.println("We cancelled it, so this is expected"); } // Request with a timeout HttpGet request3 = new HttpGet("http://httpbin.org/get"); HttpRequestFutureTask<Boolean> futureTask3 = requestExecService.execute(request3, HttpClientContext.create(), handler); Boolean wasItOk3 = futureTask3.get(10, TimeUnit.SECONDS); System.out.println("It was ok? " + wasItOk3); FutureCallback<Boolean> callback = new FutureCallback<Boolean>() { @Override public void completed(Boolean result) { System.out.println("completed with " + result); } @Override public void failed(Exception ex) { System.out.println("failed with " + ex.getMessage()); } @Override public void cancelled() { System.out.println("cancelled"); } }; // Simple request with a callback HttpGet request4 = new HttpGet("http://httpbin.org/get"); // using a null HttpContext here since it is optional // the callback will be called when the task completes, fails, or is cancelled HttpRequestFutureTask<Boolean> futureTask4 = requestExecService.execute(request4, HttpClientContext.create(), handler, callback); Boolean wasItOk4 = futureTask4.get(10, TimeUnit.SECONDS); System.out.println("It was ok? " + wasItOk4); } finally { requestExecService.close(); } }
From source file:com.weibo.motan.demo.client.DemoRpcClient.java
public static void main(String[] args) throws Exception { final DescriptiveStatistics stats = new SynchronizedDescriptiveStatistics(); int threads = Integer.parseInt(args[0]); DubboBenchmark.BenchmarkMessage msg = prepareArgs(); final byte[] msgBytes = msg.toByteArray(); int n = 1000000; final CountDownLatch latch = new CountDownLatch(n); ExecutorService es = Executors.newFixedThreadPool(threads); final AtomicInteger trans = new AtomicInteger(0); final AtomicInteger transOK = new AtomicInteger(0); ApplicationContext ctx = new ClassPathXmlApplicationContext( new String[] { "classpath:motan_demo_client.xml" }); MotanDemoService service = (MotanDemoService) ctx.getBean("motanDemoReferer"); long start = System.currentTimeMillis(); for (int i = 0; i < n; i++) { es.submit(() -> {/*from w ww .j a v a 2 s .c o m*/ try { long t = System.currentTimeMillis(); DubboBenchmark.BenchmarkMessage m = testSay(service, msgBytes); t = System.currentTimeMillis() - t; stats.addValue(t); trans.incrementAndGet(); if (m != null && m.getField1().equals("OK")) { transOK.incrementAndGet(); } } finally { latch.countDown(); } }); } latch.await(); start = System.currentTimeMillis() - start; System.out.printf("sent requests : %d\n", n); System.out.printf("received requests : %d\n", trans.get()); System.out.printf("received requests_OK : %d\n", transOK.get()); System.out.printf("throughput (TPS) : %d\n", n * 1000 / start); System.out.printf("mean: %f\n", stats.getMean()); System.out.printf("median: %f\n", stats.getPercentile(50)); System.out.printf("max: %f\n", stats.getMax()); System.out.printf("min: %f\n", stats.getMin()); System.out.printf("99P: %f\n", stats.getPercentile(90)); }