當前位置: 首頁>>代碼示例>>Java>>正文


Java LinkedBlockingQueue類代碼示例

本文整理匯總了Java中java.util.concurrent.LinkedBlockingQueue的典型用法代碼示例。如果您正苦於以下問題:Java LinkedBlockingQueue類的具體用法?Java LinkedBlockingQueue怎麽用?Java LinkedBlockingQueue使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


LinkedBlockingQueue類屬於java.util.concurrent包,在下文中一共展示了LinkedBlockingQueue類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: IndexResultScanner

import java.util.concurrent.LinkedBlockingQueue; //導入依賴的package包/類
public IndexResultScanner(List<SingleScanner> scanners, byte[][] resultColumns,
    int resultBufferSize, float loadFactor) {
  this.scanners = scanners;
  this.resultColumns = resultColumns;
  this.resultBufferSize = resultBufferSize;
  this.loadFactor = loadFactor;
  this.minLoadSize = (int) (this.resultBufferSize * this.loadFactor);
  this.resultBuffer = new LinkedBlockingQueue<Result>(resultBufferSize);

  LOG.debug("IndexResultScanner is started!");

  this.scannerNum = this.scanners.size();
  this.finishedScanner = new ArrayList<String>();
  this.stoppedScanner = new ArrayList<String>();

  this.startTime = System.currentTimeMillis();

  int i = 0;
  for (SingleScanner scanner : this.scanners) {
    scanner.setName("Scanner" + i++);
    scanner.setIndexResultScanner(this);
    scanner.start();
  }
  this.restartTimes = 0;
  this.MAX_RESTART_TIMES = HBaseConfiguration.create().getInt("hbase.client.retries.number", 10);
}
 
開發者ID:fengchen8086,項目名稱:ditb,代碼行數:27,代碼來源:IndexResultScanner.java

示例2: create

import java.util.concurrent.LinkedBlockingQueue; //導入依賴的package包/類
/**
 * Create a cache which will reside in {@code directory}. This cache is lazily initialized on
 * first access and will be created if it does not exist.
 *
 * @param directory a writable directory
 * @param valueCount the number of values per cache entry. Must be positive.
 * @param maxSize the maximum number of bytes this cache should use to store
 */
public static DiskLruCache create(FileSystem fileSystem, File directory, int appVersion,
    int valueCount, long maxSize) {
  if (maxSize <= 0) {
    throw new IllegalArgumentException("maxSize <= 0");
  }
  if (valueCount <= 0) {
    throw new IllegalArgumentException("valueCount <= 0");
  }

  // Use a single background thread to evict entries.
  Executor executor = new ThreadPoolExecutor(0, 1, 60L, TimeUnit.SECONDS,
      new LinkedBlockingQueue<Runnable>(), Util.threadFactory("OkHttp DiskLruCache", true));

  return new DiskLruCache(fileSystem, directory, appVersion, valueCount, maxSize, executor);
}
 
開發者ID:weiwenqiang,項目名稱:GitHub,代碼行數:24,代碼來源:DiskLruCache.java

示例3: rightBoundsOfProduceTasksTest

import java.util.concurrent.LinkedBlockingQueue; //導入依賴的package包/類
@Test
public void rightBoundsOfProduceTasksTest() throws Exception {
    BlockingQueue<Future<Optional<byte[]>>> tasksQueue = new LinkedBlockingQueue<>();
    S3DataLoaderMocker.mockPrimitiveLoadFromTo(mockFactory, DATA_SIZE);

    new ParallelPartsLoader(
            S3DataLoaderMocker.FAKE_URI,
            0,
            DATA_SIZE,
            mockFactory,
            tasksQueue
    );
    int numberOfFullChunks = 7;
    for (int i = 0; i < numberOfFullChunks; i++) {
        int ruleForIncreaseChunkSize = (i / 2 + 1) < 4 ? i / 2 + 1 : 3;
        checkRightSizeOfChunk(tasksQueue, (int) Math.pow(MIN_PART_SIZE, ruleForIncreaseChunkSize));
    }

    checkRightSizeOfChunk(tasksQueue, 1);
    Assert.assertFalse(tasksQueue.take().get().isPresent());
}
 
開發者ID:epam,項目名稱:htsjdk-s3-plugin,代碼行數:22,代碼來源:ParallelPartsLoaderTest.java

示例4: RowCache

import java.util.concurrent.LinkedBlockingQueue; //導入依賴的package包/類
/**
 * Create cache for a destination table.
 *
 * @param cxt the bireme context
 * @param tableName the table name to cached
 * @param pipeLine the pipeLine belongs to which
 */
public RowCache(Context cxt, String tableName, PipeLine pipeLine) {
  this.cxt = cxt;
  this.tableName = tableName;
  this.pipeLine = pipeLine;

  this.lastMergeTime = new Date().getTime();
  this.mergeInterval = cxt.conf.merge_interval;
  this.batchSize = cxt.conf.batch_size;

  this.rows = new LinkedBlockingQueue<Row>(cxt.conf.batch_size * 2);
  this.commitCallback = new LinkedBlockingQueue<CommitCallback>();

  this.localMerger = new LinkedList<RowBatchMerger>();
  for (int i = 0; i < cxt.conf.loader_task_queue_size; i++) {
    localMerger.add(new RowBatchMerger());
  }

  this.mergeResult = new LinkedBlockingQueue<Future<LoadTask>>(cxt.conf.loader_task_queue_size);
  this.loader = new ChangeLoader(cxt, pipeLine, tableName, mergeResult);

  // add statistics
  pipeLine.stat.addGaugeForCache(tableName, this);
}
 
開發者ID:HashDataInc,項目名稱:bireme,代碼行數:31,代碼來源:RowCache.java

示例5: createIOPoolExecutor

import java.util.concurrent.LinkedBlockingQueue; //導入依賴的package包/類
private ThreadPoolExecutor createIOPoolExecutor(){
	//IO線程工廠類
	ThreadFactory threadFactory = new ThreadFactory() {
		@Override
		public Thread newThread(@NonNull Runnable runnable) {
			Thread thread = new Thread(runnable);
			thread.setName("dunit-io");
			return thread;
		}
	};

	//創建一個任務拒絕策略
	//直接忽略新進的任務
	RejectedExecutionHandler rejectedExecutionHandler = new ThreadPoolExecutor.DiscardPolicy();
	//創建一個最大線程數為3的線程池
	ThreadPoolExecutor poolExecutor = new ThreadPoolExecutor(1, 3, 3, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(10),threadFactory,rejectedExecutionHandler);
	//當核心線程空閑時,允許殺死核心線程
	poolExecutor.allowCoreThreadTimeOut(true);
	return poolExecutor;
}
 
開發者ID:tik5213,項目名稱:DUnit,代碼行數:21,代碼來源:DUnitThreadManager.java

示例6: taskProducerShouldTerminateWhenItIsCanceled

import java.util.concurrent.LinkedBlockingQueue; //導入依賴的package包/類
@Test
public void taskProducerShouldTerminateWhenItIsCanceled() throws InterruptedException {
    BlockingQueue<Future<Optional<byte[]>>> tasksQueue = new LinkedBlockingQueue<>();

    ParallelPartsLoader taskProducer = new ParallelPartsLoader(
            S3DataLoaderMocker.FAKE_URI,
            0,
            DATA_SIZE,
            mockFactory,
            tasksQueue
    );
    CompletableFuture.runAsync(taskProducer)
            .thenAccept(r -> taskProducer.cancelLoading())
            .thenAccept(r -> Assert.assertTrue(tasksQueue.isEmpty()));

}
 
開發者ID:epam,項目名稱:htsjdk-s3-plugin,代碼行數:17,代碼來源:ParallelPartsLoaderTest.java

示例7: putAllCollections

import java.util.concurrent.LinkedBlockingQueue; //導入依賴的package包/類
static void putAllCollections(Map<Class<?>, IntFunction<?>> map, Map<Class<?>, Function<?, ?>> unmodMap)
{
    safePut(map, ArrayList.class, ArrayList::new);
    safePut(map, HashSet.class, LinkedHashSet::new);
    safePut(map, Properties.class, x -> new Properties());
    safePut(map, Hashtable.class, Hashtable::new);

    safePut(map, Collection.class, ArrayList::new);
    safePut(map, Set.class, LinkedHashSet::new);
    safePut(map, List.class, ArrayList::new);
    safePut(map, SortedSet.class, x -> new TreeSet<>());
    safePut(map, Queue.class, x -> new ConcurrentLinkedQueue<>());
    safePut(map, Deque.class, x -> new ConcurrentLinkedDeque<>());
    safePut(map, BlockingQueue.class, x -> new LinkedBlockingQueue<>());
    safePut(map, BlockingDeque.class, x -> new LinkedBlockingDeque<>());


    safePut(map, HashMap.class, LinkedHashMap::new);
    safePut(map, LinkedHashMap.class, LinkedHashMap::new);
    safePut(map, ConcurrentHashMap.class, ConcurrentHashMap::new);

    safePut(map, Map.class, LinkedHashMap::new);
    safePut(map, ConcurrentMap.class, x -> new ConcurrentSkipListMap<>());
    safePut(map, ConcurrentNavigableMap.class, x -> new ConcurrentSkipListMap<>());
    safePut(map, SortedMap.class, i -> new TreeMap<>());
}
 
開發者ID:GotoFinal,項目名稱:diorite-configs-java8,代碼行數:27,代碼來源:YamlCollectionCreator.java

示例8: setRoadTrafficNotInNavigate

import java.util.concurrent.LinkedBlockingQueue; //導入依賴的package包/類
/**
 * 檢查路書是否堵車
 *
 * @param target     目標地點
 * @param routeModel 路書
 * @param sb         路況信息
 * @return true=是
 */
private boolean setRoadTrafficNotInNavigate(String target, RouteModel routeModel, StringBuilder sb) {
    routeModel.refreshRoadCondition();
    Log.i(TAG, "conditionNodes.size=" + routeModel.getConditionNodes().size());
    Queue<Integer> rQueue = new LinkedBlockingQueue<Integer>();
    int conjestionCount = 0;
    for (int i = 0; i < routeModel.getConditionNodes().size(); ++i) {
        if (routeModel.getConditionNodes().get(i).getRoadCondition() >= RouteModel.ROAD_CONDITION_TYPE_Slow) {
            rQueue.offer(i);
            if (routeModel.getConditionNodes().get(i).getRoadCondition() > RouteModel.ROAD_CONDITION_TYPE_Slow) {
                conjestionCount++;
            }
        }
    }
    return setTrafficState(sb, routeModel, rQueue, conjestionCount, 0);
}
 
開發者ID:LingjuAI,項目名稱:AssistantBySDK,代碼行數:24,代碼來源:NavigatorService.java

示例9: init

import java.util.concurrent.LinkedBlockingQueue; //導入依賴的package包/類
@Override
public void init(FloodlightModuleContext context)
		throws FloodlightModuleException {
	linkDiscoveryService = context.getServiceImpl(ILinkDiscoveryService.class);
	threadPoolService = context.getServiceImpl(IThreadPoolService.class);
	floodlightProviderService = context.getServiceImpl(IFloodlightProviderService.class);
	switchService = context.getServiceImpl(IOFSwitchService.class);
	restApiService = context.getServiceImpl(IRestApiService.class);
	debugCounterService = context.getServiceImpl(IDebugCounterService.class);
	debugEventService = context.getServiceImpl(IDebugEventService.class);

	switchPorts = new HashMap<DatapathId, Set<OFPort>>();
	switchPortLinks = new HashMap<NodePortTuple, Set<Link>>();
	directLinks = new HashMap<NodePortTuple, Set<Link>>();
	portBroadcastDomainLinks = new HashMap<NodePortTuple, Set<Link>>();
	tunnelPorts = new HashSet<NodePortTuple>();
	topologyAware = new ArrayList<ITopologyListener>();
	ldUpdates = new LinkedBlockingQueue<LDUpdate>();
	haListener = new HAListenerDelegate();
	registerTopologyDebugCounters();
	registerTopologyDebugEvents();
}
 
開發者ID:xuraylei,項目名稱:fresco_floodlight,代碼行數:23,代碼來源:TopologyManager.java

示例10: main

import java.util.concurrent.LinkedBlockingQueue; //導入依賴的package包/類
public static void main(String[] args) {
	BlockingQueue<Integer> blockingQueue = new LinkedBlockingQueue<Integer>(3);
	Producer producer = new Producer(blockingQueue);
	Consumer consumer = new Consumer(blockingQueue);
	// 創建5個生產者,5個消費者
	for (int i = 0; i < 6; i++) {
		if (i < 5) {
			new Thread(producer, "producer" + i).start();
		} else {
			new Thread(consumer, "consumer" + (i - 5)).start();
		}
	}

	try {
		Thread.sleep(1000);
	} catch (InterruptedException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	producer.shutDown();
	consumer.shutDown();
}
 
開發者ID:leon66666,項目名稱:JavaCommon,代碼行數:23,代碼來源:BlockingQueueDemo.java

示例11: findScrollableViewInternal

import java.util.concurrent.LinkedBlockingQueue; //導入依賴的package包/類
protected View findScrollableViewInternal(View content, boolean selfable) {
    View scrollableView = null;
    Queue<View> views = new LinkedBlockingQueue<>(Collections.singletonList(content));
    while (!views.isEmpty() && scrollableView == null) {
        View view = views.poll();
        if (view != null) {
            if ((selfable || view != content) && isScrollableView(view)) {
                scrollableView = view;
            } else if (view instanceof ViewGroup) {
                ViewGroup group = (ViewGroup) view;
                for (int j = 0; j < group.getChildCount(); j++) {
                    views.add(group.getChildAt(j));
                }
            }
        }
    }
    return scrollableView == null ? content : scrollableView;
}
 
開發者ID:scwang90,項目名稱:SmartRefreshLayout,代碼行數:19,代碼來源:RefreshContentWrapper.java

示例12: initDictionaryCaches

import java.util.concurrent.LinkedBlockingQueue; //導入依賴的package包/類
private void initDictionaryCaches(DictionaryDAOImpl dictionaryDAO, TenantService tenantService)
{
    CompiledModelsCache compiledModelsCache = new CompiledModelsCache();
    compiledModelsCache.setDictionaryDAO(dictionaryDAO);
    compiledModelsCache.setTenantService(tenantService);
    compiledModelsCache.setRegistry(new DefaultAsynchronouslyRefreshedCacheRegistry());
    TraceableThreadFactory threadFactory = new TraceableThreadFactory();
    threadFactory.setThreadDaemon(true);
    threadFactory.setThreadPriority(Thread.NORM_PRIORITY);

    ThreadPoolExecutor threadPoolExecutor = new DynamicallySizedThreadPoolExecutor(20, 20, 90, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(), threadFactory,
            new ThreadPoolExecutor.CallerRunsPolicy());
    compiledModelsCache.setThreadPoolExecutor(threadPoolExecutor);
    dictionaryDAO.setDictionaryRegistryCache(compiledModelsCache);
    dictionaryDAO.init();
}
 
開發者ID:Alfresco,項目名稱:alfresco-data-model,代碼行數:17,代碼來源:DictionaryDAOTest.java

示例13: SyncRunner

import java.util.concurrent.LinkedBlockingQueue; //導入依賴的package包/類
/**
 * UPDATE!
 * @param syncs the batch of calls to sync that arrived as this thread was starting; when done,
 * we will put the result of the actual hdfs sync call as the result.
 * @param sequence The sequence number on the ring buffer when this thread was set running.
 * If this actual writer sync completes then all appends up this point have been
 * flushed/synced/pushed to datanodes.  If we fail, then the passed in <code>syncs</code>
 * futures will return the exception to their clients; some of the edits may have made it out
 * to data nodes but we will report all that were part of this session as failed.
 */
SyncRunner(final String name, final int maxHandlersCount) {
  super(name);
  // LinkedBlockingQueue because of
  // http://www.javacodegeeks.com/2010/09/java-best-practices-queue-battle-and.html
  // Could use other blockingqueues here or concurrent queues.
  //
  // We could let the capacity be 'open' but bound it so we get alerted in pathological case
  // where we cannot sync and we have a bunch of threads all backed up waiting on their syncs
  // to come in.  LinkedBlockingQueue actually shrinks when you remove elements so Q should
  // stay neat and tidy in usual case.  Let the max size be three times the maximum handlers.
  // The passed in maxHandlerCount is the user-level handlers which is what we put up most of
  // but HBase has other handlers running too -- opening region handlers which want to write
  // the meta table when succesful (i.e. sync), closing handlers -- etc.  These are usually
  // much fewer in number than the user-space handlers so Q-size should be user handlers plus
  // some space for these other handlers.  Lets multiply by 3 for good-measure.
  this.syncFutures = new LinkedBlockingQueue<SyncFuture>(maxHandlersCount * 3);
}
 
開發者ID:fengchen8086,項目名稱:ditb,代碼行數:28,代碼來源:FSHLog.java

示例14: output

import java.util.concurrent.LinkedBlockingQueue; //導入依賴的package包/類
/**
 * Output the items in the stream with a function.
 * This method will block until the result returns.
 * Eg. `output(StatisticOperators.count())` will output the number of items.
 *
 * @param itemsCollector the function used to output current stream
 * @param <Tout> the type of the result
 * @return the result
 * @throws PSException if failed to the result.
 */
@PSAction(blocking = true)
public <Tout> Tout output(Function<List<Item>, Tout> itemsCollector) throws PSException {
    final BlockingQueue<Object> resultQueue = new LinkedBlockingQueue<>();
    Callback<Tout> resultHandler = new Callback<Tout>() {
        @Override
        protected void onInput(Tout input) {
            resultQueue.add(input);
        }

        @Override
        protected void onFail(PSException exception) {
            resultQueue.add(exception);
        }
    };
    this.output(itemsCollector, resultHandler);
    try {
        Object resultOrException = resultQueue.take();
        if (resultOrException instanceof PSException) {
            throw (PSException) resultOrException;
        }
        return (Tout) resultOrException;
    } catch (InterruptedException e) {
        throw PSException.INTERRUPTED(e.getMessage());
    }
}
 
開發者ID:PrivacyStreams,項目名稱:PrivacyStreams,代碼行數:36,代碼來源:PStream.java

示例15: parallelPixelFromGeo

import java.util.concurrent.LinkedBlockingQueue; //導入依賴的package包/類
/**
 * 
 * @param coords
 * @return
 * @throws InterruptedException
 * @throws ExecutionException
 */
public List<double[]> parallelPixelFromGeo(final Coordinate[] coords)
		throws InterruptedException, ExecutionException {
	int processors = Runtime.getRuntime().availableProcessors();
	ThreadPoolExecutor executor = new ThreadPoolExecutor(2, processors, 2, TimeUnit.SECONDS,
			new LinkedBlockingQueue<Runnable>());//(ThreadPoolExecutor)Executors.newFixedThreadPool(processors);
	try {
		final List<Future<double[]>> tasks = new ArrayList<Future<double[]>>();
		for (int i = 0; i < coords.length; i++) {
			tasks.add(executor.submit(new ParallelReverse(coords[i].x, coords[i].y)));
		}
		executor.shutdown();

		final List<double[]> points = new ArrayList<double[]>();
		for (Future<double[]> result : tasks) {
			List<double[]> l = Arrays.asList(result.get());
			points.addAll(l);
		}

		return points;
	} catch (Exception e) {
		if (!executor.isShutdown())
			executor.shutdown();
		throw e;
	}
}
 
開發者ID:ec-europa,項目名稱:sumo,代碼行數:33,代碼來源:ParallelGeoCoding.java


注:本文中的java.util.concurrent.LinkedBlockingQueue類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。