Example usage for java.util.concurrent ConcurrentLinkedQueue ConcurrentLinkedQueue

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

Introduction

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

Prototype

public ConcurrentLinkedQueue() 

Source Link

Document

Creates a ConcurrentLinkedQueue that is initially empty.

Usage

From source file:nz.co.fortytwo.signalk.server.SubscriptionManager.java

public ConcurrentLinkedQueue<Subscription> getSubscriptions(String wsSession) {
    ConcurrentLinkedQueue<Subscription> subs = new ConcurrentLinkedQueue<Subscription>();
    for (Subscription s : subscriptions) {
        if (s.getWsSession().equals(wsSession)) {
            subs.add(s);//from   w  w  w .j  a va2  s .c  om
        }
    }
    return subs;
}

From source file:com.googlecode.concurrentlinkedhashmap.MultiThreadedTest.java

@Test(dataProvider = "builder")
public void weightedConcurrency(Builder<Integer, List<Integer>> builder) {
    final ConcurrentLinkedHashMap<Integer, List<Integer>> map = builder.weigher(Weighers.<Integer>list())
            .maximumWeightedCapacity(threads).concurrencyLevel(threads).build();
    final Queue<List<Integer>> values = new ConcurrentLinkedQueue<List<Integer>>();
    for (int i = 1; i <= threads; i++) {
        Integer[] array = new Integer[i];
        Arrays.fill(array, Integer.MIN_VALUE);
        values.add(Arrays.asList(array));
    }/* ww  w.j a va 2 s  .c  o m*/
    executeWithTimeOut(map, new Callable<Long>() {
        @Override
        public Long call() throws Exception {
            return timeTasks(threads, new Runnable() {
                @Override
                public void run() {
                    List<Integer> value = values.poll();
                    for (int i = 0; i < iterations; i++) {
                        map.put(i % 10, value);
                    }
                }
            });
        }
    });
}

From source file:org.atmosphere.cpr.PoolableBroadcasterFactoryTest.java

@Test
public void concurrentLookupTest() throws InterruptedException {
    String id = "id";
    final CountDownLatch latch = new CountDownLatch(100);
    final AtomicInteger created = new AtomicInteger();

    factory.addBroadcasterListener(new BroadcasterListenerAdapter() {
        @Override/*www  .j  a  va  2  s  . c  o m*/
        public void onPostCreate(Broadcaster b) {
            created.incrementAndGet();
        }

        @Override
        public void onComplete(Broadcaster b) {

        }

        @Override
        public void onPreDestroy(Broadcaster b) {

        }
    });

    final ConcurrentLinkedQueue<Broadcaster> c = new ConcurrentLinkedQueue<Broadcaster>();
    ExecutorService r = Executors.newCachedThreadPool();
    for (int i = 0; i < 100; i++) {
        r.submit(new Runnable() {
            @Override
            public void run() {
                c.add(factory.lookup("name" + UUID.randomUUID().toString(), true));
                latch.countDown();
            }
        });
    }

    try {
        assertTrue(latch.await(20, TimeUnit.SECONDS));
        assertEquals(created.get(), 100);
        assertEquals(c.size(), 100);

        for (Broadcaster b : c) {
            b.destroy();
        }

        assertNotNull(factory.lookup("name" + UUID.randomUUID().toString(), true).broadcast("test"));

        assertEquals(factory.poolableProvider().poolSize(), 100);

    } finally {
        factory.destroy();
        r.shutdownNow();
    }

}

From source file:com.ibm.crail.tools.CrailBenchmark.java

void write(String filename, int size, int loop, int storageClass, int locationClass, boolean buffered)
        throws Exception {
    System.out.println("write, filename " + filename + ", size " + size + ", loop " + loop + ", storageClass "
            + storageClass + ", locationClass " + locationClass + ", buffered " + buffered);

    CrailBuffer buf = null;/*from  w  w w .  j a v a 2  s.c o m*/
    if (size == CrailConstants.BUFFER_SIZE) {
        buf = fs.allocateBuffer();
    } else if (size < CrailConstants.BUFFER_SIZE) {
        CrailBuffer _buf = fs.allocateBuffer();
        _buf.clear().limit(size);
        buf = _buf.slice();
    } else {
        buf = OffHeapBuffer.wrap(ByteBuffer.allocateDirect(size));
    }

    //warmup
    ConcurrentLinkedQueue<CrailBuffer> bufferQueue = new ConcurrentLinkedQueue<CrailBuffer>();
    bufferQueue.add(buf);
    warmUp(filename, warmup, bufferQueue);

    //benchmark
    System.out.println("starting benchmark...");
    fs.getStatistics().reset();
    long _loop = (long) loop;
    long _bufsize = (long) CrailConstants.BUFFER_SIZE;
    long _capacity = _loop * _bufsize;
    double sumbytes = 0;
    double ops = 0;
    CrailFile file = fs.create(filename, CrailNodeType.DATAFILE, CrailStorageClass.get(storageClass),
            CrailLocationClass.get(locationClass)).get().asFile();
    CrailBufferedOutputStream bufferedStream = buffered ? file.getBufferedOutputStream(_capacity) : null;
    CrailOutputStream directStream = !buffered ? file.getDirectOutputStream(_capacity) : null;
    long start = System.currentTimeMillis();
    while (ops < loop) {
        buf.clear();
        if (buffered) {
            bufferedStream.write(buf.getByteBuffer());
        } else {
            directStream.write(buf).get();
        }
        sumbytes = sumbytes + buf.capacity();
        ops = ops + 1.0;
    }
    if (buffered) {
        bufferedStream.close();
    }
    long end = System.currentTimeMillis();
    double executionTime = ((double) (end - start)) / 1000.0;
    double throughput = 0.0;
    double latency = 0.0;
    double sumbits = sumbytes * 8.0;
    if (executionTime > 0) {
        throughput = sumbits / executionTime / 1000.0 / 1000.0;
        latency = 1000000.0 * executionTime / ops;
    }

    System.out.println("execution time " + executionTime);
    System.out.println("ops " + ops);
    System.out.println("sumbytes " + sumbytes);
    System.out.println("throughput " + throughput);
    System.out.println("latency " + latency);

    fs.getStatistics().print("close");
}

From source file:com.laurencedawson.image_management.ImageManager.java

/**
 * Initialize a newly created ImageManager
 * @param context The application ofinal r activity context
 * @param cacheSize The size of the LRU cache
 * @param threads The number of threads for the pools to use
 */// ww  w. j  av  a 2  s  .  c  o  m
public ImageManager(final Context context, final int cacheSize, final int threads) {

    // Instantiate the three queues. The task queue uses a custom comparator to 
    // change the ordering from FIFO (using the internal comparator) to respect
    // request priorities. If two requests have equal priorities, they are 
    // sorted according to creation date
    mTaskQueue = new PriorityBlockingQueue<Runnable>(QUEUE_SIZE, new ImageThreadComparator());
    mActiveTasks = new ConcurrentLinkedQueue<Runnable>();
    mBlockedTasks = new ConcurrentLinkedQueue<Runnable>();

    // The application context
    mContext = context;

    // Create a new threadpool using the taskQueue
    mThreadPool = new ThreadPoolExecutor(threads, threads, Long.MAX_VALUE, TimeUnit.SECONDS, mTaskQueue) {

        @Override
        protected void beforeExecute(final Thread thread, final Runnable run) {
            // Before executing a request, place the request on the active queue
            // This prevents new duplicate requests being placed in the active queue
            mActiveTasks.add(run);
            super.beforeExecute(thread, run);
        }

        @Override
        protected void afterExecute(final Runnable r, final Throwable t) {
            // After a request has finished executing, remove the request from
            // the active queue, this allows new duplicate requests to be submitted
            mActiveTasks.remove(r);

            // Perform a quick check to see if there are any remaining requests in
            // the blocked queue. Peek the head and check for duplicates in the 
            // active and task queues. If no duplicates exist, add the request to
            // the task queue. Repeat this until a duplicate is found
            synchronized (mBlockedTasks) {
                while (mBlockedTasks.peek() != null && !mTaskQueue.contains(mBlockedTasks.peek())
                        && !mActiveTasks.contains(mBlockedTasks.peek())) {
                    Runnable runnable = mBlockedTasks.poll();
                    if (runnable != null) {
                        mThreadPool.execute(runnable);
                    }
                }
            }
            super.afterExecute(r, t);
        }
    };

    // Calculate the cache size
    final int actualCacheSize = ((int) (Runtime.getRuntime().maxMemory() / 1024)) / cacheSize;

    // Create the LRU cache
    // http://developer.android.com/reference/android/util/LruCache.html

    // The items are no longer recycled as they leave the cache, turns out this wasn't the right
    // way to go about this and often resulted in recycled bitmaps being drawn
    // http://stackoverflow.com/questions/10743381/when-should-i-recycle-a-bitmap-using-lrucache
    mBitmapCache = new LruCache<String, Bitmap>(actualCacheSize) {
        protected int sizeOf(final String key, final Bitmap value) {
            return value.getByteCount() / 1024;
        }
    };
}

From source file:org.hyperic.hq.measurement.server.session.AvailabilityFallbackCheckQue.java

/**
 * Default CTor/*from   w  ww .  jav a  2 s  .c  o  m*/
 */
public AvailabilityFallbackCheckQue() {
    this.platformsRecheckQue = new ConcurrentLinkedQueue<ResourceDataPoint>();
    this.currentPlatformsInQue = new HashMap<Integer, ResourceDataPoint>();
    this.platformsRecheckInProgress = new HashSet<Integer>();
    this.platformsPendingQueRemoval = new HashSet<Integer>();
    this.measurementIdToPlatformId = new HashMap<Integer, Integer>();
}

From source file:org.apache.streams.filebuffer.FileBufferPersistReader.java

@Override
public void prepare(Object configurationObject) {

    try {/*from  w  w w  . j  a va 2  s . c  o m*/
        Thread.sleep(1000);
    } catch (InterruptedException ie) {
        //Handle exception
    }

    mapper = new ObjectMapper();

    File file = new File(config.getPath());

    if (!file.exists()) {
        try {
            file.createNewFile();
        } catch (IOException e) {
            LOGGER.error(e.getMessage());
        }
    }

    Preconditions.checkArgument(file.exists());
    Preconditions.checkArgument(file.canRead());

    try {
        queueFile = new QueueFile(file);
    } catch (IOException e) {
        LOGGER.error(e.getMessage());
    }

    Preconditions.checkNotNull(queueFile);

    this.persistQueue = new ConcurrentLinkedQueue<>();

}

From source file:org.languagetool.server.PipelinePool.java

PipelinePool(HTTPServerConfig config, ResultCache cache, boolean internalServer) {
    this.internalServer = internalServer;
    this.config = config;
    this.cache = cache;
    this.pipelineExpireCheckTimestamp = System.currentTimeMillis();
    int maxPoolSize = config.getMaxPipelinePoolSize();
    int expireTime = config.getPipelineExpireTime();
    if (config.isPipelineCachingEnabled()) {
        this.pool = CacheBuilder.newBuilder().maximumSize(maxPoolSize)
                .expireAfterAccess(expireTime, TimeUnit.SECONDS)
                .build(new CacheLoader<PipelineSettings, ConcurrentLinkedQueue<Pipeline>>() {
                    @Override//from w  ww .ja  v a 2  s.  c  o  m
                    public ConcurrentLinkedQueue<Pipeline> load(PipelineSettings key) {
                        return new ConcurrentLinkedQueue<>();
                    }
                });
    } else {
        this.pool = null;
    }
}

From source file:com.netflix.discovery.shared.Applications.java

/**
 * Note that appsHashCode and versionDelta key names are formatted in a custom/configurable way.
 *///from ww w. j ava 2s.c om
@JsonCreator
public Applications(@JsonProperty("appsHashCode") String appsHashCode,
        @JsonProperty("versionDelta") Long versionDelta,
        @JsonProperty("application") List<Application> registeredApplications) {
    this.applications = new ConcurrentLinkedQueue<Application>();
    for (Application app : registeredApplications) {
        this.addApplication(app);
    }
    this.appsHashCode = appsHashCode;
    this.versionDelta = versionDelta;
}