List of usage examples for java.util.concurrent LinkedBlockingQueue LinkedBlockingQueue
public LinkedBlockingQueue()
From source file:com.android.im.imps.HttpDataChannel.java
@Override public void connect() throws ImException { if (mConnected) { throw new ImException("Already connected"); }/*from w w w . ja v a 2s .com*/ mStopped = false; mStopRetry = false; mSendQueue = new LinkedBlockingQueue<Primitive>(); mReceiveQueue = new LinkedBlockingQueue<Primitive>(); mSendThread = new Thread(this, "HttpDataChannel"); mSendThread.setDaemon(true); mSendThread.start(); mConnected = true; }
From source file:com.netflix.curator.framework.imps.TestFramework.java
@Test public void testNamespaceInBackground() throws Exception { CuratorFrameworkFactory.Builder builder = CuratorFrameworkFactory.builder(); CuratorFramework client = builder.connectString(server.getConnectString()).namespace("aisa") .retryPolicy(new RetryOneTime(1)).build(); client.start();/*from ww w. ja v a 2s . com*/ try { final BlockingQueue<String> queue = new LinkedBlockingQueue<String>(); CuratorListener listener = new CuratorListener() { @Override public void eventReceived(CuratorFramework client, CuratorEvent event) throws Exception { if (event.getType() == CuratorEventType.EXISTS) { queue.put(event.getPath()); } } }; client.getCuratorListenable().addListener(listener); client.create().forPath("/base"); client.checkExists().inBackground().forPath("/base"); String path = queue.poll(10, TimeUnit.SECONDS); Assert.assertEquals(path, "/base"); client.getCuratorListenable().removeListener(listener); BackgroundCallback callback = new BackgroundCallback() { @Override public void processResult(CuratorFramework client, CuratorEvent event) throws Exception { queue.put(event.getPath()); } }; client.getChildren().inBackground(callback).forPath("/base"); path = queue.poll(10, TimeUnit.SECONDS); Assert.assertEquals(path, "/base"); } finally { client.close(); } }
From source file:org.mobicents.servlet.sip.restcomm.fax.InterFaxService.java
@Override public void start() throws RuntimeException { user = configuration.getString("user"); password = configuration.getString("password"); maxFileSize = configuration.getLong("maximum-file-size"); final int timeout = configuration.getInt("timeout"); // try { // interfax = (InterFaxSoapStub)new InterFaxLocator().getInterFaxSoap(); // interfax.setTimeout((int)(timeout * TimeUtils.SECOND_IN_MILLIS)); // } catch(final ServiceException exception) { // throw new RuntimeException(exception); // }//from ww w . j a va2 s.c om queue = new LinkedBlockingQueue<FaxRequest>(); worker = new Thread(this); worker.setName("InterFax Worker"); running = true; worker.start(); }
From source file:com.softwarementors.extjs.djn.router.processor.standard.json.JsonRequestProcessor.java
private ExecutorService createThreadPool() { assert getGlobalConfiguration() != null; ExecutorService result = new ThreadPoolExecutor( getGlobalConfiguration().getBatchRequestsMinThreadsPoolSize(), getGlobalConfiguration().getBatchRequestsMaxThreadsPoolSize(), getGlobalConfiguration().getBatchRequestsThreadKeepAliveSeconds(), TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>()); return result; }
From source file:com.example.android.threadsample.PhotoManager.java
/** * Constructs the work queues and thread pools used to download and decode images. *//*from ww w. j a v a 2 s. c om*/ private PhotoManager() { /* * Creates a work queue for the pool of Thread objects used for downloading, using a linked * list queue that blocks when the queue is empty. */ mDownloadWorkQueue = new LinkedBlockingQueue<Runnable>(); /* * Creates a work queue for the pool of Thread objects used for decoding, using a linked * list queue that blocks when the queue is empty. */ mDecodeWorkQueue = new LinkedBlockingQueue<Runnable>(); /* * Creates a work queue for the set of of task objects that control downloading and * decoding, using a linked list queue that blocks when the queue is empty. */ mPhotoTaskWorkQueue = new LinkedBlockingQueue<PhotoTask>(); /* * Creates a new pool of Thread objects for the download work queue */ mDownloadThreadPool = new ThreadPoolExecutor(CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE_TIME, KEEP_ALIVE_TIME_UNIT, mDownloadWorkQueue); /* * Creates a new pool of Thread objects for the decoding work queue */ mDecodeThreadPool = new ThreadPoolExecutor(NUMBER_OF_CORES, NUMBER_OF_CORES, KEEP_ALIVE_TIME, KEEP_ALIVE_TIME_UNIT, mDecodeWorkQueue); // Instantiates a new cache based on the cache size estimate mPhotoCache = new LruCache<URL, byte[]>(IMAGE_CACHE_SIZE) { /* * This overrides the default sizeOf() implementation to return the * correct size of each cache entry. */ @Override protected int sizeOf(URL paramURL, byte[] paramArrayOfByte) { return paramArrayOfByte.length; } }; /* * Instantiates a new anonymous Handler object and defines its * handleMessage() method. The Handler *must* run on the UI thread, because it moves photo * Bitmaps from the PhotoTask object to the View object. * To force the Handler to run on the UI thread, it's defined as part of the PhotoManager * constructor. The constructor is invoked when the class is first referenced, and that * happens when the View invokes startDownload. Since the View runs on the UI Thread, so * does the constructor and the Handler. */ mHandler = new Handler(Looper.getMainLooper()) { /* * handleMessage() defines the operations to perform when the * Handler receives a new Message to process. */ @Override public void handleMessage(Message inputMessage) { // Gets the image task from the incoming Message object. PhotoTask photoTask = (PhotoTask) inputMessage.obj; // Sets an PhotoView that's a weak reference to the // input ImageView PhotoView localView = photoTask.getPhotoView(); // If this input view isn't null if (localView != null) { /* * Gets the URL of the *weak reference* to the input * ImageView. The weak reference won't have changed, even if * the input ImageView has. */ URL localURL = localView.getLocation(); /* * Compares the URL of the input ImageView to the URL of the * weak reference. Only updates the bitmap in the ImageView * if this particular Thread is supposed to be serving the * ImageView. */ if (photoTask.getImageURL() == localURL) /* * Chooses the action to take, based on the incoming message */ switch (inputMessage.what) { // If the download has started, sets background color to dark green case DOWNLOAD_STARTED: localView.setStatusResource(R.drawable.imagedownloading); break; /* * If the download is complete, but the decode is waiting, sets the * background color to golden yellow */ case DOWNLOAD_COMPLETE: // Sets background color to golden yellow localView.setStatusResource(R.drawable.decodequeued); break; // If the decode has started, sets background color to orange case DECODE_STARTED: localView.setStatusResource(R.drawable.decodedecoding); break; /* * The decoding is done, so this sets the * ImageView's bitmap to the bitmap in the * incoming message */ case TASK_COMPLETE: localView.setImageBitmap(photoTask.getImage()); recycleTask(photoTask); break; // The download failed, sets the background color to dark red case DOWNLOAD_FAILED: localView.setStatusResource(R.drawable.imagedownloadfailed); // Attempts to re-use the Task object recycleTask(photoTask); break; default: // Otherwise, calls the super method super.handleMessage(inputMessage); } } } }; }
From source file:com.ery.estorm.util.Threads.java
/** * Create a new CachedThreadPool with a bounded number as the maximum thread size in the pool. * //from ww w. j a v a2 s. com * @param maxCachedThread * the maximum thread could be created in the pool * @param timeout * the maximum time to wait * @param unit * the time unit of the timeout argument * @param threadFactory * the factory to use when creating new threads * @return threadPoolExecutor the cachedThreadPool with a bounded number as the maximum thread size in the pool. */ public static ThreadPoolExecutor getBoundedCachedThreadPool(int maxCachedThread, long timeout, TimeUnit unit, ThreadFactory threadFactory) { ThreadPoolExecutor boundedCachedThreadPool = new ThreadPoolExecutor(maxCachedThread, maxCachedThread, timeout, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(), threadFactory); // allow the core pool threads timeout and terminate boundedCachedThreadPool.allowCoreThreadTimeOut(true); return boundedCachedThreadPool; }
From source file:com.example.hotnewsapp.imageutil.PhotoManager.java
/** * Constructs the work queues and thread pools used to download and decode * images./* w ww .ja va 2s . com*/ */ private PhotoManager() { /* * Creates a work queue for the pool of Thread objects used for * downloading, using a linked list queue that blocks when the queue is * empty. */ mDownloadWorkQueue = new LinkedBlockingQueue<Runnable>(); /* * Creates a work queue for the pool of Thread objects used for * decoding, using a linked list queue that blocks when the queue is * empty. */ mDecodeWorkQueue = new LinkedBlockingQueue<Runnable>(); /* * Creates a work queue for the set of of task objects that control * downloading and decoding, using a linked list queue that blocks when * the queue is empty. */ mPhotoTaskWorkQueue = new LinkedBlockingQueue<PhotoTask>(); /* * Creates a new pool of Thread objects for the download work queue */ mDownloadThreadPool = new ThreadPoolExecutor(CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE_TIME, KEEP_ALIVE_TIME_UNIT, mDownloadWorkQueue); /* * Creates a new pool of Thread objects for the decoding work queue */ mDecodeThreadPool = new ThreadPoolExecutor(NUMBER_OF_CORES, NUMBER_OF_CORES, KEEP_ALIVE_TIME, KEEP_ALIVE_TIME_UNIT, mDecodeWorkQueue); // Instantiates a new cache based on the cache size estimate mPhotoCache = new LruCache<URL, byte[]>(IMAGE_CACHE_SIZE) { /* * This overrides the default sizeOf() implementation to return the * correct size of each cache entry. */ @Override protected int sizeOf(URL paramURL, byte[] paramArrayOfByte) { return paramArrayOfByte.length; } }; /* * Instantiates a new anonymous Handler object and defines its * handleMessage() method. The Handler *must* run on the UI thread, * because it moves photo Bitmaps from the PhotoTask object to the View * object. To force the Handler to run on the UI thread, it's defined as * part of the PhotoManager constructor. The constructor is invoked when * the class is first referenced, and that happens when the View invokes * startDownload. Since the View runs on the UI Thread, so does the * constructor and the Handler. */ mHandler = new Handler(Looper.getMainLooper()) { /* * handleMessage() defines the operations to perform when the * Handler receives a new Message to process. */ @Override public void handleMessage(Message inputMessage) { // Gets the image task from the incoming Message object. PhotoTask photoTask = (PhotoTask) inputMessage.obj; // Sets an PhotoView that's a weak reference to the // input ImageView PhotoView localView = photoTask.getPhotoView(); // If this input view isn't null if (localView != null) { /* * Gets the URL of the *weak reference* to the input * ImageView. The weak reference won't have changed, even if * the input ImageView has. */ URL localURL = localView.getLocation(); /* * Compares the URL of the input ImageView to the URL of the * weak reference. Only updates the bitmap in the ImageView * if this particular Thread is supposed to be serving the * ImageView. */ if (photoTask.getImageURL() == localURL) { /* * Chooses the action to take, based on the incoming * message */ switch (inputMessage.what) { // If the download has started, sets background color to // dark green case DOWNLOAD_STARTED: localView.setStatusResource(R.drawable.imagedownloading); break; /* * If the download is complete, but the decode is * waiting, sets the background color to golden yellow */ case DOWNLOAD_COMPLETE: // Sets background color to golden yellow localView.setStatusResource(R.drawable.decodequeued); break; // If the decode has started, sets background color to // orange case DECODE_STARTED: localView.setStatusResource(R.drawable.decodedecoding); break; /* * The decoding is done, so this sets the ImageView's * bitmap to the bitmap in the incoming message */ case TASK_COMPLETE: localView.setImageBitmap(photoTask.getImage()); recycleTask(photoTask); break; // The download failed, sets the background color to // dark red case DOWNLOAD_FAILED: localView.setStatusResource(R.drawable.imagedownloadfailed); // Attempts to re-use the Task object recycleTask(photoTask); break; default: // Otherwise, calls the super method super.handleMessage(inputMessage); } } } } }; }
From source file:edu.berkeley.sparrow.examples.BackendBenchmarkProfiler.java
/** * Run an experiment which launches tasks at {@code arrivalRate} for {@code durationMs} * seconds and waits for all tasks to finish. Return a {@link DescriptiveStatistics} * object which contains stats about the distribution of task finish times. Tasks * are executed in a thread pool which contains at least {@code corePoolSize} threads * and grows up to {@code maxPoolSize} threads (growing whenever a new task arrives * and all existing threads are used). /*w w w .j a v a2 s. c o m*/ * * Setting {@code maxPoolSize} to a very large number enacts time sharing, while * setting it equal to {@code corePoolSize} creates a fixed size task pool. * * The derivative of task finishes is tracked by bucketing tasks at the granularity * {@code bucketSize}. If it is detected that task finishes are increasing in an * unbounded fashion (i.e. infinite queuing is occuring) a {@link RuntimeException} * is thrown. */ public static void runExperiment(double arrivalRate, int corePoolSize, int maxPoolSize, long bucketSize, long durationMs, DescriptiveStatistics runTimes, DescriptiveStatistics waitTimes) { long startTime = System.currentTimeMillis(); long keepAliveTime = 10; Random r = new Random(); BlockingQueue<Runnable> runQueue = new LinkedBlockingQueue<Runnable>(); ExecutorService threadPool = new ThreadPoolExecutor(corePoolSize, maxPoolSize, keepAliveTime, TimeUnit.MILLISECONDS, runQueue); if (maxPoolSize == Integer.MAX_VALUE) { threadPool = Executors.newCachedThreadPool(); } // run times indexed by bucketing interval HashMap<Long, List<Long>> bucketedRunTimes = new HashMap<Long, List<Long>>(); // wait times indexed by bucketing interval HashMap<Long, List<Long>> bucketedWaitTimes = new HashMap<Long, List<Long>>(); /* * This is a little tricky. * * We want to generate inter-arrival delays according to the arrival rate specified. * The simplest option would be to generate an arrival delay and then sleep() for it * before launching each task. This has in issue, however: sleep() might wait * several ms longer than we ask it to. When task arrival rates get really fast, * i.e. one task every 10 ms, sleeping an additional few ms will mean we launch * tasks at a much lower rate than requested. * * Instead, we keep track of task launches in a way that does not depend on how long * sleep() actually takes. We still might have tasks launch slightly after their * scheduled launch time, but we will not systematically "fall behind" due to * compounding time lost during sleep()'s; */ long currTime = startTime; while (true) { long delay = (long) (generateInterarrivalDelay(r, arrivalRate) * 1000); // When should the next task launch, based on when the last task was scheduled // to launch. long nextTime = currTime + delay; // Diff gives how long we should wait for the next scheduled task. The difference // may be negative if our last sleep() lasted too long relative to the inter-arrival // delay based on the last scheduled launch, so we round up to 0 in that case. long diff = Math.max(0, nextTime - System.currentTimeMillis()); currTime = nextTime; if (diff > 0) { try { Thread.sleep(diff); } catch (InterruptedException e) { System.err.println("Unexpected interruption!"); System.exit(1); } } threadPool.submit((new BenchmarkRunnable(bucketedRunTimes, bucketedWaitTimes, bucketSize))); if (System.currentTimeMillis() > startTime + durationMs) { break; } } threadPool.shutdown(); try { threadPool.awaitTermination(Long.MAX_VALUE, TimeUnit.MILLISECONDS); } catch (InterruptedException e1) { System.err.println("Unexpected interruption!"); System.exit(1); } List<Long> times = new ArrayList<Long>(bucketedRunTimes.keySet()); Collections.sort(times); HashMap<Long, DescriptiveStatistics> bucketStats = new HashMap<Long, DescriptiveStatistics>(); // Remove first and last buckets since they will not be completely full to do // discretization. times.remove(0); times.remove(times.size() - 1); for (Long time : times) { DescriptiveStatistics stats = new DescriptiveStatistics(); List<Long> list = bucketedRunTimes.get(time); for (Long l : list) { stats.addValue(l); runTimes.addValue(l); } bucketStats.put(time, stats); List<Long> waitList = bucketedWaitTimes.get(time); for (Long l : waitList) { waitTimes.addValue(l); } } int size = bucketStats.size(); if (size >= 2) { DescriptiveStatistics first = bucketStats.get(times.get(0)); DescriptiveStatistics last = bucketStats.get(times.get(times.size() - 1)); double increase = last.getPercentile(50) / first.getPercentile(50); // A simple heuristic, if the median runtime went up by five from the first to // last complete bucket, we assume we are seeing unbounded growth if (increase > 5.0) { throw new RuntimeException( "Queue not in steady state: " + last.getMean() + " vs " + first.getMean()); } } }
From source file:com.nearinfinity.blur.thrift.AsyncClientPool.java
private synchronized BlockingQueue<TAsyncClient> getQueue(Connection connection) { BlockingQueue<TAsyncClient> blockingQueue = _clientMap.get(connection); if (blockingQueue == null) { blockingQueue = new LinkedBlockingQueue<TAsyncClient>(); _clientMap.put(connection, blockingQueue); }//from ww w.j a v a 2s . c om return blockingQueue; }
From source file:com.comic.lazyupload.image.PhotoManager.java
/** * Constructs the work queues and thread pools used to download and decode * images./*ww w. ja va 2 s .c o m*/ */ private PhotoManager() { /* * Creates a work queue for the pool of Thread objects used for * downloading, using a linked list queue that blocks when the queue is * empty. */ mDownloadWorkQueue = new LinkedBlockingQueue<Runnable>(); /* * Creates a work queue for the pool of Thread objects used for * decoding, using a linked list queue that blocks when the queue is * empty. */ mDecodeWorkQueue = new LinkedBlockingQueue<Runnable>(); /* * Creates a work queue for the set of of task objects that control * downloading and decoding, using a linked list queue that blocks when * the queue is empty. */ mPhotoTaskWorkQueue = new LinkedBlockingQueue<PhotoTask>(); /* * Creates a new pool of Thread objects for the download work queue */ mDownloadThreadPool = new ThreadPoolExecutor(CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE_TIME, KEEP_ALIVE_TIME_UNIT, mDownloadWorkQueue); /* * Creates a new pool of Thread objects for the decoding work queue */ mDecodeThreadPool = new ThreadPoolExecutor(NUMBER_OF_CORES, NUMBER_OF_CORES, KEEP_ALIVE_TIME, KEEP_ALIVE_TIME_UNIT, mDecodeWorkQueue); // Instantiates a new cache based on the cache size estimate mPhotoCache = new LruCache<URL, byte[]>(IMAGE_CACHE_SIZE) { /* * This overrides the default sizeOf() implementation to return the * correct size of each cache entry. */ @Override protected int sizeOf(URL paramURL, byte[] paramArrayOfByte) { return paramArrayOfByte.length; } }; /* * Instantiates a new anonymous Handler object and defines its * handleMessage() method. The Handler *must* run on the UI thread, * because it moves photo Bitmaps from the PhotoTask object to the View * object. To force the Handler to run on the UI thread, it's defined as * part of the PhotoManager constructor. The constructor is invoked when * the class is first referenced, and that happens when the View invokes * startDownload. Since the View runs on the UI Thread, so does the * constructor and the Handler. */ mHandler = new Handler(Looper.getMainLooper()) { /* * handleMessage() defines the operations to perform when the * Handler receives a new Message to process. */ @Override public void handleMessage(Message inputMessage) { // Gets the image task from the incoming Message object. PhotoTask photoTask = (PhotoTask) inputMessage.obj; // Sets an PhotoView that's a weak reference to the // input ImageView PhotoView localView = photoTask.getPhotoView(); // If this input view isn't null if (localView != null) { /* * Gets the URL of the *weak reference* to the input * ImageView. The weak reference won't have changed, even if * the input ImageView has. */ URL localURL = localView.getLocation(); /* * Compares the URL of the input ImageView to the URL of the * weak reference. Only updates the bitmap in the ImageView * if this particular Thread is supposed to be serving the * ImageView. */ int downloadingImageId = localView.getCustomDownloadingImage(); int failImageId = localView.getCustomFailImage(); if (photoTask.getImageURL() == localURL) /* * Chooses the action to take, based on the incoming * message */ switch (inputMessage.what) { // If the download has started, sets background color to // dark green case DOWNLOAD_STARTED: Loge.i("DOWNLOAD_STARTED"); localView.setStatusResource(downloadingImageId); break; /* * If the download is complete, but the decode is * waiting, sets the background color to golden yellow */ case DOWNLOAD_COMPLETE: // Sets background color to golden yellow Loge.i("DOWNLOAD_COMPLETE"); localView.setStatusResource(downloadingImageId); break; // If the decode has started, sets background color to // orange case DECODE_STARTED: Loge.i("DECODE_STARTED"); localView.setStatusResource(downloadingImageId); break; /* * The decoding is done, so this sets the ImageView's * bitmap to the bitmap in the incoming message */ case TASK_COMPLETE: Loge.i("TASK_COMPLETE"); localView.setImageBitmap(photoTask.getImage()); recycleTask(photoTask); break; // The download failed, sets the background color to // dark red case DOWNLOAD_FAILED: Loge.i("DOWNLOAD_FAILED"); localView.setStatusResource(downloadingImageId); // Attempts to re-use the Task object recycleTask(photoTask); break; default: // Otherwise, calls the super method super.handleMessage(inputMessage); } } } }; }