Example usage for java.util.concurrent SynchronousQueue SynchronousQueue

List of usage examples for java.util.concurrent SynchronousQueue SynchronousQueue

Introduction

In this page you can find the example usage for java.util.concurrent SynchronousQueue SynchronousQueue.

Prototype

public SynchronousQueue() 

Source Link

Document

Creates a SynchronousQueue with nonfair access policy.

Usage

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/*from   w ww .j  a  v  a2s. co  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:org.bml.util.elasticconsumer.example.ElasticConsumerTest.java

public static void main(String args[]) throws Exception {
    boolean fair = true, debug = true, result = false;

    //We need the queue to create the thread factory and the ElasticConsumer after that you can disgard the refrence.
    BlockingQueue<ProcData> queueIn = new SynchronousQueue<ProcData>();

    //This is the factory that creates worker threads for the ElasticConsumer
    PoolableObjectFactory factory = new TestWorkerThreadObjectFactory(queueIn, 2, TimeUnit.SECONDS, 100);

    //The ElasticConsumer component.
    ElasticConsumer<ProcData, TestWorkerThread> app = new ElasticConsumer<ProcData, TestWorkerThread>(factory,
            queueIn, 1, false);//from   ww  w .  j  av a  2s. c  o  m

    app.setDebug(debug);
    app.start();

    System.out.println("ElasticConsumer: ALIVE=" + app.isAlive());

    int processors = Runtime.getRuntime().availableProcessors();
    System.out.println("System is reporting " + processors + " processor cores.");

    List<LoadProducer> LoadProducerList = new ArrayList<LoadProducer>(processors);
    LoadProducer load;
    for (int c = 0; c < processors; c++) {
        load = new LoadProducer(app);
        load.start();
        LoadProducerList.add(load);
    }

    Thread.sleep(10000);

    app.setShouldRun(false);
    System.out.println("ElasticConsumer: ALIVE=" + app.isAlive());

}

From source file:ProducerConsumerExample.java

public static void main(String[] args) {
    BlockingQueue<String> drop = new SynchronousQueue<String>();
    (new Thread(new Producer(drop))).start();
    (new Thread(new Consumer(drop))).start();
}

From source file:Main.java

public static ThreadPoolExecutor newFixedThreadPool(int corePoolSize) {
    return new ThreadPoolExecutor(corePoolSize, corePoolSize, 0, TimeUnit.MILLISECONDS,
            new SynchronousQueue<Runnable>());
}

From source file:Main.java

public static ExecutorService newFixedThreadPool(int threadSize) {
    if (threadSize <= 0) {
        throw new IllegalArgumentException("ThreadSize must be greater than 0!");
    }// w  w  w . j a  v  a  2s  . c  om
    if (threadSize == 1) {
        return MoreExecutors.sameThreadExecutor();

    }
    return new ThreadPoolExecutor(threadSize - 1, threadSize - 1, 0L, TimeUnit.MILLISECONDS,
            new SynchronousQueue<Runnable>(), new ThreadPoolExecutor.CallerRunsPolicy());
}

From source file:Main.java

public static <E> SynchronousQueue<E> newSynchronousQueue() {
    return new SynchronousQueue<E>();
}

From source file:Main.java

/**
 * Create a cached thread pool whose max number of threads is `maxThreadNumber`. Thread names
 * are formatted as prefix-ID, where ID is a unique, sequentially assigned integer.
 */// w  w w.  j a  v  a2  s  . c o  m
public static ThreadPoolExecutor newDaemonCachedThreadPool(String prefix, int maxThreadNumber)

{
    ThreadFactory threadFactory = namedThreadFactory(prefix);
    return new ThreadPoolExecutor(0, maxThreadNumber, 60L, TimeUnit.SECONDS, new SynchronousQueue<Runnable>(),
            threadFactory);
}

From source file:Main.java

public void runTest() throws Exception {
    ThreadPoolExecutor tp = new ThreadPoolExecutor(1, 1, 60L, TimeUnit.SECONDS,
            new SynchronousQueue<Runnable>());
    tp.setRejectedExecutionHandler(//from  w w  w  . java 2 s .co  m
            (Runnable r, ThreadPoolExecutor executor) -> System.out.println("Task rejected: " + r));
    Semaphore oneTaskDone = new Semaphore(0);
    tp.execute(() -> {
        System.out.println("Sleeping");
        try {
            Thread.sleep(300);
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("Done sleeping");
        oneTaskDone.release();
    });
    tp.execute(new Runnable() {
        @Override
        public void run() {
            System.out.println("Never happends");
        }

        @Override
        public String toString() {
            return "Rejected Runnable";
        }
    });
    oneTaskDone.acquire();
    tp.execute(() -> System.out.println("Running"));
    tp.shutdown();
    tp.awaitTermination(100, TimeUnit.MILLISECONDS);
    System.out.println("Finished");
}

From source file:org.polymap.core.runtime.UnboundPoolExecutor.java

public static ExecutorService newInstance() {
    final int procs = Runtime.getRuntime().availableProcessors();
    final int maxThreads = procs * MAX_THREADS_PER_PROC;

    // thread factory
    ThreadFactory threadFactory = new ThreadFactory() {
        volatile int threadNumber = 0;

        public Thread newThread(Runnable r) {
            String prefix = "polymap-";
            Thread t = new Thread(r, prefix + threadNumber++);
            t.setDaemon(false);//from   www  .j a  va  2 s . co  m
            t.setPriority(DEFAULT_THREAD_PRIORITY);
            return t;
        }
    };

    // thread pool
    ThreadPoolExecutor executor = new ThreadPoolExecutor(procs, maxThreads, 180L, TimeUnit.SECONDS,
            new SynchronousQueue<Runnable>(), threadFactory);

    // rejected? -> wait and try again
    executor.setRejectedExecutionHandler(new RejectedExecutionHandler() {
        Random rand = new Random();

        public void rejectedExecution(Runnable r, ThreadPoolExecutor _executor) {
            do {
                try {
                    Thread.sleep(rand.nextInt(1000) + 100);
                } catch (InterruptedException e) {
                }
            } while (_executor.getActiveCount() >= maxThreads);

            _executor.execute(r);
        }
    });

    //executor.allowCoreThreadTimeOut( true );        
    return executor;
}

From source file:org.mule.config.pool.DefaultThreadPoolFactory.java

public ThreadPoolExecutor createPool(String name, ThreadingProfile tp) {
    BlockingQueue buffer;//from  w ww  .jav a2 s . c  o m

    if (tp.getMaxBufferSize() > 0 && tp.getMaxThreadsActive() > 1) {
        buffer = new LinkedBlockingDeque(tp.getMaxBufferSize());
    } else {
        buffer = new SynchronousQueue();
    }

    ThreadPoolExecutor pool = internalCreatePool(name, tp, buffer);
    configureThreadPoolExecutor(name, tp, pool);
    return pool;

}