Java Code Examples for java.util.concurrent.ConcurrentLinkedQueue

The following code examples are extracted from open source projects. You can click to vote up the examples that are useful to you.

Example 1

From project netty-socketio, under directory /src/test/java/com/corundumstudio/socketio/parser/.

Source file: EncoderJsonPacketTest.java

  32 
vote

@Test public void testPerf() throws IOException {
  List<Packet> packets=new ArrayList<Packet>();
  for (int i=0; i < 100; i++) {
    Packet packet=new Packet(PacketType.JSON);
    packet.setId(1L);
    packet.setData(Collections.singletonMap("??????","123123jksdf213"));
    packets.add(packet);
  }
  List<Queue<Packet>> queues=new ArrayList<Queue<Packet>>();
  for (int i=0; i < 5000; i++) {
    ConcurrentLinkedQueue queue=new ConcurrentLinkedQueue(packets);
    queues.add(queue);
  }
  long t=System.currentTimeMillis();
  for (int i=0; i < 5000; i++) {
    encoder.encodePackets(queues.get(i));
  }
  System.out.println(System.currentTimeMillis() - t);
}
 

Example 2

From project activejdbc, under directory /activejdbc/src/test/java/org/javalite/activejdbc/.

Source file: RaceConditionTest.java

  29 
vote

@Test public void shouldNotGetRaceCondition() throws InterruptedException {
  final ConcurrentLinkedQueue<Integer> queue=new ConcurrentLinkedQueue<Integer>();
  Runnable r=new Runnable(){
    public void run(){
      Base.open("com.mysql.jdbc.Driver","jdbc:mysql://localhost/activejdbc","root","p@ssw0rd");
      Person p=new Person();
      p.set("name","Igor");
      Base.close();
      queue.add(1);
    }
  }
;
  for (int i=0; i < 10; i++) {
    new Thread(r).start();
  }
  Thread.sleep(2000);
  a(queue.size()).shouldEqual(10);
}
 

Example 3

From project AeminiumRuntime, under directory /src/aeminium/runtime/implementations/implicitworkstealing/scheduler/.

Source file: BlockingWorkStealingScheduler.java

  29 
vote

public void init(EventManager eventManager){
  this.eventManager=eventManager;
  this.parkedThreads=new ConcurrentLinkedQueue<WorkStealingThread>();
  this.threads=new WorkStealingThread[maxParallelism];
  this.counter=new AtomicInteger(threads.length);
  this.submissionQueue=new ConcurrentLinkedQueue<ImplicitTask>();
  this.wsa=loadWorkStealingAlgorithm(Configuration.getProperty(BlockingWorkStealingScheduler.class,"workStealingAlgorithm","SequentialReverseScan"));
  if (useBlockingThreadPool) {
    blockingThreadPool=new BlockingThreadPool();
    blockingThreadPool.init(rt,eventManager);
  }
  for (int i=0; i < threads.length; i++) {
    threads[i]=new WorkStealingThread(rt,i);
  }
  wsa.init(threads,submissionQueue);
  for (  WorkStealingThread thread : threads) {
    thread.start();
  }
}
 

Example 4

From project agraph-java-client, under directory /src/com/franz/agraph/http/.

Source file: AGHttpRepoClient.java

  29 
vote

public AGHttpRepoClient(AGAbstractRepository repo,AGHTTPClient client,String repoRoot,String sessionRoot){
  this.repo=repo;
  this.sessionRoot=sessionRoot;
  this.repoRoot=repoRoot;
  this.client=client;
  savedQueryDeleteQueue=new ConcurrentLinkedQueue<String>();
}
 

Example 5

From project Aion-Extreme, under directory /AE-go_GameServer/src/com/aionemu/gameserver/model/gameobjects/player/.

Source file: FriendList.java

  29 
vote

/** 
 * Constructs a friend list for the given player, with the given friends
 * @param player Player who has this friend list
 * @param friends Friends on the list
 */
public FriendList(Player owner,Collection<Friend> newFriends){
  this.friends=new ConcurrentLinkedQueue<Friend>(newFriends);
  this.player=owner;
  ((EnhancedObject)player).addCallback(new PlayerLoggedOutListener(){
    @Override protected void onLoggedOut(    Player loggedOutPlayer){
      setStatus(FriendList.Status.OFFLINE);
    }
  }
);
}
 

Example 6

From project Arecibo, under directory /alert/src/main/java/com/ning/arecibo/alert/objects/.

Source file: ThresholdConfig.java

  29 
vote

public synchronized boolean checkMinThresholdSamplesReached(Event evt){
  if (this.minThresholdSamples == null || this.minThresholdSamples <= 1 || this.maxSampleWindowMs == null || this.maxSampleWindowMs <= 0) {
    return true;
  }
  String contextIdentifier=getContextIdentifier(evt);
  _ActiveThresholdContext atc=this.activeThresholdContexts.get(contextIdentifier);
  ConcurrentLinkedQueue<Event> queue=(atc == null) ? null : atc.getSampleWindowQueue();
  if (queue == null) {
    queue=new ConcurrentLinkedQueue<Event>();
    if (atc == null) {
      atc=new _ActiveThresholdContext(contextIdentifier);
      this.activeThresholdContexts.put(contextIdentifier,atc);
    }
    atc.setSampleWindowQueue(queue);
  }
  queue.add(evt);
  long sampleWindowStartMillis=System.currentTimeMillis() - this.maxSampleWindowMs;
  while (queue.size() > 0) {
    Event headEvt=queue.peek();
    if (headEvt == null || headEvt.getTimestamp() > sampleWindowStartMillis) {
      break;
    }
    queue.poll();
  }
  if (queue.size() >= this.minThresholdSamples) {
    return true;
  }
 else {
    return false;
  }
}
 

Example 7

From project bonecp, under directory /bonecp/src/test/java/com/jolbox/bonecp/.

Source file: TestConnectionHandle.java

  29 
vote

/** 
 * Closing a connection handle should release that connection back in the pool and mark it as closed.
 * @throws SecurityException
 * @throws NoSuchFieldException
 * @throws IllegalArgumentException
 * @throws IllegalAccessException
 * @throws InvocationTargetException
 * @throws NoSuchMethodException
 * @throws SQLException
 */
@SuppressWarnings("unchecked") @Test public void testInternalClose() throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException, InvocationTargetException, NoSuchMethodException, SQLException {
  ConcurrentLinkedQueue<Statement> mockStatementHandles=createNiceMock(ConcurrentLinkedQueue.class);
  StatementHandle mockStatement=createNiceMock(StatementHandle.class);
  this.mockConnection.close();
  expectLastCall().once().andThrow(new SQLException()).once();
  Map<Connection,Reference<ConnectionHandle>> refs=new HashMap<Connection,Reference<ConnectionHandle>>();
  expect(this.mockPool.getFinalizableRefs()).andReturn(refs).anyTimes();
  FinalizableReferenceQueue finalizableRefQueue=new FinalizableReferenceQueue();
  expect(this.mockPool.getFinalizableRefQueue()).andReturn(finalizableRefQueue).anyTimes();
  expect(this.mockConnection.getPool()).andReturn(this.mockPool).anyTimes();
  Field f=this.testClass.getClass().getDeclaredField("finalizableRefs");
  f.setAccessible(true);
  f.set(this.testClass,refs);
  replay(mockStatement,this.mockConnection,mockStatementHandles,this.mockPool);
  this.testClass.internalClose();
  try {
    this.testClass.internalClose();
    fail("Should have thrown an exception");
  }
 catch (  Throwable t) {
  }
  verify(mockStatement,this.mockConnection,mockStatementHandles);
}
 

Example 8

From project cometd, under directory /cometd-java/cometd-java-client/src/test/java/org/cometd/client/.

Source file: TimeExtensionsTest.java

  29 
vote

@Test public void testTimeStamp() throws Exception {
  bayeux.addExtension(new TimestampExtension());
  final BayeuxClient client=newBayeuxClient();
  client.addExtension(new TimestampClientExtension());
  final Queue<Message> messages=new ConcurrentLinkedQueue<>();
  client.getChannel(Channel.META_HANDSHAKE).addListener(new ClientSessionChannel.MessageListener(){
    public void onMessage(    ClientSessionChannel channel,    Message message){
      messages.add(message);
    }
  }
);
  client.handshake();
  Assert.assertTrue(client.waitFor(5000,BayeuxClient.State.CONNECTED));
  Assert.assertTrue(client.disconnect(5000));
  Assert.assertTrue(messages.size() > 0);
  for (  Message message : messages)   Assert.assertTrue(message.get(Message.TIMESTAMP_FIELD) != null);
  disconnectBayeuxClient(client);
}
 

Example 9

From project cpp-maven-plugins, under directory /cpp-compiler-maven-plugin/src/main/java/com/ericsson/tools/cpp/compiler/classprocessing/.

Source file: FilesProcessor.java

  29 
vote

public FilesProcessor(final String name,final Log log,final BlockingQueue<NativeCodeFile> classesToProcess,final ConcurrentLinkedQueue<NativeCodeFile> processedClasses,final int numberOfProcessorThreads,final Object monitor){
  this.name=name;
  this.log=log;
  this.classesToProcess=classesToProcess;
  this.processedClasses=processedClasses;
  this.numberOfProcessorThreads=numberOfProcessorThreads;
  this.monitor=monitor;
}
 

Example 10

From project crammer, under directory /src/main/java/uk/ac/ebi/ena/sra/cram/bam/.

Source file: BAMFileQueryQueues.java

  29 
vote

public Queue<SAMRecord> getQueueForQuery(String sequenceName,int start,int end,boolean overlapping){
  SAMFileReader reader=new SAMFileReader(bamFile);
  SAMRecordIterator iterator=reader.query(sequenceName,start,end,overlapping);
  Queue<SAMRecord> queue=new ConcurrentLinkedQueue<SAMRecord>();
  startQuery(iterator,queue);
  return queue;
}
 

Example 11

From project dawn-isencia, under directory /com.isencia.passerelle.engine/src/main/java/com/isencia/passerelle/actor/v5/.

Source file: Actor.java

  29 
vote

@Override public Object clone(Workspace workspace) throws CloneNotSupportedException {
  final Actor actor=(Actor)super.clone(workspace);
  actor.blockingInputHandlers=new ArrayList<PortHandler>();
  actor.blockingInputFinishRequests=new ArrayList<Boolean>();
  actor.pushedMessages=new ConcurrentLinkedQueue<MessageInputContext>();
  actor.msgProviders=new HashSet<Object>();
  return actor;
}
 

Example 12

From project droolsjbpm-integration, under directory /droolsjbpm-integration-examples/src/main/java/org/drools/examples/broker/ui/.

Source file: ScrollingBanner.java

  29 
vote

public ScrollingBanner(){
  super();
  ticks=new ConcurrentLinkedQueue<StockTick>();
  setBackground(Color.BLACK);
  setForeground(Color.GREEN);
  setFont(new JTextField().getFont().deriveFont(Font.BOLD));
  setPreferredSize(new Dimension(500,20));
}
 

Example 13

From project eucalyptus, under directory /clc/modules/cluster-manager/src/edu/ucsb/eucalyptus/cloud/cluster/.

Source file: ClusterAllocator.java

  29 
vote

public ClusterAllocator(ResourceToken vmToken,VmAllocationInfo vmAllocInfo){
  this.msgMap=Multimaps.newHashMultimap();
  this.vmAllocInfo=vmAllocInfo;
  this.pendingEvents=new ConcurrentLinkedQueue<QueuedEvent>();
  this.cluster=Clusters.getInstance().lookup(vmToken.getCluster());
  this.state=State.START;
  this.rollback=new AtomicBoolean(false);
  for (  NetworkToken networkToken : vmToken.getNetworkTokens())   this.setupNetworkMessages(networkToken);
  this.setupVmMessages(vmToken);
}
 

Example 14

From project flazr, under directory /src/main/java/org/red5/server/so/.

Source file: SharedObjectMessage.java

  29 
vote

/** 
 * Creates Shared Object event with given listener, name, SO version and persistence flag
 * @param source Event listener
 * @param name Event name
 * @param version SO version
 * @param persistent SO persistence flag
 */
public SharedObjectMessage(IEventListener source,String name,int version,boolean persistent){
  this.name=name;
  this.version=version;
  this.persistent=persistent;
  this.events=new ConcurrentLinkedQueue<ISharedObjectEvent>();
}
 

Example 15

From project floodlight, under directory /src/main/java/net/floodlightcontroller/counter/.

Source file: ConcurrentCounter.java

  29 
vote

protected void init(Date startDate){
  this.startDate=startDate;
  this.unprocessedCountBuffer=new ConcurrentLinkedQueue<CountAtom>();
  this.counts=new HashMap<DateSpan,CountBuffer>();
  for (  DateSpan ds : DateSpan.values()) {
    CountBuffer cb=new CountBuffer(startDate,ds,MAX_HISTORY.get(ds));
    counts.put(ds,cb);
  }
}
 

Example 16

From project Gibberbot, under directory /src/info/guardianproject/otr/app/im/plugin/xmpp/.

Source file: XmppStreamHandler.java

  29 
vote

private void sendEnablePacket(){
  debug("sm send enable " + sessionId);
  if (sessionId != null) {
    isOutgoingSmEnabled=true;
    StreamHandlingPacket resumePacket=new StreamHandlingPacket("resume",URN_SM_2);
    resumePacket.addAttribute("h",String.valueOf(previousIncomingStanzaCount));
    resumePacket.addAttribute("previd",sessionId);
    mConnection.sendPacket(resumePacket);
  }
 else {
    outgoingStanzaCount=0;
    outgoingQueue=new ConcurrentLinkedQueue<Packet>();
    isOutgoingSmEnabled=true;
    StreamHandlingPacket enablePacket=new StreamHandlingPacket("enable",URN_SM_2);
    enablePacket.addAttribute("resume","true");
    mConnection.sendPacket(enablePacket);
  }
}
 

Example 17

From project grails-data-mapping, under directory /grails-datastore-core/src/main/groovy/org/grails/datastore/mapping/core/.

Source file: AbstractSession.java

  29 
vote

public void addPendingInsert(PendingInsert insert){
  Collection<PendingInsert> inserts=pendingInserts.get(insert.getEntity());
  if (inserts == null) {
    inserts=new ConcurrentLinkedQueue<PendingInsert>();
    pendingInserts.put(insert.getEntity(),inserts);
  }
  inserts.add(insert);
}
 

Example 18

From project hank, under directory /src/java/com/rapleaf/hank/performance/.

Source file: ThriftClientTheoreticalLimit.java

  29 
vote

void test(String[] args) throws InterruptedException, IOException {
  parseCommandLine(args);
  populateConnections();
  int queryTotal=nbThread * queryPerThread;
  queryCount=new CountDownLatch(queryTotal);
  latencies=new ConcurrentLinkedQueue<Long>();
  LinkedList<Thread> threads=new LinkedList<Thread>();
  long qpsStart=System.nanoTime();
  for (int i=0; i < nbThread; ++i) {
    Thread thread=new Thread(new TheoreticalLimitRunnable(),"Runner");
    thread.start();
    threads.addLast(thread);
  }
  for (  Thread thread : threads) {
    thread.join();
  }
  queryCount.await();
  float elapsedS=Math.abs(((float)(System.nanoTime() - qpsStart)) / 1000000000);
  System.out.println("QPS is " + ((float)queryTotal / elapsedS) + " ("+ queryTotal+ ", "+ elapsedS+ ")");
  for (  Long l : latencies) {
    System.out.println((float)l / 1000000.);
  }
}
 

Example 19

From project hawtdispatch, under directory /hawtdispatch/src/main/java/org/fusesource/hawtdispatch/internal/pool/.

Source file: SimpleThread.java

  29 
vote

@Override public void run(){
  debug("run start");
  try {
    ConcurrentLinkedQueue<Task> sharedQueue=pool.tasks;
    while (!pool.shutdown) {
      Task task=threadQueue.poll();
      if (task == null) {
        task=sharedQueue.poll();
        if (task == null) {
          task=threadQueue.getSourceQueue().poll();
        }
      }
      if (task == null) {
        pool.park(this);
      }
 else {
        task.run();
      }
    }
  }
  finally {
    debug("run end");
  }
}
 

Example 20

From project hbase-dsl, under directory /src/main/java/com/nearinfinity/hbase/dsl/.

Source file: HBase.java

  29 
vote

private Queue<Delete> getDeletes(byte[] tableName){
  Queue<Delete> queue=deletesMap.get(tableName);
  if (queue == null) {
    queue=new ConcurrentLinkedQueue<Delete>();
    deletesMap.put(tableName,queue);
  }
  return queue;
}
 

Example 21

From project httpcore, under directory /httpcore-nio/src/main/java/org/apache/http/impl/nio/reactor/.

Source file: AbstractIOReactor.java

  29 
vote

/** 
 * Creates new AbstractIOReactor instance.
 * @param selectTimeout the select timeout.
 * @param interestOpsQueueing Ops queueing flag.
 * @throws IOReactorException in case if a non-recoverable I/O error.
 * @since 4.1
 */
public AbstractIOReactor(long selectTimeout,boolean interestOpsQueueing) throws IOReactorException {
  super();
  Args.positive(selectTimeout,"Select timeout");
  this.selectTimeout=selectTimeout;
  this.interestOpsQueueing=interestOpsQueueing;
  this.sessions=Collections.synchronizedSet(new HashSet<IOSession>());
  this.interestOpsQueue=new ConcurrentLinkedQueue<InterestOpEntry>();
  this.closedSessions=new ConcurrentLinkedQueue<IOSession>();
  this.newChannels=new ConcurrentLinkedQueue<ChannelEntry>();
  try {
    this.selector=Selector.open();
  }
 catch (  IOException ex) {
    throw new IOReactorException("Failure opening selector",ex);
  }
  this.statusMutex=new Object();
  this.status=IOReactorStatus.INACTIVE;
}
 

Example 22

From project httptunnel, under directory /src/main/java/com/yammer/httptunnel/client/.

Source file: HttpTunnelClientChannelSendHandler.java

  29 
vote

public HttpTunnelClientChannelSendHandler(HttpTunnelClientWorkerOwner tunnelChannel){
  this.tunnelChannel=tunnelChannel;
  disconnecting=new AtomicBoolean(false);
  queuedWrites=new ConcurrentLinkedQueue<TimedMessageEventWrapper>();
  pendingRequestCount=new AtomicInteger(0);
  Metrics.newGauge(HttpTunnelClientChannelSendHandler.class,"queuedWrites",new Gauge<Integer>(){
    @Override public Integer value(){
      return queuedWrites.size();
    }
  }
);
  tunnelId=null;
  postShutdownEvent=null;
  sendRequestTime=0;
}
 

Example 23

From project JavaStory, under directory /Core/src/main/java/javastory/db/.

Source file: Database.java

  29 
vote

private Database(){
  try {
    DriverManager.registerDriver(new Driver());
  }
 catch (  final SQLException ex) {
    Logger.getLogger(Database.class.getName()).log(Level.SEVERE,null,ex);
  }
  this.connections=new ConcurrentLinkedQueue<>();
  final Map<String,String> properties=this.loadDbProperties();
  this.url=properties.get("url");
  this.username=properties.get("username");
  this.password=properties.get("password");
}
 

Example 24

From project juel, under directory /modules/impl/src/main/java/de/odysseus/el/tree/impl/.

Source file: Cache.java

  29 
vote

/** 
 * Creates a new cache with the specified capacity and concurrency level.
 * @param capacity Cache size. The actual map size may exceed it temporarily.
 * @param concurrencyLevel The estimated number of concurrently updating threads. The implementation performs internal sizing to try to accommodate this many threads.
 */
public Cache(int capacity,int concurrencyLevel){
  this.map=new ConcurrentHashMap<String,Tree>(16,0.75f,concurrencyLevel);
  this.queue=new ConcurrentLinkedQueue<String>();
  this.size=new AtomicInteger();
  this.capacity=capacity;
}
 

Example 25

From project krati, under directory /krati-main/src/main/java/krati/core/array/entry/.

Source file: EntryPool.java

  29 
vote

public EntryPool(EntryFactory<T> factory,int entryCapacity){
  this._entryFactory=factory;
  this._entryCapacity=entryCapacity;
  this._serviceQueue=new ConcurrentLinkedQueue<Entry<T>>();
  this._recycleQueue=new ConcurrentLinkedQueue<Entry<T>>();
}
 

Example 26

From project Metamorphosis, under directory /metamorphosis-integration-test/src/test/java/com/taobao/meta/test/.

Source file: BaseMetaTest.java

  29 
vote

public void subscribe_nConsumer(final String topic,final int maxsize,final int count,final int consumerNum,final int producerNum) throws Exception {
  this.consumerList=new ArrayList<MessageConsumer>();
  for (int i=0; i < consumerNum; i++) {
    final ConcurrentLinkedQueue<Message> singlequeue=new ConcurrentLinkedQueue<Message>();
    this.consumerList.add(i,this.sessionFactory.createConsumer(new ConsumerConfig("group" + i)));
    this.consumerList.get(i).subscribe(topic,maxsize,new MessageListener(){
      public void recieveMessages(      final Message messages){
        BaseMetaTest.this.queue.add(messages);
        singlequeue.add(messages);
      }
      public Executor getExecutor(){
        return null;
      }
    }
).completeSubscribe();
    while (singlequeue.size() < count * producerNum) {
      Thread.sleep(1000);
      System.out.println("??????" + count * producerNum + "???????" + singlequeue.size() + "?");
    }
    assertEquals(count * producerNum,singlequeue.size());
    System.out.println(singlequeue.size());
    for (    final Message msg : this.messages) {
      assertTrue(singlequeue.contains(msg));
    }
  }
  while (this.queue.size() < count * producerNum * consumerNum) {
    Thread.sleep(1000);
    System.out.println("??????count*num???????" + this.queue.size() + "?");
  }
  assertEquals(count * producerNum * consumerNum,this.queue.size());
  System.out.println(this.queue.size());
  for (  final Message msg : this.messages) {
    assertTrue(this.queue.contains(msg));
  }
}
 

Example 27

From project OlympicPhoneBox, under directory /src/olympic/screens/.

Source file: ScreenIconManager.java

  29 
vote

/** 
 * create a new instance of the screenGUI system for retrieving motion sensitive filter changes
 * @param configuration the configuration of the screen
 * @param height        the maximum height of the icon manager for optimisation purposes
 */
public ScreenIconManager(ScreenConfiguration configuration,int height){
  this.height=height;
  this.touched=-1;
  this.active=-1;
  this.running=true;
  this.configuration=configuration;
  this.storage=CvMemStorage.create();
  this.images=new ConcurrentLinkedQueue<IplImage>();
  this.icons=new Vector<ScreenIcon>();
  for (int i=0, w=(configuration.width / configuration.filters.length); configuration.filters.length > i; i++) {
    this.icons.add(new ScreenIcon(cvRect(w * i,0,w,this.height)));
  }
}
 

Example 28

From project omid, under directory /src/main/java/com/yahoo/omid/client/.

Source file: TSOClient.java

  29 
vote

public TSOClient(Configuration conf) throws IOException {
  state=State.DISCONNECTED;
  queuedOps=new ArrayBlockingQueue<Op>(200);
  retryTimer=new Timer(true);
  commitCallbacks=Collections.synchronizedMap(new HashMap<Long,CommitCallback>());
  isCommittedCallbacks=Collections.synchronizedMap(new HashMap<Long,List<CommitQueryCallback>>());
  createCallbacks=new ConcurrentLinkedQueue<CreateCallback>();
  channel=null;
  System.out.println("Starting TSOClient");
  factory=new NioClientSocketChannelFactory(Executors.newCachedThreadPool(),Executors.newCachedThreadPool(),3);
  bootstrap=new ClientBootstrap(factory);
  int executorThreads=conf.getInt("tso.executor.threads",3);
  bootstrap.getPipeline().addLast("executor",new ExecutionHandler(new OrderedMemoryAwareThreadPoolExecutor(executorThreads,1024 * 1024,4 * 1024 * 1024)));
  bootstrap.getPipeline().addLast("handler",this);
  bootstrap.setOption("tcpNoDelay",false);
  bootstrap.setOption("keepAlive",true);
  bootstrap.setOption("reuseAddress",true);
  bootstrap.setOption("connectTimeoutMillis",100);
  String host=conf.get("tso.host");
  int port=conf.getInt("tso.port",1234);
  max_retries=conf.getInt("tso.max_retries",100);
  retry_delay_ms=conf.getInt("tso.retry_delay_ms",1000);
  if (host == null) {
    throw new IOException("tso.host missing from configuration");
  }
  addr=new InetSocketAddress(host,port);
  connectIfNeeded();
}
 

Example 29

From project PerformanceRegressionTest, under directory /src/main/java/org/neo4j/bench/cases/mixedload/.

Source file: MixedLoadBenchCase.java

  29 
vote

public MixedLoadBenchCase(long timeToRun){
  simpleTasks=new LinkedList<Future<int[]>>();
  bulkTasks=new LinkedList<Future<int[]>>();
  this.timeToRun=timeToRun;
  nodes=new ConcurrentLinkedQueue<Node>();
  readTasksExecuted=0;
  writeTasksExecuted=0;
}
 

Example 30

From project PocketMonstersOnline, under directory /Client/src/org/pokenet/client/ui/.

Source file: NotificationManager.java

  29 
vote

/** 
 * Starts the notification manager
 */
public void start(){
  m_notifications=new ConcurrentLinkedQueue<Notification>();
  m_isRunning=true;
  m_thread=new Thread(this);
  m_thread.start();
}
 

Example 31

From project Red5, under directory /src/org/red5/server/so/.

Source file: SharedObjectMessage.java

  29 
vote

@SuppressWarnings({"unchecked"}) @Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
  super.readExternal(in);
  name=(String)in.readObject();
  version=in.readInt();
  persistent=in.readBoolean();
  Object o=in.readObject();
  if (o != null && o instanceof ConcurrentLinkedQueue) {
    events=(ConcurrentLinkedQueue<ISharedObjectEvent>)o;
  }
}
 

Example 32

From project red5-mavenized, under directory /red5_base/src/main/java/org/red5/server/so/.

Source file: SharedObject.java

  29 
vote

/** 
 * Send update notification over data channel of RTMP connection
 */
protected void sendUpdates(){
  int currentVersion=version.get();
  boolean persist=isPersistentObject();
  ConcurrentLinkedQueue<ISharedObjectEvent> events=new ConcurrentLinkedQueue<ISharedObjectEvent>(ownerMessage.getEvents());
  ownerMessage.getEvents().clear();
  if (!events.isEmpty()) {
    SharedObjectMessage syncOwner=new SharedObjectMessage(null,name,currentVersion,persist);
    syncOwner.addEvents(events);
    if (source != null) {
      Channel channel=((RTMPConnection)source).getChannel((byte)3);
      if (channel != null) {
        channel.write(syncOwner);
        log.debug("Owner: {}",channel);
      }
 else {
        log.warn("No channel found for owner changes!?");
      }
    }
  }
  events.clear();
  events.addAll(syncEvents);
  syncEvents.clear();
  if (!events.isEmpty()) {
    for (    IEventListener listener : listeners) {
      if (listener == source) {
        log.debug("Skipped {}",source);
        continue;
      }
      if (!(listener instanceof RTMPConnection)) {
        log.warn("Can't send sync message to unknown connection {}",listener);
        continue;
      }
      SharedObjectMessage syncMessage=new SharedObjectMessage(null,name,currentVersion,persist);
      syncMessage.addEvents(events);
      Channel channel=((RTMPConnection)listener).getChannel((byte)3);
      log.debug("Send to {}",channel);
      channel.write(syncMessage);
    }
  }
}
 

Example 33

From project red5-server, under directory /src/org/red5/server/so/.

Source file: SharedObjectMessage.java

  29 
vote

@SuppressWarnings({"unchecked"}) @Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
  super.readExternal(in);
  name=(String)in.readObject();
  version=in.readInt();
  persistent=in.readBoolean();
  Object o=in.readObject();
  if (o != null && o instanceof ConcurrentLinkedQueue) {
    events=(ConcurrentLinkedQueue<ISharedObjectEvent>)o;
  }
}
 

Example 34

From project riak-hadoop, under directory /src/main/java/com/basho/riak/hadoop/.

Source file: RiakRecordReader.java

  29 
vote

@Override public void initialize(InputSplit split,TaskAttemptContext taskAttemptContext) throws IOException, InterruptedException {
  RiakInputSplit inputSplit=(RiakInputSplit)split;
  keys=new ConcurrentLinkedQueue<BucketKey>(inputSplit.getInputs());
  initialSize=split.getLength();
  client=getRawClient(inputSplit.getLocation());
}
 

Example 35

From project riak-java-client, under directory /src/main/java/com/basho/riak/pbc/.

Source file: RiakConnectionPool.java

  29 
vote

/** 
 * Crate a new host connection pool. NOTE: before using you must call start()
 * @param initialSize the number of connections to create at pool creation time
 * @param clusterSemaphore a  {@link Semaphore} set with the number of permits for thepool (and maybe cluster (see  {@link PoolSemaphore}))
 * @param host the host this pool holds connections to
 * @param port the port on host that this pool holds connections to
 * @param connectionWaitTimeoutMillis the connection timeout
 * @param bufferSizeKb the size of the socket/stream read/write buffers (3 buffers, each of this size)
 * @param idleConnectionTTLMillis How long for an idle connection to exist before it is reaped, 0 mean forever
 * @param requestTimeoutMillis The SO_TIMEOUT flag on the socket; read/write timeout 0 means forever
 * @throws IOException If the initial connection creation throws an IOException
 */
public RiakConnectionPool(int initialSize,Semaphore poolSemaphore,InetAddress host,int port,long connectionWaitTimeoutMillis,int bufferSizeKb,long idleConnectionTTLMillis,int requestTimeoutMillis) throws IOException {
  this.permits=poolSemaphore;
  this.available=new ConcurrentLinkedQueue<RiakConnection>();
  this.inUse=new ConcurrentLinkedQueue<RiakConnection>();
  this.bufferSizeKb=bufferSizeKb;
  this.host=host;
  this.port=port;
  this.connectionWaitTimeoutNanos=TimeUnit.NANOSECONDS.convert(connectionWaitTimeoutMillis,TimeUnit.MILLISECONDS);
  this.requestTimeoutMillis=requestTimeoutMillis;
  this.initialSize=initialSize;
  this.idleConnectionTTLNanos=TimeUnit.NANOSECONDS.convert(idleConnectionTTLMillis,TimeUnit.MILLISECONDS);
  this.idleReaper=Executors.newScheduledThreadPool(1);
  this.shutdownExecutor=Executors.newScheduledThreadPool(1);
  this.state=State.CREATED;
  warmUp();
}
 

Example 36

From project seage, under directory /seage-misc/src/main/java/org/seage/thread/.

Source file: TaskRunner.java

  29 
vote

public void runTasks(List<Runnable> taskQueue,int nrOfThreads){
  _taskQueue=new ConcurrentLinkedQueue<Runnable>(taskQueue);
  List<Thread> runnerThreads=new ArrayList<Thread>();
  for (int i=0; i < nrOfThreads; i++) {
    Thread t=new Thread(new RunnerThread());
    runnerThreads.add(t);
    t.start();
  }
  for (int i=0; i < nrOfThreads; i++) {
    try {
      runnerThreads.get(i).join();
    }
 catch (    InterruptedException e) {
      _logger.log(Level.FINER,e.getMessage());
    }
  }
}
 

Example 37

From project shiro, under directory /core/src/main/java/org/apache/shiro/util/.

Source file: SoftHashMap.java

  29 
vote

/** 
 * Creates a new SoftHashMap with the specified retention size. <p/> The retention size (n) is the total number of most recent entries in the map that will be strongly referenced (ie 'retained') to prevent them from being eagerly garbage collected.  That is, the point of a SoftHashMap is to allow the garbage collector to remove as many entries from this map as it desires, but there will always be (n) elements retained after a GC due to the strong references. <p/> Note that in a highly concurrent environments the exact total number of strong references may differ slightly than the actual <code>retentionSize</code> value.  This number is intended to be a best-effort retention low water mark.
 * @param retentionSize the total number of most recent entries in the map that will be strongly referenced(retained), preventing them from being eagerly garbage collected by the JVM.
 */
@SuppressWarnings({"unchecked"}) public SoftHashMap(int retentionSize){
  super();
  RETENTION_SIZE=Math.max(0,retentionSize);
  queue=new ReferenceQueue<V>();
  strongReferencesLock=new ReentrantLock();
  map=new ConcurrentHashMap<K,SoftValue<V,K>>();
  strongReferences=new ConcurrentLinkedQueue<V>();
}
 

Example 38

From project skalli, under directory /org.eclipse.skalli.core.test/src/main/java/org/eclipse/skalli/core/internal/persistence/.

Source file: EntityHelperTest.java

  29 
vote

private void assertCollectionTypes(TestEntityWithVariousCollections entity){
  Assert.assertEquals(ArrayList.class,entity.list.getClass());
  Assert.assertEquals(HashSet.class,entity.set.getClass());
  Assert.assertEquals(TreeSet.class,entity.set1.getClass());
  Assert.assertEquals(HashMap.class,entity.map1.getClass());
  Assert.assertEquals(TreeMap.class,entity.map2.getClass());
  Assert.assertEquals(ArrayList.class,entity.list1.getClass());
  Assert.assertEquals(TreeSet.class,entity.set2.getClass());
  Assert.assertEquals(HashSet.class,entity.set3.getClass());
  Assert.assertEquals(LinkedHashSet.class,entity.set4.getClass());
  Assert.assertEquals(HashMap.class,entity.map3.getClass());
  Assert.assertEquals(Vector.class,entity.vector.getClass());
  Assert.assertEquals(ConcurrentLinkedQueue.class,entity.queue.getClass());
}
 

Example 39

From project snaptree, under directory /src/test/java/jsr166tests/jtreg/util/concurrent/ConcurrentQueues/.

Source file: GCRetention.java

  29 
vote

Collection<Queue<Boolean>> queues(){
  List<Queue<Boolean>> queues=new ArrayList<Queue<Boolean>>();
  queues.add(new ConcurrentLinkedQueue<Boolean>());
  queues.add(new ArrayBlockingQueue<Boolean>(count,false));
  queues.add(new ArrayBlockingQueue<Boolean>(count,true));
  queues.add(new LinkedBlockingQueue<Boolean>());
  queues.add(new LinkedBlockingDeque<Boolean>());
  queues.add(new PriorityBlockingQueue<Boolean>());
  queues.add(new PriorityQueue<Boolean>());
  queues.add(new LinkedList<Boolean>());
  Collections.shuffle(queues);
  return queues;
}
 

Example 40

From project Sparkweave, under directory /spark-core/src/main/java/at/sti2/spark/core/collect/.

Source file: IndexStructure.java

  29 
vote

public IndexStructure(){
  this.subjectIndexing=false;
  this.predicateIndexing=false;
  this.objectIndexing=false;
  this.windowInMillis=0;
  subjectMap=HashMultimap.create();
  predicateMap=HashMultimap.create();
  objectMap=HashMultimap.create();
  tokenList=new ArrayList<Value>();
  expireTokenQueue=new ConcurrentLinkedQueue<TTLEntrySingle<Value>>();
  expireSubjectQueue=new ConcurrentLinkedQueue<TTLEntry<RDFValue,Value>>();
  expirePredicateQueue=new ConcurrentLinkedQueue<TTLEntry<RDFValue,Value>>();
  expireObjectQueue=new ConcurrentLinkedQueue<TTLEntry<RDFValue,Value>>();
}
 

Example 41

From project speech_trainer, under directory /app/src/mixedbit/speechtrainer/controller/.

Source file: AudioBufferAllocator.java

  29 
vote

/** 
 * All audio buffers are allocated during the construction of {@link AudioBufferAllocator}.
 * @param numberOfBuffers
 * @param singleBufferSize
 */
public AudioBufferAllocator(int numberOfBuffers,int singleBufferSize){
  this.numberOfBuffers=numberOfBuffers;
  availableBuffers=new ConcurrentLinkedQueue<AudioBuffer>();
  for (int i=0; i < numberOfBuffers; ++i) {
    availableBuffers.add(new AudioBuffer(singleBufferSize));
  }
}
 

Example 42

From project Spout, under directory /src/main/java/org/spout/engine/util/thread/snapshotable/.

Source file: SnapshotableTripleIntHashMap.java

  29 
vote

public SnapshotableTripleIntHashMap(SnapshotManager manager){
  live=new TInt21TripleObjectHashMap<V>();
  snapshot=new TInt21TripleObjectHashMap<V>();
  unmutableSnapshot=new TUnmodifiableInt21TripleObjectHashMap<V>(snapshot);
  unmutableLive=new TUnmodifiableInt21TripleObjectHashMap<V>(live);
  dirtyQueue=new ConcurrentLinkedQueue<TripleInt>();
  dirtyMap=new ConcurrentHashMap<TripleInt,Boolean>();
  manager.add(this);
}
 

Example 43

From project Switji, under directory /src/main/java/org/jinglenodes/jingle/processor/.

Source file: JingleProcessor.java

  29 
vote

public void init(){
  for (  final CallSession cs : callSessionMapper.getSessions()) {
    if (cs.getPreparations() == null) {
      cs.setPreparations(new ConcurrentLinkedQueue<CallPreparation>());
    }
    if (cs.getProceeds() == null) {
      cs.setProceeds(new ConcurrentLinkedQueue<CallPreparation>());
      cs.getProceeds().addAll(preparations.subList(0,preparations.size()));
    }
  }
}
 

Example 44

From project Tanks_1, under directory /src/org/apache/mina/core/buffer/.

Source file: CachedBufferAllocator.java

  29 
vote

Map<Integer,Queue<CachedBuffer>> newPoolMap(){
  Map<Integer,Queue<CachedBuffer>> poolMap=new HashMap<Integer,Queue<CachedBuffer>>();
  int poolSize=maxPoolSize == 0 ? DEFAULT_MAX_POOL_SIZE : maxPoolSize;
  for (int i=0; i < 31; i++) {
    poolMap.put(1 << i,new ConcurrentLinkedQueue<CachedBuffer>());
  }
  poolMap.put(0,new ConcurrentLinkedQueue<CachedBuffer>());
  poolMap.put(Integer.MAX_VALUE,new ConcurrentLinkedQueue<CachedBuffer>());
  return poolMap;
}
 

Example 45

From project tesb-rt-se, under directory /sam/sam-agent/src/test/java/org/talend/esb/sam/agent/collector/.

Source file: EventCollectorTest.java

  29 
vote

@Test public void testEventCollector() throws InterruptedException {
  Queue<Event> queue=new ConcurrentLinkedQueue<Event>();
  EventCollector eventCollector=new EventCollector();
  eventCollector.setDefaultInterval(500);
  eventCollector.getFilters().add(new StringContentFilter());
  eventCollector.getHandlers().add(new ContentLengthHandler());
  eventCollector.setEventsPerMessageCall(2);
  eventCollector.setQueue(queue);
  TaskExecutor executor=new SyncTaskExecutor();
  eventCollector.setExecutor(executor);
  MockService monitoringService=new MockService();
  eventCollector.setMonitoringServiceClient(monitoringService);
  queue.add(createEvent("1"));
  queue.add(createEvent("2"));
  queue.add(createEvent("3"));
  eventCollector.sendEventsFromQueue();
  eventCollector.sendEventsFromQueue();
  Assert.assertEquals(2,monitoringService.receivedEvents.size());
  List<Event> events0=monitoringService.receivedEvents.get(0);
  Assert.assertEquals(2,events0.size());
  List<Event> events1=monitoringService.receivedEvents.get(1);
  Assert.assertEquals(1,events1.size());
}
 

Example 46

From project TitanChat, under directory /src/main/java/com/titankingdoms/nodinchan/titanchat/processing/.

Source file: ChatProcessor.java

  29 
vote

public ChatProcessor(){
  super("TitanChat Chat Processor");
  this.plugin=TitanChat.getInstance();
  this.chatQueue=new ConcurrentLinkedQueue<ChatPacket>();
  start();
}
 

Example 47

From project ubuntu-packaging-floodlight, under directory /src/main/java/net/floodlightcontroller/counter/.

Source file: ConcurrentCounter.java

  29 
vote

protected void init(Date startDate){
  this.startDate=startDate;
  this.unprocessedCountBuffer=new ConcurrentLinkedQueue<CountAtom>();
  this.counts=new HashMap<DateSpan,CountBuffer>();
  for (  DateSpan ds : DateSpan.values()) {
    CountBuffer cb=new CountBuffer(startDate,ds,MAX_HISTORY.get(ds));
    counts.put(ds,cb);
  }
}
 

Example 48

From project undertow, under directory /core/src/main/java/io/undertow/server/handlers/.

Source file: RequestLimitingHandler.java

  29 
vote

/** 
 * Construct a new instance. The maximum number of concurrent requests must be at least one.  The next handler must not be  {@code null}.
 * @param maximumConcurrentRequests the maximum concurrent requests
 * @param nextHandler the next handler
 */
public RequestLimitingHandler(int maximumConcurrentRequests,HttpHandler nextHandler){
  if (nextHandler == null) {
    throw new IllegalArgumentException("nextHandler is null");
  }
  if (maximumConcurrentRequests < 1) {
    throw new IllegalArgumentException("Maximum concurrent requests must be at least 1");
  }
  state=(maximumConcurrentRequests & 0xFFFFFFFFL) << 32;
  this.nextHandler=nextHandler;
  Queue<QueuedRequest> queue;
  if (linkedTransferQueue == null) {
    queue=new ConcurrentLinkedQueue<QueuedRequest>();
  }
 else {
    try {
      queue=linkedTransferQueue.newInstance();
    }
 catch (    Throwable t) {
      queue=new ConcurrentLinkedQueue<QueuedRequest>();
    }
  }
  this.queue=queue;
}
 

Example 49

From project WaarpR66, under directory /src/main/java/org/waarp/openr66/commander/.

Source file: CommanderNoDb.java

  29 
vote

/** 
 * Prepare requests that will be executed from time to time
 * @param runner
 * @param fromStartup True if call from startup of the server
 */
public CommanderNoDb(InternalRunner runner,boolean fromStartup){
  this.internalConstructor(runner);
  if (fromStartup) {
    ClientRunner.activeRunners=new ConcurrentLinkedQueue<ClientRunner>();
    File directory=new File(Configuration.configuration.baseDirectory + Configuration.configuration.archivePath);
    File[] files=FileUtils.getFiles(directory,new ExtensionFilter(DbTaskRunner.XMLEXTENSION));
    for (    File file : files) {
      String shortname=file.getName();
      String[] info=shortname.split("_");
      if (info.length < 5) {
        continue;
      }
      DbRule rule;
      try {
        rule=new DbRule(null,info[2]);
      }
 catch (      WaarpDatabaseException e) {
        logger.warn("Cannot find the rule named: " + info[2]);
        continue;
      }
      long id=Long.parseLong(info[3]);
      try {
        DbTaskRunner task=new DbTaskRunner(null,null,rule,id,info[0],info[1]);
        UpdatedInfo status=task.getUpdatedInfo();
        if (status == UpdatedInfo.RUNNING || status == UpdatedInfo.INTERRUPTED) {
          task.changeUpdatedInfo(UpdatedInfo.TOSUBMIT);
          task.update();
        }
      }
 catch (      WaarpDatabaseException e) {
        logger.warn("Cannot reload the task named: " + shortname);
        continue;
      }
    }
  }
}
 

Example 50

From project xmemcached, under directory /src/main/java/net/rubyeye/xmemcached/impl/.

Source file: MemcachedConnector.java

  29 
vote

private void addMainSession(Session session){
  InetSocketAddress remoteSocketAddress=session.getRemoteSocketAddress();
  log.warn("Add a session: " + SystemUtils.getRawAddress(remoteSocketAddress) + ":"+ remoteSocketAddress.getPort());
  Queue<Session> sessions=this.sessionMap.get(remoteSocketAddress);
  if (sessions == null) {
    sessions=new ConcurrentLinkedQueue<Session>();
    Queue<Session> oldSessions=this.sessionMap.putIfAbsent(remoteSocketAddress,sessions);
    if (null != oldSessions) {
      sessions=oldSessions;
    }
  }
  if (this.failureMode) {
    Iterator<Session> it=sessions.iterator();
    while (it.hasNext()) {
      Session tmp=it.next();
      if (tmp.isClosed()) {
        it.remove();
        break;
      }
    }
  }
  sessions.offer(session);
  while (sessions.size() > this.connectionPoolSize) {
    Session oldSession=sessions.poll();
    ((MemcachedSession)oldSession).setAllowReconnect(false);
    oldSession.close();
  }
}
 

Example 51

From project xwiki-rendering, under directory /xwiki-rendering-transformations/xwiki-rendering-transformation-linkchecker/src/test/java/org/xwiki/rendering/internal/transformation/linkchecker/.

Source file: LinkCheckThreadTest.java

  29 
vote

@Test public void runWithInitializer() throws Exception {
  final ComponentManager componentManager=getMockery().mock(ComponentManager.class);
  Queue<LinkQueueItem> queue=new ConcurrentLinkedQueue<LinkQueueItem>();
  final LinkCheckerTransformationConfiguration configuration=getMockery().mock(LinkCheckerTransformationConfiguration.class);
  final LinkCheckerThreadInitializer initializer=getMockery().mock(LinkCheckerThreadInitializer.class);
  getMockery().checking(new Expectations(){
{
      oneOf(componentManager).getInstance(LinkStateManager.class);
      will(returnValue(getMockery().mock(LinkStateManager.class)));
      oneOf(componentManager).getInstance(HTTPChecker.class);
      will(returnValue(getMockery().mock(HTTPChecker.class)));
      oneOf(componentManager).getInstance(LinkCheckerTransformationConfiguration.class);
      will(returnValue(configuration));
      oneOf(configuration).getCheckTimeout();
      will(returnValue(3600000L));
      oneOf(componentManager).getInstanceList(LinkCheckerThreadInitializer.class);
      will(returnValue(Arrays.asList(initializer)));
      oneOf(initializer).initialize();
    }
  }
);
  LinkCheckerThread thread=new LinkCheckerThread(componentManager,queue);
  ReflectionUtils.setFieldValue(thread,"shouldStop",true);
  thread.run();
}
 

Example 52

From project zk-service-registry-server, under directory /lib/zk-service-registry-server/zookeeper-3.3.3/src/java/main/org/apache/zookeeper/server/quorum/.

Source file: Leader.java

  29 
vote

/** 
 * This request processor simply maintains the toBeApplied list. For this to work next must be a FinalRequestProcessor and FinalRequestProcessor.processRequest MUST process the request synchronously!
 * @param next a reference to the FinalRequestProcessor
 */
ToBeAppliedRequestProcessor(RequestProcessor next,ConcurrentLinkedQueue<Proposal> toBeApplied){
  if (!(next instanceof FinalRequestProcessor)) {
    throw new RuntimeException(ToBeAppliedRequestProcessor.class.getName() + " must be connected to " + FinalRequestProcessor.class.getName()+ " not "+ next.getClass().getName());
  }
  this.toBeApplied=toBeApplied;
  this.next=next;
}
 

Example 53

From project zoie, under directory /zoie-core/src/main/java/proj/zoie/api/impl/util/.

Source file: MemoryManager.java

  29 
vote

public MemoryManager(Initializer<T> initializer){
  this._initializer=initializer;
  _cleanThread=new Thread(new Runnable(){
    public void run(){
      T buf=null;
      while (true) {
synchronized (MemoryManager.this) {
          try {
            MemoryManager.this.wait(200);
          }
 catch (          InterruptedException e) {
            log.error(e);
          }
        }
        while ((buf=_releaseQueue.poll()) != null) {
          ConcurrentLinkedQueue<WeakReference<T>> queue=_sizeMap.get(_initializer.size(buf));
          _initializer.init(buf);
          queue.offer(new WeakReference<T>(buf));
          _releaseQueueSize.decrementAndGet();
        }
        buf=null;
      }
    }
  }
);
  _cleanThread.setDaemon(true);
  _cleanThread.start();
}