List of usage examples for java.util.concurrent ExecutorService shutdown
void shutdown();
From source file:agileinterop.AgileInterop.java
private static JSONObject getPSRData(String body) throws ParseException, InterruptedException, APIException { // Parse body as JSON JSONParser parser = new JSONParser(); JSONArray jsonBody = (JSONArray) parser.parse(body); Map<String, Object> data = new HashMap<>(); class GetObjectData implements Runnable { private String psrNumber; private Map<String, Object> data; private IServiceRequest psr; public GetObjectData(String psrNumber, Map<String, Object> data) throws APIException, InterruptedException { this.psrNumber = psrNumber; this.data = data; psr = (IServiceRequest) Agile.session.getObject(IServiceRequest.OBJECT_TYPE, psrNumber); }/*from w ww . j a v a 2s . c o m*/ @Override public void run() { this.data.put(psrNumber, new HashMap<String, Object>()); try { if (psr != null) { getCellValues(); getAttachments(); getHistory(); } } catch (APIException ex) { Logger.getLogger(AgileInterop.class.getName()).log(Level.SEVERE, null, ex); } } private void getCellValues() throws APIException { Map<String, Object> cellValues = new HashMap<>(); long startTime = System.currentTimeMillis(); // Get cell values ICell[] cells = psr.getCells(); for (ICell cell : cells) { if (cell.getDataType() == DataTypeConstants.TYPE_DATE) { if (cell.getValue() != null) { SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss a zz"); sdf.setTimeZone(TimeZone.getTimeZone("Europe/London")); cellValues.put(cell.getName(), sdf.format((Date) cell.getValue())); } else { cellValues.put(cell.getName(), cell.toString()); } } else { cellValues.put(cell.getName(), cell.toString()); } } long endTime = System.currentTimeMillis(); String logMessage = String.format("%s: getCellValues executed in %d milliseconds", psrNumber, endTime - startTime); System.out.println(logMessage); ((HashMap<String, Object>) this.data.get(psrNumber)).put("cellValues", cellValues); } private void getAttachments() throws APIException { List<Map<String, String>> attachments = new ArrayList<>(); long startTime = System.currentTimeMillis(); // Get attachments information ITable table = psr.getTable("Attachments"); ITwoWayIterator tableIterator = table.getTableIterator(); while (tableIterator.hasNext()) { IRow row = (IRow) tableIterator.next(); Map<String, String> attachment = new HashMap<>(); ICell[] cells = row.getCells(); for (ICell cell : cells) { if (cell.getDataType() == DataTypeConstants.TYPE_DATE) { if (cell.getValue() != null) { SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss a zz"); sdf.setTimeZone(TimeZone.getTimeZone("Europe/London")); attachment.put(cell.getName(), sdf.format((Date) cell.getValue())); } else { attachment.put(cell.getName(), cell.toString()); } } else { attachment.put(cell.getName(), cell.toString()); } } attachments.add(attachment); } long endTime = System.currentTimeMillis(); String logMessage = String.format("%s: getAttachments executed in %d milliseconds", psrNumber, endTime - startTime); System.out.println(logMessage); ((HashMap<String, Object>) this.data.get(psrNumber)).put("attachments", attachments); } private void getHistory() throws APIException { List<Map<String, String>> histories = new ArrayList<>(); long startTime = System.currentTimeMillis(); // Get history information ITable table = psr.getTable("History"); ITwoWayIterator tableIterator = table.getTableIterator(); while (tableIterator.hasNext()) { IRow row = (IRow) tableIterator.next(); Map<String, String> history = new HashMap<>(); ICell[] cells = row.getCells(); for (ICell cell : cells) { if (cell.getDataType() == DataTypeConstants.TYPE_DATE) { if (cell.getValue() != null) { SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss a zz"); sdf.setTimeZone(TimeZone.getTimeZone("Europe/London")); history.put(cell.getName(), sdf.format((Date) cell.getValue())); } else { history.put(cell.getName(), cell.toString()); } } else { history.put(cell.getName(), cell.toString()); } } histories.add(history); } long endTime = System.currentTimeMillis(); String logMessage = String.format("%s: getHistory executed in %d milliseconds", psrNumber, endTime - startTime); System.out.println(logMessage); ((HashMap<String, Object>) this.data.get(psrNumber)).put("history", histories); } } synchronized (data) { // Do something funky with the first one Thread t = new Thread(new GetObjectData(jsonBody.get(0).toString(), data)); t.start(); t.join(); ExecutorService executor = Executors.newFixedThreadPool(10); for (Object object : jsonBody.subList(1, jsonBody.size() - 1)) { executor.execute(new Thread(new GetObjectData(object.toString(), data))); } executor.shutdown(); while (!executor.isTerminated()) { } } JSONObject obj = new JSONObject(); obj.put("data", data); return obj; }
From source file:com.dsclab.loader.app.Loader.java
public static void load(Configs prop) throws SQLException, ClassNotFoundException, InterruptedException, ExecutionException { int readThread = prop.getReadThread(); int writeThread = prop.getWriteThread(); ExecutorService readExecutor = Executors.newFixedThreadPool(readThread); ExecutorService writeExecutor = Executors.newFixedThreadPool(writeThread); LOG.info("Start load: writeThread:" + writeThread + ", readThread:" + readThread); BlockingQueue<List<String>> contentQueue = new LinkedBlockingQueue<>(); int tableCount = tableTask.size(); int sum = 0;/*ww w. j a v a 2s . c om*/ for (int i = 0; i < tableCount; i++) { sum = sum + tableTask.get(i).getTaskSqlList().size(); } for (int i = 0; i < sum; i++) { readExecutor.submit(new ProducerThread(prop.getInputURL(), contentQueue)); writeExecutor.submit(new ConsumerThread(prop.getOutputURL(), contentQueue)); } readExecutor.shutdown(); readExecutor.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS); System.out.println("[CHIA7712] read threads end"); writeExecutor.shutdown(); writeExecutor.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS); System.out.println("[CHIA7712] write threads end"); }
From source file:org.lambdamatic.internal.elasticsearch.codec.ObjectMapperFactory.java
/** * Initializes an {@link ObjectMapper} configured with mixins to support serialization and * deserialization of all built-in and user-defined domain types. * <p>//w w w. j a va 2s. c om * <strong>Note:</strong>The {@link ObjectMapper} is instantiated and initialized once and then * kept in cache, so multiple calls will retrieve the same instance. * </p> * * @return the {@link ObjectMapper} * */ public static ObjectMapper getObjectMapper() { if (instance.objectMapper == null) { LOGGER.info("Initializing the ObjectMapper"); final ObjectMapper mapper = new ObjectMapper(); final ExecutorService availableProcessorsThreadPool = Executors .newFixedThreadPool(Runtime.getRuntime().availableProcessors()); final Reflections reflections = new Reflections(new ConfigurationBuilder() // TODO: allow for configuration settings to reduce the scope of searching, using package // names instead of a classloader .setUrls(ClasspathHelper.forJavaClassPath()) // .setUrls(ClasspathHelper.forClassLoader()) .setScanners(new SubTypesScanner(), new TypeAnnotationsScanner()) .setExecutorService(availableProcessorsThreadPool)); // thread pool must be closed after it has been used, to avoid leaking threads in the JVM. availableProcessorsThreadPool.shutdown(); // final Reflections reflections = new Reflections(); reflections.getTypesAnnotatedWith(Mixin.class).stream().forEach(mixin -> { final Mixin mixinAnnotation = mixin.getAnnotation(Mixin.class); LOGGER.info("Adding mixin {} to {}", mixin, mixinAnnotation.target()); mapper.addMixIn(mixinAnnotation.target(), mixin); }); mapper.registerModule(new JavaTimeModule()); // configure LocalDate serialization as string with pattern: YYYY-mm-dd mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false); instance.objectMapper = mapper; } return instance.objectMapper; }
From source file:gda.device.detector.mythen.data.MythenDataFileUtils.java
/** * Reads the specified Mythen processed data files. * //from ww w . jav a 2s .co m * @param filenames * the names of the files to read * @return 3D double array of data */ public static double[][][] readMythenProcessedDataFiles(String filenames[]) { // 3D array of data; will be filled in by tasks (one task per file to be loaded) final double[][][] data = new double[filenames.length][][]; // thread pool for loading files // 4 threads seems to give good results ExecutorService executor = Executors.newFixedThreadPool(4); // create and execute a task for each file to be loaded for (int i = 0; i < filenames.length; i++) { final int index = i; final String filename = filenames[i]; Runnable r = new Runnable() { @Override public void run() { data[index] = readMythenProcessedDataFile(filename, false); } }; executor.execute(r); } // wait until executor has shut down executor.shutdown(); try { boolean terminated = executor.awaitTermination(1, TimeUnit.MINUTES); if (!terminated) { throw new Exception("Timed out waiting for files to load"); } } catch (Exception e) { throw new RuntimeException("Unable to load data", e); } return data; }
From source file:com.laudandjolynn.mytv.Main.java
/** * ?// w ww . j a v a 2 s . c o m * * @param data * @param tvService */ private static void createEverydayCron(final MyTvData data, final TvService tvService) { ScheduledExecutorService scheduled = new ScheduledThreadPoolExecutor(3, new BasicThreadFactory.Builder().namingPattern("Mytv_Scheduled_Task").build()); Date today = new Date(); String nextWeek = DateUtils.date2String(DateUtils.nextWeek(today), "yyyy-MM-dd 00:01:00"); long crawlTaskInitDelay = (DateUtils.string2Date(nextWeek).getTime() - today.getTime()) / 1000; logger.info("cron crawler task will be automatic start after " + crawlTaskInitDelay + " seconds at " + nextWeek); scheduled.scheduleWithFixedDelay(new Runnable() { @Override public void run() { Date[] weeks = DateUtils.getWeek(new Date()); logger.info("begin to crawl program table of " + Arrays.deepToString(weeks)); ExecutorService executorService = Executors.newFixedThreadPool(Constant.CPU_PROCESSOR_NUM, new BasicThreadFactory.Builder().namingPattern("Mytv_Schedule_Crawl_Program_Table_%d") .build()); List<TvStation> stationList = tvService.getDisplayedTvStation(); for (Date date : weeks) { crawlAllProgramTable(stationList, executorService, DateUtils.date2String(date, "yyyy-MM-dd"), tvService); } executorService.shutdown(); } }, crawlTaskInitDelay, 604860, TimeUnit.SECONDS); // ?? String nextDate = DateUtils.tommorow() + " 23:00:00"; long commonInitDelay = (DateUtils.string2Date(nextDate).getTime() - today.getTime()) / 1000; logger.info("cron refresh proxy task will be automatic start after " + commonInitDelay + " seconds at " + nextDate); scheduled.scheduleWithFixedDelay(new Runnable() { @Override public void run() { logger.info("begin to refresh proxies."); MyTvProxyManager.getInstance().refresh(); } }, commonInitDelay, 86400, TimeUnit.SECONDS); // logger.info("cron refresh cache task will be automatic start after " + commonInitDelay + " seconds at " + nextDate); scheduled.scheduleWithFixedDelay(new Runnable() { @Override public void run() { logger.info("begin to refresh caches."); makeCache(tvService); } }, commonInitDelay, 86400, TimeUnit.SECONDS); // scheduled????? // scheduled.shutdown(); }
From source file:it.unibo.alchemist.language.EnvironmentBuilder.java
private static <T> Future<Result<T>> build(final EnvironmentBuilder<T> builder) { final ExecutorService ex = Executors.newSingleThreadExecutor(); final Future<Result<T>> result = ex.submit(() -> { builder.buildEnvironment();// w w w. j a va2s . c o m return Result.build(builder.result, builder.random); }); ex.shutdown(); return result; }
From source file:no.ntnu.idi.socialhitchhiking.client.RequestTask.java
/** * Static method which adds elements and data to an xml file and sends it as a string to the server. * /*from w w w .ja va 2 s. c o m*/ * @param req - {@link Request} * @return returns a subclass of {@link Response} to the input {@link Request} * @throws ClientProtocolException * @throws MalformedURLException * @throws FileNotFoundException * @throws IOException * @throws ExecutionException * @throws InterruptedException */ public static Response sendRequest(final Request req, final Context c) throws ClientProtocolException, IOException, InterruptedException, ExecutionException { /** * Code for putting all all network communication on separate thread as required by higher Android APIs */ ExecutorService executor = Executors.newSingleThreadExecutor(); Callable<Response> callable = new Callable<Response>() { @Override /** * This contains the actual code for initiating the communication */ public Response call() throws ClientProtocolException, IOException { String xml = RequestSerializer.serialize(req); con = c; String url = con.getResources().getString(R.string.server_url); RequestTask requestTask = new RequestTask(url, xml); return ResponseParser.parse(requestTask.getResponse()); } }; /** * Execute and retrieve result from network operation */ Future<Response> future = executor.submit(callable); Response ret = future.get(); executor.shutdown(); return ret; }
From source file:agileinterop.AgileInterop.java
private static JSONObject getPSRList(String body) throws ParseException, InterruptedException, java.text.ParseException, Exception { // Parse body as JSON JSONParser parser = new JSONParser(); JSONObject jsonBody = (JSONObject) parser.parse(body); Date startDateOriginated = new SimpleDateFormat("MM/dd/yyyy") .parse(jsonBody.get("startDateOriginated").toString()); Date endDateOriginated = new SimpleDateFormat("MM/dd/yyyy") .parse(jsonBody.get("endDateOriginated").toString()); List<String> data = new ArrayList<>(); class getPSRListForDate implements Runnable { private Date dateOriginated; private List<String> data; public getPSRListForDate(Date dateOriginated, List<String> data) { this.dateOriginated = dateOriginated; this.data = data; }//from www . ja v a 2 s.c o m public getPSRListForDate(List<String> data) { this.data = data; } @Override public void run() { try { String dateOriginatedString = new SimpleDateFormat("MM/dd/yyyy").format(dateOriginated); Long startTime = System.currentTimeMillis(); IQuery query = (IQuery) Agile.session.createObject(IQuery.OBJECT_TYPE, "Product Service Requests"); String criteria = "[Cover Page.Date Originated] == '" + dateOriginatedString + " 12:00:00 AM GMT' AND " + "[Cover Page.Type] IN ('Customer Complaint', 'Customer Inquiry', 'Partner Complaint', " + "'Reportable Malfunction / Adverse Event', 'Ancillary Devices & Applications', 'Distributors / Partners', " + "'MDR Decision Tree', 'Investigation Report - No RGA', 'Investigation Report - RGA')"; query.setCriteria(criteria); query.setResultAttributes(new Integer[] { 4856 }); // 4856 = Object ID of [Cover Page.PSR Number] ITable queryResults = query.execute(); queryResults.setPageSize(5000); ITwoWayIterator tableIterator = queryResults.getTableIterator(); while (tableIterator.hasNext()) { IRow row = (IRow) tableIterator.next(); data.add(row.getCell(4856).toString()); // 4856 = Object ID of [Cover Page.PSR Number] } Long endTime = System.currentTimeMillis(); String logMessage = String.format("getPSRList: Query for %s executed in %d milliseconds", new SimpleDateFormat("yyyy-MM-dd").format(dateOriginated), endTime - startTime); System.out.println(logMessage); } catch (APIException ex) { Logger.getLogger(AgileInterop.class.getName()).log(Level.SEVERE, null, ex); } } } if (startDateOriginated.after(endDateOriginated)) { throw new Exception("startDateOriginated is after endDateOriginated. This makes no sense, silly."); } synchronized (data) { Date currentDateOriginated = startDateOriginated; ExecutorService executor = Executors.newFixedThreadPool(6); do { executor.execute(new Thread(new getPSRListForDate(currentDateOriginated, data))); Calendar c = Calendar.getInstance(); c.setTime(currentDateOriginated); c.add(Calendar.DATE, 1); currentDateOriginated = c.getTime(); } while (currentDateOriginated.before(endDateOriginated) | currentDateOriginated.equals(endDateOriginated)); executor.shutdown(); while (!executor.isTerminated()) { } } JSONObject obj = new JSONObject(); obj.put("data", data); return obj; }
From source file:com.dattack.dbtools.drules.engine.DrulesEngine.java
private static SourceResultGroup getSourceResultsList(final List<SourceBean> sourceList) throws DrulesNestableException { final ExecutorService executorService = Executors.newCachedThreadPool(createThreadFactory()); final List<Future<SourceResult>> futureList = new ArrayList<>(); for (final SourceBean sourceBean : sourceList) { futureList.add(executorService.submit(new SourceExecutor(sourceBean, ConfigurationUtils.cloneConfiguration(ThreadContext.getInstance().getConfiguration())))); }//from w w w .j av a 2 s . c o m final SourceResultGroup sourceResultList = new SourceResultGroup(); for (final Future<SourceResult> future : futureList) { try { sourceResultList.add(future.get()); } catch (InterruptedException | ExecutionException e) { throw new DrulesNestableException(e); } } executorService.shutdown(); return sourceResultList; }
From source file:ejp.examples.MultiThreadedWithConnectionPooling.java
static void execute(final DatabaseManager dbm) throws DatabaseException, InterruptedException { long time = System.currentTimeMillis(); ExecutorService exec = Executors.newFixedThreadPool(100); System.out.println("\n\nWorking ..."); Runnable runnable = new Runnable() { public void run() { for (int t = 0; t < 100; t++) { try { new UpdateManager(dbm) { public void run() throws DatabaseException { for (int j = 0; j < 100; j++) { saveObject(new Dog(String.valueOf(Count.get()), Count.get())); Count.count(); }/*from w w w .j av a 2 s. c o m*/ } }.executeBatchUpdates(); } catch (DatabaseException e) { e.printStackTrace(); } } } }; for (int i = 0; i < 100; i++) { exec.execute(runnable); } exec.shutdown(); exec.awaitTermination(100, TimeUnit.SECONDS); time = (System.currentTimeMillis() - time) / 1000; System.out.println("\n\n" + Count.count + " dogs added to database in " + time + " seconds"); Long count = ((Collection<Long>) dbm.executeQuery(new ArrayList<Long>(), true, "select count(*) from dog")) .toArray(new Long[1])[0]; System.out.println("select count(*) from dog = " + count); }