List of usage examples for java.util.concurrent BlockingQueue put
void put(E e) throws InterruptedException;
From source file:DelayedJob.java
public static void main(String[] args) throws InterruptedException { BlockingQueue<DelayedJob> queue = new DelayQueue<>(); Instant now = Instant.now(); queue.put(new DelayedJob("A", now.plusSeconds(9))); queue.put(new DelayedJob("B", now.plusSeconds(3))); queue.put(new DelayedJob("C", now.plusSeconds(6))); queue.put(new DelayedJob("D", now.plusSeconds(1))); while (queue.size() > 0) { System.out.println("started..."); DelayedJob job = queue.take();/*from w w w .ja va2 s . com*/ System.out.println("Job: " + job); } System.out.println("Finished."); }
From source file:Main.java
public static void main(String[] argv) throws Exception { int capacity = 10; BlockingQueue<Integer> queue = new ArrayBlockingQueue<Integer>(capacity); int numWorkers = 2; Worker[] workers = new Worker[numWorkers]; for (int i = 0; i < workers.length; i++) { workers[i] = new Worker(queue); workers[i].start();/*from w w w. j a v a2s . c om*/ } for (int i = 0; i < 100; i++) { queue.put(i); } }
From source file:com.blacklocus.qs.worker.RandomStdoutTasksExample.java
public static void main(String[] args) { // Mock our source of tasks. final BlockingQueue<QSTaskModel> workQueue = new SynchronousQueue<QSTaskModel>(); // Generates tasks new Thread(new ExceptingRunnable() { @Override// ww w .j a v a 2 s.c o m protected void go() throws Exception { while (true) { workQueue.put(new QSTaskModel(null, "" + RandomUtils.nextInt(), "stdout", 1, new Params(RandomStringUtils.randomAscii(RandomUtils.nextInt(32))))); } } }).start(); // All this worker does is log an extra message describing the length of the "message" param. QSWorker<Params> worker = new AbstractQSWorker<Params>() { @Override public String getHandlerName() { // This identifies the type of task this worker can handle. In our task generator above, the // tasks are created with the same handler identifier "stdout". return "stdout"; } @Override public TaskKit<Params> convert(TaskKitFactory<Params> factory) throws Exception { return factory.newTaskKit(Params.class); } @Override public Object process(TaskKit<Params> kit) throws Exception { String msg = kit.params().message; kit.log(msg + " is " + msg.length() + " characters long"); return null; } }; QSAssembly.newBuilder() // The source of work. .taskServices(new BlockingQueueQSTaskService(workQueue)) // Logging service which records task start, task-specific logging, task end. .logService(new SystemOutQSLogService()) // Service that helps identify the machine completing tasks, this machine. .workerIdService(new HostNameQSWorkerIdService()) // The worker logic observed by this instance. .workers(worker) // Run it in the current thread. .build().run(); }
From source file:Main.java
public static <E> void surePut(BlockingQueue<E> q, E el) { while (true) { try {//from w w w. j a v a2s .c o m q.put(el); break; } catch (InterruptedException e) { } } }
From source file:org.wso2.carbon.cloud.gateway.transport.server.CGThriftServerHandler.java
/** * Add a message into the server's request buffer, wait if the buffer is full. * * @param msg the new Thrift message/*from www . j av a 2 s. com*/ * @param token the token to look up the real buffer * @throws AxisFault in case of an error - for e.g. out of space in the queue */ public static void addRequestMessage(Message msg, String token) throws AxisFault { try { BlockingQueue<Message> buffer = requestBuffers.get(token); if (buffer == null) { throw new AxisFault("The requested buffer is not found"); } buffer.put(msg); } catch (Exception e) { throw new AxisFault(e.getMessage(), e); } }
From source file:net.yacy.cora.storage.Files.java
public static BlockingQueue<String> concurentLineReader(final File f) throws IOException { final BlockingQueue<String> q = new LinkedBlockingQueue<String>(); final InputStream is = read(f); final BufferedReader br = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8)); Thread t = new Thread() { @Override// ww w . j a v a 2s .c o m public void run() { Thread.currentThread().setName("Files.concurrentLineReader:" + f); String line; try { while ((line = br.readLine()) != null) { q.put(line); } } catch (final IOException e) { } catch (final InterruptedException e) { } finally { try { q.put(POISON_LINE); try { br.close(); is.close(); } catch (final IOException ee) { } } catch (final InterruptedException e) { // last try q.add(POISON_LINE); try { br.close(); is.close(); } catch (final IOException ee) { } } } } }; t.start(); return q; }
From source file:enmasse.queue.scheduler.Artemis.java
public static Future<Broker> create(Vertx vertx, ProtonConnection connection) { CompletableFuture<Broker> promise = new CompletableFuture<>(); connection.sessionOpenHandler(ProtonSession::open); BlockingQueue<Message> replies = new LinkedBlockingDeque<>(); ProtonSender sender = connection.createSender("activemq.management"); sender.openHandler(result -> {/*from w w w . ja v a 2 s . c o m*/ ProtonReceiver receiver = connection.createReceiver("activemq.management"); Source source = new Source(); source.setDynamic(true); receiver.setSource(source); receiver.openHandler(h -> { promise.complete(new Artemis(vertx, sender, h.result().getRemoteSource().getAddress(), replies)); }); receiver.handler(((protonDelivery, message) -> { try { replies.put(message); ProtonHelper.accepted(protonDelivery, true); } catch (Exception e) { ProtonHelper.rejected(protonDelivery, true); } })); receiver.open(); }); sender.open(); return promise; }
From source file:org.opensilk.music.playback.control.PlaybackController.java
public static PlaybackServiceConnection bindService(Context context) throws InterruptedException { if (context == null) { throw new NullPointerException("context == null"); }/*from www . jav a 2s .c o m*/ ensureNotOnMainThread(context); final BlockingQueue<IPlaybackService> q = new LinkedBlockingQueue<IPlaybackService>(1); ServiceConnection keyChainServiceConnection = new ServiceConnection() { volatile boolean mConnectedAtLeastOnce = false; @Override public void onServiceConnected(ComponentName name, IBinder service) { if (!mConnectedAtLeastOnce) { mConnectedAtLeastOnce = true; try { q.put(IPlaybackService.Stub.asInterface(service)); } catch (InterruptedException e) { // will never happen, since the queue starts with one available slot } } } @Override public void onServiceDisconnected(ComponentName name) { } }; Intent intent = new Intent(context, PlaybackService.class); boolean isBound = context.bindService(intent, keyChainServiceConnection, Context.BIND_AUTO_CREATE); if (!isBound) { throw new AssertionError("could not bind to KeyChainService"); } return new PlaybackServiceConnection(context, keyChainServiceConnection, q.take()); }
From source file:org.mitre.mpf.mst.TestSystemStress3.java
/** * This test intentionally runs one file per job *///from ww w . j a v a 2 s. c om @Test(timeout = 180 * MINUTES) public void runFaceOcvDetectImageManyJobs() throws Exception { testCtr++; log.info("Beginning test #{} runFaceOcvDetectImageManyJobs()", testCtr); IOFileFilter fileFilter = FileFilterUtils.and(FileFilterUtils.fileFileFilter(), FileFilterUtils.suffixFileFilter(".jpg")); int numExtractors = 6; // number of extractors on Jenkins (* number of nodes, now 1) // int numExtractors = 2; // number of extractors on local VM * 1 node // for testing on local VM only // Collection<File> files = FileUtils.listFiles(new File(getClass().getClassLoader().getResource("samples/face").getFile()), // fileFilter, null); // for testing on Jenkins // 10,000 jpgs Collection<File> files = FileUtils.listFiles(new File("/mpfdata/datasets/mugshots_10000"), fileFilter, null); BlockingQueue<File> fQueue = new ArrayBlockingQueue<File>(files.size()); for (File file : files) { fQueue.put(file); } ExecutorService executor = Executors.newFixedThreadPool(numExtractors); JobRunner[] jobRunners = new JobRunner[numExtractors]; for (int i = 0; i < numExtractors; i++) { jobRunners[i] = new JobRunner(fQueue); executor.submit(jobRunners[i]); } executor.shutdown(); executor.awaitTermination(Long.MAX_VALUE, TimeUnit.MILLISECONDS); Assert.assertEquals( "Number of files to process={} doesn't match actual number of jobs run={} (one job/file)", files.size(), manyJobsNumFilesProcessed); log.info("Successfully ran {} jobs for {} files, one file per job, without a hiccup", manyJobsNumFilesProcessed, files.size()); log.info("Finished test runFaceOcvDetectImageManyJobs()"); }
From source file:com.mirth.connect.server.controllers.DefaultEventController.java
@Override public void dispatchEvent(Event event) { try {// w w w .jav a 2 s. c o m Map<Object, BlockingQueue<Event>> queues = null; /* * Using instanceof is several thousand times faster than using a map to store the * different queue sets. */ if (event instanceof MessageEvent) { queues = messageEventQueues; } else if (event instanceof ErrorEvent) { queues = errorEventQueues; } else if (event instanceof DeployedStateEvent) { queues = deployedStateEventQueues; } else if (event instanceof ConnectionStatusEvent) { queues = connectionStatusEventQueues; } else if (event instanceof ServerEvent) { queues = serverEventQueues; } else { queues = genericEventQueues; } for (BlockingQueue<Event> queue : queues.values()) { queue.put(event); } } catch (InterruptedException e) { Thread.currentThread().interrupt(); } }