List of usage examples for java.util.concurrent ConcurrentLinkedQueue ConcurrentLinkedQueue
public ConcurrentLinkedQueue()
From source file:com.codefollower.lealone.omid.client.TSOClient.java
public TSOClient(Configuration conf) throws IOException { state = State.DISCONNECTED;//from w ww .j a v a 2 s .c om 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; LOG.info("Starting TSOClient"); // Start client with Nb of active threads = 3 as maximum. factory = new NioClientSocketChannelFactory(Executors.newCachedThreadPool(), Executors.newCachedThreadPool(), 3); // Create the bootstrap 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); maxRetries = conf.getInt("tso.max_retries", 100); retryDelayMs = conf.getInt("tso.retry_delay_ms", 1000); if (host == null) { throw new IOException("tso.host missing from configuration"); } addr = new InetSocketAddress(host, port); connectIfNeeded(); }
From source file:com.predic8.membrane.core.interceptor.apimanagement.statistics.AMStatisticsCollector.java
public void addExchangeToQueue(Exchange exc) { String apiKey = (String) exc.getProperty(Exchange.API_KEY); if (apiKey != null) { ConcurrentLinkedQueue<Exchange> exchangeQueue = exchangesForApiKey.get(apiKey); // See SO 3752194 for explanation for this if (exchangeQueue == null) { ConcurrentLinkedQueue<Exchange> newValue = new ConcurrentLinkedQueue<Exchange>(); exchangeQueue = exchangesForApiKey.putIfAbsent(apiKey, newValue); if (exchangeQueue == null) exchangeQueue = newValue; }// w w w. j a v a 2 s .c o m exchangeQueue.add(exc); } }
From source file:de.hybris.platform.jdbcwrapper.ConnectionPoolTest.java
@Test public void testJndiDataSource() throws SQLException { TestUtils.disableFileAnalyzer("log error expected"); final Collection<TestConnectionImpl> allConnections = new ConcurrentLinkedQueue<TestConnectionImpl>(); final AtomicLong connectionCounter = new AtomicLong(0); final HybrisDataSource dataSource = createDataSource(Registry.getCurrentTenantNoFallback(), allConnections, connectionCounter, false, true); final Connection conn = dataSource.getConnection(); conn.close();//from w w w .j av a 2 s . co m // kill data source dataSource.destroy(); assertTrue(dataSource.getConnectionPool().isPoolClosed()); LOG.info("data source destroyed"); TestUtils.enableFileAnalyzer(); }
From source file:oculus.aperture.graph.aggregation.impl.ModularityAggregator.java
@Override public void run() { logger.debug("Running kSnap clustering algorithm on " + nodeMap.size() + " nodes and " + linkMap.size() + " links..."); StopWatch stopWatch = new StopWatch(); stopWatch.start();/*from ww w .ja v a 2 s.c o m*/ HashMap<String, ModularityNode> linklookup = new HashMap<String, ModularityAggregator.ModularityNode>(); for (Node n : nodeMap.values()) { ModularityNode mn = new ModularityNode(n); linklookup.put(n.getId(), mn); groups.add(mn); } links = new ArrayList<ModularityLink>(); for (Link l : linkMap.values()) { if (linklookup.containsKey(l.getSourceId()) && linklookup.containsKey(l.getTargetId())) { //if this is not true we have links pointing to an invalid node... ModularityLink ml = new ModularityLink(linklookup.get(l.getSourceId()), linklookup.get(l.getTargetId())); links.add(ml); ModularityNode start = linklookup.get(l.getSourceId()); ModularityNode end = linklookup.get(l.getSourceId()); start.addLink(ml); end.addLink(ml); } } boolean notterminate = true; int linksize; while (notterminate) { final List<Future<?>> futures = new ArrayList<Future<?>>(); notterminate = false; final PriorityBlockingQueue<ModularityLink> linksort = new PriorityBlockingQueue<ModularityLink>(); linksize = links.size(); final int itrsize = linksize / nThreads; for (int i = 0; i < nThreads; i++) { final int passval = i; Future<?> foo = executor.submit(new Callable<Boolean>() { @Override public Boolean call() throws Exception { boolean nt = false; for (int lnknum = 0; lnknum < itrsize; lnknum++) { ModularityLink ln = links.get(passval * itrsize + lnknum); long nc = 0; if (ln.source.neighbourcounts.containsKey(ln.target)) { nc = ln.source.neighbourcounts.get(ln.target).intValue(); } else { System.out.println("Oooops"); } long q = nc - (ln.source.totalvolume * ln.target.totalvolume) / 2; if (q > 0) nt = true; ln.q.set(q); linksort.add(ln); } return nt; } }); futures.add(foo); } for (Future<?> foo : futures) { try { notterminate = (Boolean) foo.get(); } catch (InterruptedException interruptedCancellingAndSignalling) { Thread.currentThread().interrupt(); } catch (ExecutionException wtf) { wtf.printStackTrace(); } } if (!notterminate) break; //Now we take each link in the queue and add it to maximal matching ConcurrentLinkedQueue<ModularityLink> maximalmatching = new ConcurrentLinkedQueue<ModularityAggregator.ModularityLink>(); ConcurrentSkipListSet<ModularityNode> vertexcheck = new ConcurrentSkipListSet<ModularityAggregator.ModularityNode>(); ModularityLink top = linksort.poll(); maximalmatching.add(top); vertexcheck.add(top.source); vertexcheck.add(top.target); while (!linksort.isEmpty()) { ModularityLink nlnk = linksort.poll(); if (nlnk.q.intValue() < 0) continue; if (vertexcheck.contains(nlnk.source) || vertexcheck.contains(nlnk.target)) continue; maximalmatching.add(nlnk); vertexcheck.add(nlnk.source); vertexcheck.add(nlnk.target); } //Now we take all the pairs in maximal matching and fuse them for (ModularityLink ln : maximalmatching) { ModularityNode so = ln.source; ModularityNode tr = ln.target; so.assimilate(tr); groups.remove(tr); links.remove(ln); } linksize = links.size(); if (linksize == 1) notterminate = false; } /* final List<Future<?>> futures = new ArrayList<Future<?>>(); Future<?> foo = executor.submit(new Runnable(){ @Override public void run() { }}); futures.add(foo); */ clusterSet = new ArrayList<Set<Node>>(); for (ModularityNode g : groups) { if (cancel) { setStatusWaiting(); return; } Set<Node> set = new HashSet<Node>(); clusterSet.add(set); for (Node n : g.nodes) { if (cancel) { setStatusWaiting(); return; } set.add(n); } } if (clusterer != null) { graphResult = clusterer.convertClusterSet(clusterSet); } stopWatch.stop(); System.out.println("Finished Modularity clustering algorithm."); System.out.println("Algorithm took " + stopWatch.toString());//30 = 33.487 stopWatch.reset(); this.result = result; }
From source file:de.da_sense.moses.client.service.MosesService.java
@Override public void onCreate() { super.onCreate(); thisInstance = this; for (HookTypesEnum hookType : HookTypesEnum.values()) { mset.hooks.put(hookType, new ConcurrentLinkedQueue<ExecutableWithType>()); }/*from w w w . j a va 2 s .c om*/ registerHook(HookTypesEnum.POST_LOGIN_FAILED, MessageTypesEnum.SPAMMABLE, new Executable() { @Override public void execute() { mset.loggingIn = false; loggedOut(); } }); if (HistoryExternalApplicationsManager.getInstance() == null) { HistoryExternalApplicationsManager.init(this); } if (InstalledExternalApplicationsManager.getInstance() == null) { InstalledExternalApplicationsManager.init(this); } if (UserstudyNotificationManager.getInstance() == null) { UserstudyNotificationManager.init(this); } if (PreferenceManager.getDefaultSharedPreferences(this).getString(MosesPreferences.PREF_GCM_ID, "") .equals("")) { Log.d(LOG_TAG, "Requesting registration ID."); C2DMManager.requestC2DMId(MosesService.this); } if (PreferenceManager.getDefaultSharedPreferences(this).contains("url_pref")) { mset.url = PreferenceManager.getDefaultSharedPreferences(this).getString("url_pref", ""); } else { PreferenceManager.getDefaultSharedPreferences(this).edit().putString("url_pref", mset.url); } NetworkJSON.url = mset.url; PreferenceManager.getDefaultSharedPreferences(this).registerOnSharedPreferenceChangeListener(this); initConfig(); Log.d("MoSeS.SERVICE", "Service Created"); }
From source file:org.apache.lens.driver.hive.HiveDriver.java
/** * Instantiates a new hive driver./* www. j a va 2s . c o m*/ * * @throws LensException the lens exception */ public HiveDriver() throws LensException { this.sessionLock = new ReentrantLock(); lensToHiveSession = new HashMap<>(); opHandleToSession = new ConcurrentHashMap<>(); orphanedHiveSessions = new ConcurrentLinkedQueue<>(); resourcesAddedForSession = new HashMap<>(); connectionExpiryThread.setDaemon(true); connectionExpiryThread.setName("HiveDriver-ConnectionExpiryThread"); connectionExpiryThread.start(); driverListeners = new ArrayList<LensEventListener<DriverEvent>>(); log.info("Hive driver inited"); }
From source file:LessonSaver.ServerBridge.java
public ServerBridge() { // ? ? ? ? if (new File("frameQueue.dat").exists()) //? ?? ? ? {//from www. j av a2 s .c o m try { FileInputStream FIS = new FileInputStream("frameQueue.dat"); try { ObjectInputStream OIS = new ObjectInputStream(FIS); try { this.frameQueue = (ConcurrentLinkedQueue<ServerBridge.Frame>) OIS.readObject(); } catch (ClassNotFoundException ex) { } OIS.close(); } catch (IOException ex) { } } catch (FileNotFoundException ex) { } } else //? ?? ? { this.frameQueue = new ConcurrentLinkedQueue<>(); } this.bridge = new Bridge(); Thread T = new Thread(this.bridge); T.setDaemon(true); T.start(); }
From source file:de.hybris.platform.jdbcwrapper.ConnectionPoolTest.java
@Test public void testReturnWhenClosed() { HybrisDataSource dataSource = null;/*from w w w . ja va 2 s . c o m*/ TestThreadsHolder threadsHolder = null; try { final Collection<TestConnectionImpl> allConnections = new ConcurrentLinkedQueue<TestConnectionImpl>(); final AtomicLong connectionCounter = new AtomicLong(0); dataSource = createDataSource(Registry.getCurrentTenantNoFallback(), allConnections, connectionCounter, false, false); final int maxConnections = dataSource.getMaxAllowedPhysicalOpen(); final CountDownLatch allFetched = new CountDownLatch(maxConnections); final CountDownLatch release = new CountDownLatch(1); final Runnable runnable = new GetOneConnectionRunnable(dataSource, allFetched, release); threadsHolder = new TestThreadsHolder(maxConnections, runnable); threadsHolder.startAll(); assertTrue(allFetched.await(10, TimeUnit.SECONDS)); LOG.info("all connection fetched"); assertEquals(maxConnections, dataSource.getNumInUse()); assertEquals(maxConnections, dataSource.getNumPhysicalOpen()); assertEquals(maxConnections, dataSource.getMaxInUse()); assertEquals(maxConnections, dataSource.getMaxPhysicalOpen()); // kill data source dataSource.destroy(); assertTrue(dataSource.getConnectionPool().isPoolClosed()); LOG.info("data source destroyed"); // test get error try { dataSource.getConnection(); fail("SQLExcpetion expected after destroy()"); } catch (final SQLException e) { // fine LOG.info("no new connection allowed"); } // check stats again -> should not have changed assertEquals(maxConnections, dataSource.getNumInUse()); assertEquals(maxConnections, dataSource.getNumPhysicalOpen()); assertEquals(maxConnections, dataSource.getMaxInUse()); assertEquals(maxConnections, dataSource.getMaxPhysicalOpen()); // now let all threads return their connections release.countDown(); LOG.info("all threads close connections now..."); threadsHolder.waitForAll(10, TimeUnit.SECONDS); LOG.info("all threads died"); assertTrue(waitForAllInactive(dataSource.getConnectionPool(), 10, TimeUnit.SECONDS)); // check final stats assertEquals(0, dataSource.getNumInUse()); assertEquals(0, dataSource.getNumPhysicalOpen()); assertEquals(maxConnections, dataSource.getMaxInUse()); assertEquals(maxConnections, dataSource.getMaxPhysicalOpen()); final Stats stats = getStats(allConnections); // make sure all connections have been finally closed assertEquals(0, stats.open); } catch (final InterruptedException e) { // ok } finally { stopThreads(threadsHolder); destroyDataSource(dataSource); } }
From source file:org.apache.juddi.replication.ReplicationNotifier.java
public synchronized void run() { log.debug("Replication thread triggered"); if (queue == null) { queue = new ConcurrentLinkedQueue(); }// w w w . j a va2 s. c om if (queue2 == null) { queue2 = new ConcurrentLinkedQueue(); } //TODO revisie this if (!queue.isEmpty()) { log.info("Replication, Notifying nodes of new change records. " + queue.size() + " queued"); } //TODO check for replication config changes while (!queue.isEmpty()) { //for each change at this node ChangeRecord j = queue.poll(); ProcessChangeRecord(j); } while (!queue2.isEmpty()) { //for each change at this node org.uddi.repl_v3.ChangeRecord j = queue2.poll(); ChangeRecord model = new ChangeRecord(); try { model = MappingApiToModel.mapChangeRecord(j); } catch (UnsupportedEncodingException ex) { Logger.getLogger(ReplicationNotifier.class.getName()).log(Level.SEVERE, null, ex); } log.info("retransmitting CR notificationm entity owner: " + j.getChangeID().getNodeID() + " CR: " + j.getChangeID().getOriginatingUSN() + " key:" + model.getEntityKey() + " " + model.getRecordType().name() + " accepted locally:" + model.getIsAppliedLocally()); SendNotifications(j.getChangeID().getOriginatingUSN(), j.getChangeID().getNodeID(), true); } }
From source file:edu.cornell.mannlib.vitro.webapp.rdfservice.impl.jena.RDFServiceJena.java
private List<Statement> sort(List<Statement> stmts) { List<Statement> output = new ArrayList<Statement>(); int originalSize = stmts.size(); if (originalSize == 1) { return stmts; }/*from w w w. j ava 2s .com*/ List<Statement> remaining = stmts; ConcurrentLinkedQueue<Resource> subjQueue = new ConcurrentLinkedQueue<Resource>(); for (Statement stmt : remaining) { if (stmt.getSubject().isURIResource()) { subjQueue.add(stmt.getSubject()); break; } } if (subjQueue.isEmpty()) { log.warn("No named subject in statement patterns"); return stmts; } while (remaining.size() > 0) { if (subjQueue.isEmpty()) { subjQueue.add(remaining.get(0).getSubject()); } while (!subjQueue.isEmpty()) { Resource subj = subjQueue.poll(); List<Statement> temp = new ArrayList<Statement>(); for (Statement stmt : remaining) { if (stmt.getSubject().equals(subj)) { output.add(stmt); if (stmt.getObject().isResource()) { subjQueue.add((Resource) stmt.getObject()); } } else { temp.add(stmt); } } remaining = temp; } } if (output.size() != originalSize) { throw new RuntimeException( "original list size was " + originalSize + " but sorted size is " + output.size()); } return output; }