List of usage examples for java.util.concurrent LinkedBlockingQueue LinkedBlockingQueue
public LinkedBlockingQueue()
From source file:Test.java
public static void main(String[] args) throws Exception { LinkedBlockingQueue<String> queue = new LinkedBlockingQueue<String>(); FileOutputStream fos = new FileOutputStream("out.log"); DataOutputStream dos = new DataOutputStream(fos); while (!queue.isEmpty()) { dos.writeUTF(queue.take());/*from w w w . j a va 2s . c om*/ } }
From source file:PoolSize.java
public static void main(String[] args) { ThreadPoolExecutor executor = new ThreadPoolExecutor(10, 20, 60L, TimeUnit.SECONDS, new LinkedBlockingQueue()); System.out.println(executor.getPoolSize()); }
From source file:Test.java
public static void main(String[] args) throws InterruptedException { BlockingQueue<Runnable> queue = new LinkedBlockingQueue<Runnable>(); for (int i = 0; i < 10; i++) { final int localI = i; queue.add(new Runnable() { public void run() { doExpensiveOperation(localI); }/* w w w .j a v a 2 s . c o m*/ }); } ThreadPoolExecutor executor = new ThreadPoolExecutor(10, 10, 1000, TimeUnit.MILLISECONDS, queue); executor.prestartAllCoreThreads(); executor.shutdown(); executor.awaitTermination(100000, TimeUnit.SECONDS); }
From source file:MainClass.java
public static void main(String[] args) { int nTasks = 5; long n = 1000L; int tpSize = 10; ThreadPoolExecutor tpe = new ThreadPoolExecutor(tpSize, tpSize, 50000L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>()); Task[] tasks = new Task[nTasks]; for (int i = 0; i < nTasks; i++) { tasks[i] = new Task(n, "Task " + i); tpe.execute(tasks[i]);/* w w w . ja v a 2 s.c om*/ } tpe.shutdown(); }
From source file:PrepareProduction.java
public static void main(String[] args) throws Exception { BlockingQueue<String> q = new LinkedBlockingQueue<String>(); Thread p1 = new Thread(new PrepareProduction(q)); Thread c1 = new Thread(new DoProduction(q)); p1.start();//from ww w . ja v a 2 s .com c1.start(); p1.join(); c1.join(); }
From source file:httpscheduler.HttpScheduler.java
/** * @param args the command line arguments * @throws java.lang.Exception// ww w . ja v a2 s.co m */ public static void main(String[] args) throws Exception { if (args.length != 2) { System.err.println("Invalid command line parameters for worker"); System.exit(-1); } int fixedExecutorSize = 4; //Creating fixed size executor ThreadPoolExecutor taskCommExecutor = new ThreadPoolExecutor(fixedExecutorSize, fixedExecutorSize, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>()); // Used for late binding JobMap jobMap = new JobMap(); // Set port number int port = Integer.parseInt(args[0]); // Set worker mode String mode = args[1].substring(2); // Set up the HTTP protocol processor HttpProcessor httpproc = HttpProcessorBuilder.create().add(new ResponseDate()) .add(new ResponseServer("Test/1.1")).add(new ResponseContent()).add(new ResponseConnControl()) .build(); // Set up request handlers UriHttpRequestHandlerMapper reqistry = new UriHttpRequestHandlerMapper(); // Different handlers for late binding and generic cases if (mode.equals("late")) reqistry.register("*", new LateBindingRequestHandler(taskCommExecutor, jobMap)); else reqistry.register("*", new GenericRequestHandler(taskCommExecutor, mode)); // Set up the HTTP service HttpService httpService = new HttpService(httpproc, reqistry); SSLServerSocketFactory sf = null; // create a thread to listen for possible client available connections Thread t; if (mode.equals("late")) t = new LateBindingRequestListenerThread(port, httpService, sf); else t = new GenericRequestListenerThread(port, httpService, sf); System.out.println("Request Listener Thread created"); t.setDaemon(false); t.start(); // main thread should wait for the listener to exit before shutdown the // task executor pool t.join(); // shutdown task executor pool and wait for any taskCommExecutor thread // still running taskCommExecutor.shutdown(); while (!taskCommExecutor.isTerminated()) { } System.out.println("Finished all task communication executor threads"); System.out.println("Finished all tasks"); }
From source file:org.sourcepit.docker.watcher.Main.java
public static void main(String[] args) throws IOException { final HttpClientFactory clientFactory = new HttpClientFactory() { @Override//www.j ava2 s . c o m public CloseableHttpClient createHttpClient() { return HttpClients.createDefault(); } }; final String dockerDaemonUri = "http://192.168.56.101:2375"; final String consulAgentUri = "http://192.168.56.101:8500"; final BlockingQueue<List<JsonObject>> queue = new LinkedBlockingQueue<>(); final ConsulForwarder consulForwarder = new ConsulForwarder(clientFactory.createHttpClient(), consulAgentUri); final Thread containerStateDispatcher = new Thread("Consul Forwarder") { @Override public void run() { while (true) { try { consulForwarder.forward(queue.take()); } catch (InterruptedException e) { break; } catch (Exception e) { LOG.error("Error while forwarding Docker container state to Consul.", e); } } } }; containerStateDispatcher.start(); final DockerWatcher watcher = new DockerWatcher(clientFactory, dockerDaemonUri) { @Override protected void handle(List<JsonObject> containerState) { queue.add(containerState); } }; Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { watcher.stop(); while (containerStateDispatcher.isAlive()) { containerStateDispatcher.interrupt(); try { Thread.sleep(100L); } catch (InterruptedException e) { } } } }); watcher.start(); }
From source file:org.sourcepit.consul.forwarder.Main.java
public static void main(String[] args) { final String dockerUri = "http://192.168.56.101:2375"; final String consulUri = "http://192.168.56.101:8500"; final int fetchConsulStateInterval = 30; final int fetchDockerStateInterval = 30; final int dispatchItemsInterval = 2; final int requestDockerStateDelay = 5; PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(); connManager.setDefaultMaxPerRoute(10); final HttpClient httpClient = HttpClients.createMinimal(connManager); final BlockingQueue<JsonObject> queue = new LinkedBlockingQueue<>(); final FetchConsulStateCmd fetchConsulStateCmd = new FetchConsulStateCmd(httpClient, consulUri) { @Override/*from w w w .j a v a 2s . c om*/ protected void doHandle(JsonObject consulState) { final JsonObject item = createItem("ConsulState", consulState); LOG.debug(item.toString()); queue.add(item); } }; final FetchDockerStateCmd fetchDockerStateCmd = new FetchDockerStateCmd(httpClient, dockerUri) { @Override protected void doHandle(JsonArray dockerState) { final JsonObject item = createItem("DockerState", dockerState); LOG.debug(item.toString()); queue.add(item); } }; final ConsulForwarderState forwarderState = new ConsulForwarderState(); final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1); scheduler.scheduleAtFixedRate(fetchConsulStateCmd, 0, fetchConsulStateInterval, TimeUnit.SECONDS); scheduler.scheduleAtFixedRate(fetchDockerStateCmd, 0, fetchDockerStateInterval, TimeUnit.SECONDS); scheduler.scheduleAtFixedRate(new DispatchItemsCmd(queue) { @Override protected void handleDockerState(JsonArray dockerState) { forwarderState.applyDockerState(dockerState); } @Override protected void handleDockerEvents(JsonArray dockerEvents) { // trigger docker state update scheduler.schedule(fetchDockerStateCmd, requestDockerStateDelay, TimeUnit.SECONDS); } @Override protected void handleConsulState(JsonObject consulState) { forwarderState.applyConsulState(consulState); } }, 0, dispatchItemsInterval, TimeUnit.SECONDS); final DockerEventObserver eventObserver = new DockerEventObserver(httpClient, dockerUri) { @Override protected void handle(JsonObject event) { queue.add(createItem("DockerEvent", event)); } }; final Thread eventObserverThread = new Thread(eventObserver, "Docker Event Observer") { @Override public void interrupt() { eventObserver.die(); super.interrupt(); } }; eventObserverThread.start(); }
From source file:com.stehno.sanctuary.core.Sanctuary.java
public static void main(String[] args) throws Exception { log.info("Starting run..."); JdbcTemplate jdbcTemplate = new JdbcTemplate(createDataSource()); // FIXME: AndroidLocalStore LocalStore localStore = new JdbcLocalStore(jdbcTemplate); localStore.init();/*from w ww. jav a2 s . com*/ // FIXME: FileSystemRemoteStore, S3RemoteStore, AndroidS3LocalStore? // FIXME: remote keys RemoteStore remoteStore = new S3RemoteStore("yourkey", "yourotherkey"); remoteStore.init(); DirectoryScanner scanner = new DefaultDirectoryScanner(localStore); ExecutorService executor = new ThreadPoolExecutor(2, 2, 1, TimeUnit.MINUTES, new LinkedBlockingQueue<Runnable>()); FileArchiver archiver = new DefaultFileArchiver(executor, localStore, remoteStore); ChangeSet changeSet = scanner.scanDirectory(WORKING_DIR); // FIXME: allow review of changeset here (confirm/cancel) log.info("Changes: " + changeSet); MessageSet messageSet = archiver.archiveChanges(changeSet); // FIXME: allow review of messages here log.info("Messages" + messageSet); remoteStore.destroy(); localStore.destroy(); }
From source file:com.curecomp.primefaces.migrator.PrimefacesMigration.java
public static void main(String[] args) throws Exception { // Let's use some colors :) // AnsiConsole.systemInstall(); CommandLineParser cliParser = new BasicParser(); CommandLine cli = null;//from ww w .jav a2s . c o m try { cli = cliParser.parse(OPTIONS, args); } catch (ParseException e) { printHelp(); } if (!cli.hasOption("s")) { printHelp(); } String sourcePattern; if (cli.hasOption("p")) { sourcePattern = cli.getOptionValue("p"); } else { sourcePattern = DEFAULT_SOURCE_PATTERN; } String defaultAnswer; if (cli.hasOption("default-answer")) { defaultAnswer = cli.getOptionValue("default-answer"); } else { defaultAnswer = DEFAULT_DEFAULT_PROMPT_ANSWER; } boolean defaultAnswerYes = defaultAnswer.equalsIgnoreCase("y"); boolean quiet = cli.hasOption("q"); boolean testWrite = cli.hasOption("t"); Path sourceDirectory = Paths.get(cli.getOptionValue("s")).toAbsolutePath(); // Since we use IO we will have some blocking threads hanging around int threadCount = Runtime.getRuntime().availableProcessors() * 2; ThreadPoolExecutor threadPool = new ThreadPoolExecutor(threadCount, threadCount, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>()); BlockingQueue<WidgetVarLocation> foundUsages = new LinkedBlockingQueue<>(); BlockingQueue<WidgetVarLocation> unusedOrAmbiguous = new LinkedBlockingQueue<>(); BlockingQueue<WidgetVarLocation> skippedUsages = new LinkedBlockingQueue<>(); List<Future<?>> futures = new ArrayList<>(); findWidgetVars(sourceDirectory, sourcePattern, threadPool).forEach(widgetVarLocation -> { // We can't really find usages of widget vars that use EL expressions :( if (widgetVarLocation.widgetVar.contains("#")) { unusedOrAmbiguous.add(widgetVarLocation); return; } try { FileActionVisitor visitor = new FileActionVisitor(sourceDirectory, sourcePattern, sourceFile -> futures.add(threadPool.submit((Callable<?>) () -> { findWidgetVarUsages(sourceFile, widgetVarLocation, foundUsages, skippedUsages, unusedOrAmbiguous); return null; }))); Files.walkFileTree(sourceDirectory, visitor); } catch (IOException ex) { throw new RuntimeException(ex); } }); awaitAll(futures); new TreeSet<>(skippedUsages).forEach(widgetUsage -> { int startIndex = widgetUsage.columnNr; int endIndex = startIndex + widgetUsage.widgetVar.length(); String relativePath = widgetUsage.location.toAbsolutePath().toString() .substring(sourceDirectory.toString().length()); String previous = replace(widgetUsage.line, startIndex, endIndex, Ansi.ansi().bold().fg(Ansi.Color.RED).a(widgetUsage.widgetVar).reset().toString()); System.out.println("Skipped " + relativePath + " at line " + widgetUsage.lineNr + " and col " + widgetUsage.columnNr + " for widgetVar '" + widgetUsage.widgetVar + "'"); System.out.println("\t" + previous); }); Map<WidgetVarLocation, List<WidgetVarLocation>> written = new HashMap<>(); new TreeSet<>(foundUsages).forEach(widgetUsage -> { WidgetVarLocation key = new WidgetVarLocation(null, widgetUsage.location, widgetUsage.lineNr, -1, null); List<WidgetVarLocation> writtenList = written.get(key); int existing = writtenList == null ? 0 : writtenList.size(); int startIndex = widgetUsage.columnNr; int endIndex = startIndex + widgetUsage.widgetVar.length(); String relativePath = widgetUsage.location.toAbsolutePath().toString() .substring(sourceDirectory.toString().length()); String next = replace(widgetUsage.line, startIndex, endIndex, Ansi.ansi().bold().fg(Ansi.Color.RED) .a("PF('" + widgetUsage.widgetVar + "')").reset().toString()); System.out .println(relativePath + " at line " + widgetUsage.lineNr + " and col " + widgetUsage.columnNr); System.out.println("\t" + next); System.out.print("Replace (Y/N)? [" + (defaultAnswerYes ? "Y" : "N") + "]: "); String input; if (quiet) { input = ""; System.out.println(); } else { try { do { input = in.readLine(); } while (input != null && !input.isEmpty() && !"y".equalsIgnoreCase(input) && !"n".equalsIgnoreCase(input)); } catch (IOException ex) { throw new RuntimeException(ex); } } if (input == null) { System.out.println("Aborted!"); } else if (input.isEmpty() && defaultAnswerYes || !input.isEmpty() && !"n".equalsIgnoreCase(input)) { System.out.println("Replaced!"); System.out.print("\t"); if (writtenList == null) { writtenList = new ArrayList<>(); written.put(key, writtenList); } writtenList.add(widgetUsage); List<String> lines; try { lines = Files.readAllLines(widgetUsage.location); } catch (IOException ex) { throw new RuntimeException(ex); } try (OutputStream os = testWrite ? new ByteArrayOutputStream() : Files.newOutputStream(widgetUsage.location); PrintWriter pw = new PrintWriter(new OutputStreamWriter(os, StandardCharsets.UTF_8))) { String line; for (int i = 0; i < lines.size(); i++) { int lineNr = i + 1; line = lines.get(i); if (lineNr == widgetUsage.lineNr) { int begin = widgetUsage.columnNr + (testWrite ? 0 : existing * 6); int end = begin + widgetUsage.widgetVar.length(); String newLine = replace(line, begin, end, "PF('" + widgetUsage.widgetVar + "')", false); if (testWrite) { System.out.println(newLine); } else { pw.println(newLine); } } else { if (!testWrite) { pw.println(line); } } } } catch (IOException ex) { throw new RuntimeException(ex); } } else { System.out.println("Skipped!"); } }); new TreeSet<>(unusedOrAmbiguous).forEach(widgetUsage -> { int startIndex = widgetUsage.columnNr; int endIndex = startIndex + widgetUsage.widgetVar.length(); String relativePath = widgetUsage.location.toAbsolutePath().toString() .substring(sourceDirectory.toString().length()); String previous = replace(widgetUsage.line, startIndex, endIndex, Ansi.ansi().bold().fg(Ansi.Color.RED).a(widgetUsage.widgetVar).reset().toString()); System.out.println("Skipped unused or ambiguous " + relativePath + " at line " + widgetUsage.lineNr + " and col " + widgetUsage.columnNr); System.out.println("\t" + previous); }); threadPool.shutdown(); }