Java Code Examples for java.util.concurrent.atomic.AtomicLong
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 airlift, under directory /stats/src/main/java/io/airlift/stats/.
Source file: QuantileDigest.java

public long getMin(){ final AtomicLong chosen=new AtomicLong(min); postOrderTraversal(root,new Callback(){ public boolean process( Node node){ if (node.weightedCount >= ZERO_WEIGHT_THRESHOLD) { chosen.set(node.getLowerBound()); return false; } return true; } } ,TraversalOrder.FORWARD); return Math.max(min,chosen.get()); }
Example 2
From project Arecibo, under directory /collector/src/test/java/com/ning/arecibo/collector/persistent/.
Source file: TestTimelineAggregator.java

private void checkSamplesForATimeline(final Integer startTimeMinutesAgo,final Integer endTimeMinutesAgo,final long expectedChunks) throws InterruptedException { final AtomicLong timelineChunkSeen=new AtomicLong(0); timelineDAO.getSamplesByHostIdsAndSampleKindIds(ImmutableList.<Integer>of(hostId),ImmutableList.<Integer>of(minHeapUsedKindId,maxHeapUsedKindId),START_TIME.minusMinutes(startTimeMinutesAgo),START_TIME.minusMinutes(endTimeMinutesAgo),new TimelineChunkConsumer(){ @Override public void processTimelineChunk( final TimelineChunk chunk){ Assert.assertEquals((Integer)chunk.getHostId(),hostId); Assert.assertTrue(chunk.getSampleKindId() == minHeapUsedKindId || chunk.getSampleKindId() == maxHeapUsedKindId); timelineChunkSeen.incrementAndGet(); } } ); Assert.assertEquals(timelineChunkSeen.get(),expectedChunks); }
Example 3
From project awaitility, under directory /awaitility/src/test/java/com/jayway/awaitility/.
Source file: UsingAtomicTest.java

@Test(timeout=2000) public void usingAtomicLongAndTimeout() throws Exception { exception.expect(TimeoutException.class); exception.expectMessage("expected <1L> but was <0> within 200 milliseconds."); AtomicLong atomic=new AtomicLong(0); await().atMost(200,MILLISECONDS).untilAtomic(atomic,equalTo(1L)); }
Example 4
From project cometd, under directory /cometd-java/cometd-java-examples/src/main/java/org/cometd/benchmark/.
Source file: BayeuxLoadServer.java

private void updateLatencies(long begin,long end){ long latency=TimeUnit.MICROSECONDS.toNanos(TimeUnit.NANOSECONDS.toMicros(end - begin)); Atomics.updateMin(minLatency,latency); Atomics.updateMax(maxLatency,latency); totLatency.addAndGet(latency); AtomicLong count=latencies.get(latency); if (count == null) { count=new AtomicLong(); AtomicLong existing=latencies.put(latency,count); if (existing != null) count=existing; } count.incrementAndGet(); }
Example 5
From project hdfs-nfs-proxy, under directory /src/main/java/com/cloudera/hadoop/hdfs/nfs/nfs4/.
Source file: Metrics.java

/** * Create or increment a named counter */ public void incrementMetric(String name,long count){ name=name.toUpperCase(); AtomicLong counter; synchronized (mMetrics) { counter=mMetrics.get(name); if (counter == null) { counter=new AtomicLong(0); mMetrics.put(name,counter); } } counter.addAndGet(count); }
Example 6
From project heritrix3, under directory /engine/src/main/java/org/archive/crawler/reporting/.
Source file: StatisticsTracker.java

/** * Increment a counter for a key in a given HashMap by an arbitrary amount. Used for various aggregate data. The increment amount can be negative. * @param map The HashMap * @param key The key for the counter to be incremented, if it does not exist it will be added (set to equal to <code>increment</code>). If null it will increment the counter "unknown". * @param increment The amount to increment counter related to the <code>key</code>. */ protected static void incrementMapCount(ConcurrentMap<String,AtomicLong> map,String key,long increment){ if (key == null) { key="unknown"; } AtomicLong lw=(AtomicLong)map.get(key); if (lw == null) { lw=new AtomicLong(0); AtomicLong prevVal=map.putIfAbsent(key,lw); if (prevVal != null) { lw=prevVal; } } lw.addAndGet(increment); }
Example 7
From project james-mailbox, under directory /memory/src/main/java/org/apache/james/mailbox/inmemory/mail/.
Source file: InMemoryModSeqProvider.java

private AtomicLong getHighest(Long id){ AtomicLong uid=map.get(id); if (uid == null) { uid=new AtomicLong(0); AtomicLong u=map.putIfAbsent(id,uid); if (u != null) { uid=u; } } return uid; }
Example 8
From project joda-convert, under directory /src/test/java/org/joda/convert/.
Source file: TestJDKStringConverters.java

@Test public void test_AtomicLong(){ JDKStringConverter test=JDKStringConverter.ATOMIC_LONG; AtomicLong obj=new AtomicLong(12); assertEquals(AtomicLong.class,test.getType()); assertEquals("12",test.convertToString(obj)); AtomicLong back=(AtomicLong)test.convertFromString(AtomicLong.class,"12"); assertEquals(12,back.get()); }
Example 9
From project memcached-session-manager, under directory /core/src/main/java/de/javakaffee/web/msm/.
Source file: ReadOnlyRequestsCache.java

private void incrementOrPut(final LRUCache<String,AtomicLong> cache,final String requestURI){ final AtomicLong count=cache.get(requestURI); if (count != null) { count.incrementAndGet(); } else { cache.put(requestURI,new AtomicLong(1)); } }
Example 10
From project Metamorphosis, under directory /metamorphosis-server/src/test/java/com/taobao/metamorphosis/server/utils/.
Source file: SystemTimerUnitTest.java

private static long testSystem(){ final AtomicLong result=new AtomicLong(0); final ConcurrentTestCase testCase=new ConcurrentTestCase(50,400000,new ConcurrentTestTask(){ public void run( final int index, final int times) throws Exception { result.addAndGet(System.currentTimeMillis()); } } ); testCase.start(); System.out.println("System:" + result.get()); return testCase.getDurationInMillis(); }
Example 11
From project netty, under directory /transport/src/test/java/io/netty/channel/.
Source file: SingleThreadEventLoopTest.java

@Test public void scheduleTask() throws Exception { long startTime=System.nanoTime(); final AtomicLong endTime=new AtomicLong(); loop.schedule(new Runnable(){ @Override public void run(){ endTime.set(System.nanoTime()); } } ,500,TimeUnit.MILLISECONDS).get(); assertTrue(endTime.get() - startTime >= TimeUnit.MILLISECONDS.toNanos(500)); }
Example 12
From project platform_3, under directory /stats/src/main/java/com/proofpoint/stats/.
Source file: QuantileDigest.java

public long getMin(){ final AtomicLong chosen=new AtomicLong(min); postOrderTraversal(root,new Callback(){ public boolean process( Node node){ if (node.weightedCount >= ZERO_WEIGHT_THRESHOLD) { chosen.set(node.getLowerBound()); return false; } return true; } } ,TraversalOrder.FORWARD); return Math.max(min,chosen.get()); }
Example 13
From project psl, under directory /psl-core/src/main/java/edu/umd/cs/psl/evaluation/process/local/.
Source file: LocalProcess.java

@Override public long incrementLong(String key,long inc){ Object o=values.get(key); AtomicLong d=null; if (o == null) { values.putIfAbsent(key,new AtomicLong()); d=(AtomicLong)values.get(key); } else d=(AtomicLong)o; return d.addAndGet(inc); }
Example 14
From project teatrove, under directory /teaservlet/src/main/java/org/teatrove/teaservlet/management/.
Source file: HttpContextManagement.java

public String[] listRequestedUrls(){ ArrayList result=new ArrayList(); Set urlKeySet=__UrlMap.keySet(); for (Iterator it=urlKeySet.iterator(); it.hasNext(); ) { String url=(String)it.next(); AtomicLong count=(AtomicLong)__UrlMap.get(url); String displayString=url + " : " + count.toString(); result.add(displayString); } return (String[])result.toArray(new String[result.size()]); }
Example 15
From project turmeric-releng, under directory /utils/TurmericUtils/src/org/ebayopensource/turmeric/utils/cache/.
Source file: AbstractCache.java

/** * @param key */ private AtomicLong putHitStatsIfAbsent(K key,long l){ AtomicLong statObj=this.hitStats.get(key); if (statObj == null) { statObj=new AtomicLong(l); this.hitStats.put(key,statObj); return statObj; } return statObj; }
Example 16
From project vert.x, under directory /vertx-testsuite/src/test/java/vertx/tests/core/timer/.
Source file: TestClient.java

public void testOneOff() throws Exception { final AtomicLong id=new AtomicLong(-1); id.set(vertx.setTimer(1,new Handler<Long>(){ int count; public void handle( Long timerID){ tu.checkContext(); tu.azzert(id.get() == timerID.longValue()); tu.azzert(count == 0); count++; setEndTimer(); } } )); }
Example 17
From project zoie, under directory /zoie-jms/src/test/java/proj/zoie/dataprovider/jms/.
Source file: TestJMSStreamDataProvider.java

@Before public void setUpJMSStreamDataProvider() throws JMSException { final AtomicLong v=new AtomicLong(0); when(dataEventBuilder.buildDataEvent(any(Message.class))).thenAnswer(new Answer<DataEvent<Object>>(){ @Override public DataEvent<Object> answer( InvocationOnMock invocation) throws Throwable { return new DataEvent<Object>(new Object(),String.valueOf(v.incrementAndGet())); } } ); provider=new JMSStreamDataProvider<Object>("topic","clientID",connectionFactory,topicFactory,dataEventBuilder,ZoieConfig.DEFAULT_VERSION_COMPARATOR); }
Example 18
From project agraph-java-client, under directory /src/test/pool/.
Source file: AGConnPoolSessionTest.java

@Test @Category(TestSuites.Stress.class) public void maxActive() throws Exception { final int seconds=5; final int clients=4; final AGConnPool pool=closeLater(AGConnPool.create(AGConnProp.serverUrl,AGAbstractTest.findServerUrl(),AGConnProp.username,AGAbstractTest.username(),AGConnProp.password,AGAbstractTest.password(),AGConnProp.catalog,"/",AGConnProp.repository,"pool.maxActive",AGConnProp.session,AGConnProp.Session.DEDICATED,AGConnProp.sessionLifetime,seconds * clients * 2,AGConnProp.httpSocketTimeout,TimeUnit.SECONDS.toMillis(seconds * clients),AGPoolProp.shutdownHook,true,AGPoolProp.testOnBorrow,true,AGPoolProp.maxActive,2,AGPoolProp.maxWait,TimeUnit.SECONDS.toMillis((seconds * clients) + 10),AGPoolProp.maxIdle,8)); ExecutorService exec=Executors.newFixedThreadPool(clients); List<Future<Boolean>> errors=new ArrayList<Future<Boolean>>(clients); final AtomicLong idx=new AtomicLong(0); for (int i=0; i < clients; i++) { errors.add(exec.submit(new Callable<Boolean>(){ @Override public Boolean call() throws Exception { try { long id=idx.incrementAndGet(); log.debug(id + " start"); AGRepositoryConnection conn=pool.borrowConnection(); try { log.debug(id + " open"); conn.size(); Thread.sleep(TimeUnit.SECONDS.toMillis(seconds)); conn.size(); } finally { conn.close(); log.debug(id + " close"); } return true; } catch ( Throwable e) { log.error("error " + this,e); return false; } } } )); } assertSuccess(errors,seconds * clients * 2,TimeUnit.SECONDS); }
Example 19
From project asterisk-java, under directory /src/main/java/org/asteriskjava/live/internal/.
Source file: AsteriskServerImpl.java

/** * Creates a new instance. */ public AsteriskServerImpl(){ connectionPool=new ManagerConnectionPool(1); idCounter=new AtomicLong(); listeners=new ArrayList<AsteriskServerListener>(); originateCallbacks=new HashMap<String,OriginateCallbackData>(); channelManager=new ChannelManager(this); agentManager=new AgentManager(this); meetMeManager=new MeetMeManager(this,channelManager); queueManager=new QueueManager(this,channelManager); }
Example 20
From project astyanax, under directory /src/test/java/com/netflix/astyanax/recipes/.
Source file: ReverseIndexQueryTest.java

@Test public void testReverseIndex(){ LOG.info("Starting"); final AtomicLong counter=new AtomicLong(); Keyspace keyspace=clusterContext.getEntity().getKeyspace(TEST_KEYSPACE_NAME); ReverseIndexQuery.newQuery(keyspace,CF_DATA,CF_INDEX.getName(),LongSerializer.get()).fromIndexValue(100L).toIndexValue(10000L).withIndexShards(new Shards.StringShardBuilder().setPrefix("B_").setShardCount(SHARD_COUNT).build()).withColumnSlice(Arrays.asList("A")).forEach(new Function<Row<Long,String>,Void>(){ @Override public Void apply( Row<Long,String> row){ StringBuilder sb=new StringBuilder(); for ( Column<String> column : row.getColumns()) { sb.append(column.getName()).append(", "); } counter.incrementAndGet(); LOG.info("Row: " + row.getKey() + " Columns: "+ sb.toString()); return null; } } ).forEachIndexEntry(new IndexEntryCallback<Long,Long>(){ @Override public boolean handleEntry( Long key, Long value, ByteBuffer meta){ LOG.info("Row : " + key + " IndexValue: "+ value+ " Meta: "+ LongSerializer.get().fromByteBuffer(meta)); if (key % 2 == 1) return false; return true; } } ).execute(); LOG.info("Read " + counter.get() + " rows"); }
Example 21
From project avro, under directory /lang/java/ipc/src/test/java/org/apache/avro/ipc/.
Source file: TestNettyServerWithCallbacks.java

@Ignore @Test public void performanceTest() throws Exception { final int threadCount=8; final long runTimeMillis=10 * 1000L; ExecutorService threadPool=Executors.newFixedThreadPool(threadCount); System.out.println("Running performance test for " + runTimeMillis + "ms..."); final AtomicLong rpcCount=new AtomicLong(0L); final AtomicBoolean runFlag=new AtomicBoolean(true); final CountDownLatch startLatch=new CountDownLatch(threadCount); for (int ii=0; ii < threadCount; ii++) { threadPool.submit(new Runnable(){ @Override public void run(){ try { startLatch.countDown(); startLatch.await(2,TimeUnit.SECONDS); while (runFlag.get()) { rpcCount.incrementAndGet(); Assert.assertEquals("Hello, World!",simpleClient.hello("World!")); } } catch ( Exception e) { e.printStackTrace(); } } } ); } startLatch.await(2,TimeUnit.SECONDS); Thread.sleep(runTimeMillis); runFlag.set(false); threadPool.shutdown(); Assert.assertTrue("Timed out shutting down thread pool",threadPool.awaitTermination(2,TimeUnit.SECONDS)); System.out.println("Completed " + rpcCount.get() + " RPCs in "+ runTimeMillis+ "ms => "+ (((double)rpcCount.get() / (double)runTimeMillis) * 1000)+ " RPCs/sec, "+ ((double)runTimeMillis / (double)rpcCount.get())+ " ms/RPC."); }
Example 22
From project azkaban, under directory /azkaban/src/java/azkaban/flow/.
Source file: ImmutableFlowManager.java

public ImmutableFlowManager(Map<String,Flow> flowMap,Set<String> rootFlows,Map<String,List<String>> folderToRoot,FlowExecutionSerializer serializer,FlowExecutionDeserializer deserializer,File storageDirectory,long lastId){ this.folderToRoot=folderToRoot; this.flowsMap=flowMap; this.rootFlowNames=rootFlows; this.serializer=serializer; this.deserializer=deserializer; this.storageDirectory=storageDirectory; this.lastId=new AtomicLong(lastId); this.jsonToJava=new JSONToJava(); }
Example 23
From project beintoo-android-sdk, under directory /BeintooSDK/src/com/beintoo/main/managers/.
Source file: PlayerManager.java

public void logout(Context ctx){ try { PreferencesHandler.saveBool("isLogged",false,ctx); Beintoo.LAST_LOGIN=new AtomicLong(0); String guid=Current.getCurrentPlayer(ctx).getGuid(); String key=guid + ":count"; PreferencesHandler.clearPref(key,ctx); PreferencesHandler.clearPref("currentPlayer",ctx); PreferencesHandler.clearPref("SubmitScoresCount",ctx); } catch ( Exception e) { e.printStackTrace(); } }
Example 24
From project bitcask-java, under directory /src/main/java/com/trifork/bitcask/.
Source file: BitCaskFile.java

private BitCaskFile(int file_id,File filename,FileChannel wch,FileChannel wch_hint,FileChannel rch) throws IOException { this.file_id=file_id; this.filename=filename; this.wch=wch; this.rch=rch; this.wch_hint=wch_hint; this.write_offset=new AtomicLong(rch.size()); }
Example 25
From project cloudhopper-smpp, under directory /src/main/java/com/cloudhopper/smpp/util/.
Source file: ConcurrentCommandCounter.java

public ConcurrentCommandCounter(){ this.request=new AtomicInteger(0); this.requestExpired=new AtomicInteger(0); this.requestWaitTime=new AtomicLong(0); this.requestResponseTime=new AtomicLong(0); this.requestEstimatedProcessingTime=new AtomicLong(0); this.response=new AtomicInteger(0); this.responseCommandStatusCounter=new ConcurrentCommandStatusCounter(); }
Example 26
From project commons-j, under directory /src/main/java/nerds/antelax/commons/stat/.
Source file: SimpleStatistic.java

public SimpleStatistic(final String name){ Preconditions.checkNotNull(name,"Statistic name must be set"); this.name=name; sampleCount=new AtomicLong(); minimum=new AtomicLong(); maximum=new AtomicLong(); sum=new AtomicLong(); }
Example 27
From project curator, under directory /curator-framework/src/test/java/com/netflix/curator/framework/imps/.
Source file: TestFrameworkBackground.java

@Test public void testRetries() throws Exception { final int SLEEP=1000; final int TIMES=5; Timing timing=new Timing(); CuratorFramework client=CuratorFrameworkFactory.newClient(server.getConnectString(),timing.session(),timing.connection(),new RetryNTimes(TIMES,SLEEP)); try { client.start(); client.getZookeeperClient().blockUntilConnectedOrTimedOut(); final CountDownLatch latch=new CountDownLatch(TIMES); final List<Long> times=Lists.newArrayList(); final AtomicLong start=new AtomicLong(System.currentTimeMillis()); ((CuratorFrameworkImpl)client).debugListener=new CuratorFrameworkImpl.DebugBackgroundListener(){ @Override public void listen( OperationAndData<?> data){ if (data.getOperation().getClass().getName().contains("CreateBuilderImpl")) { long now=System.currentTimeMillis(); times.add(now - start.get()); start.set(now); latch.countDown(); } } } ; server.stop(); client.create().inBackground().forPath("/one"); latch.await(); for ( long elapsed : times.subList(1,times.size())) { Assert.assertTrue(elapsed >= SLEEP,elapsed + ": " + times); } } finally { Closeables.closeQuietly(client); } }
Example 28
From project Dempsy, under directory /lib-dempsyimpl/src/main/java/com/nokia/dempsy/cluster/invm/.
Source file: LocalClusterSessionFactory.java

private String omkdir(String path,DirMode mode) throws ClusterInfoException { Entry parent=null; String pathToUse; synchronized (this) { if (oexists(path,null)) return path; String parentPath=parent(path); parent=entries.get(parentPath); if (parent == null) { throw new ClusterInfoException("No Parent for \"" + path + "\" which is expected to be \""+ parent(path)+ "\""); } long seq=-1; if (mode.isSequential()) { AtomicLong cseq=parent.childSequences.get(path); if (cseq == null) parent.childSequences.put(path,cseq=new AtomicLong(0)); seq=cseq.getAndIncrement(); } pathToUse=seq >= 0 ? (path + seq) : path; entries.put(pathToUse,new Entry()); int lastSlash=pathToUse.lastIndexOf('/'); parent.children.add(pathToUse.substring(lastSlash + 1)); } if (parent != null) parent.callWatchers(false,true); return pathToUse; }
Example 29
From project DeuceSTM, under directory /src/java/org/deuce/transaction/lsacm/.
Source file: Context.java

public Context(){ id=threadID.incrementAndGet(); threads.put(id,this); attempts=0; vr=false; startTime=new AtomicLong(0L); status=new AtomicInteger(TX_IDLE); }
Example 30
From project efflux, under directory /src/main/java/com/biasedbit/efflux/participant/.
Source file: RtpParticipant.java

private RtpParticipant(RtpParticipantInfo info){ this.info=info; this.lastSequenceNumber=-1; this.lastReceptionInstant=0; this.byeReceptionInstant=0; this.receivedByteCounter=new AtomicLong(); this.receivedPacketCounter=new AtomicLong(); this.validPacketCounter=new AtomicInteger(); }
Example 31
From project flume, under directory /flume-ng-core/src/main/java/org/apache/flume/.
Source file: CounterGroup.java

public synchronized AtomicLong getCounter(String name){ if (!counters.containsKey(name)) { counters.put(name,new AtomicLong()); } return counters.get(name); }
Example 32
From project Flume-Hive, under directory /src/java/com/cloudera/flume/reporter/aggregator/.
Source file: CounterSink.java

@Override public void open() throws IOException { Preconditions.checkState(!isOpen); isOpen=true; cnt=new AtomicLong(); LOG.info("CounterSink " + name + " opened"); }
Example 33
From project flume_1, under directory /flume-core/src/main/java/com/cloudera/flume/reporter/aggregator/.
Source file: CounterSink.java

@Override public void open() throws IOException, InterruptedException { Preconditions.checkState(!isOpen); isOpen=true; cnt=new AtomicLong(); LOG.info("CounterSink " + name + " opened"); }
Example 34
From project gatein-toolbox, under directory /sqlman/src/main/java/org/sqlman/.
Source file: LocalStatisticCollector.java

LocalStatisticCollector(ConcurrentStatisticCollector parent,Configuration config){ super(config); this.parent=parent; this.depth=0; this.state=new HashMap<String,Map<Integer,Statistic>>(); this.beginMillis=new AtomicLong(); this.timeMillis=new AtomicLong(); }
Example 35
From project gecko, under directory /src/main/java/com/taobao/gecko/core/util/.
Source file: MyMBeanServer.java

private String getId(final String name,final String idPrefix){ ConcurrentHashMap<String,AtomicLong> subMap=this.idMap.get(name); if (null == subMap) { this.lock.lock(); try { subMap=this.idMap.get(name); if (null == subMap) { subMap=new ConcurrentHashMap<String,AtomicLong>(); this.idMap.put(name,subMap); } } finally { this.lock.unlock(); } } AtomicLong indexValue=subMap.get(idPrefix); if (null == indexValue) { this.lock.lock(); try { indexValue=subMap.get(idPrefix); if (null == indexValue) { indexValue=new AtomicLong(0); subMap.put(idPrefix,indexValue); } } finally { this.lock.unlock(); } } final long value=indexValue.incrementAndGet(); final String result=idPrefix + "-" + value; return result; }
Example 36
From project google-gson, under directory /src/test/java/com/google/gson/.
Source file: GsonTypeAdapterTest.java

public void testTypeAdapterThrowsException() throws Exception { try { gson.toJson(new AtomicLong(0)); fail("Type Adapter should have thrown an exception"); } catch ( IllegalStateException expected) { } try { gson.fromJson("123",AtomicLong.class); fail("Type Adapter should have thrown an exception"); } catch ( JsonParseException expected) { } }
Example 37
From project gson, under directory /gson/src/test/java/com/google/gson/.
Source file: GsonTypeAdapterTest.java

public void testTypeAdapterThrowsException() throws Exception { try { gson.toJson(new AtomicLong(0)); fail("Type Adapter should have thrown an exception"); } catch ( IllegalStateException expected) { } try { gson.fromJson("123",AtomicLong.class); fail("Type Adapter should have thrown an exception"); } catch ( JsonParseException expected) { } }
Example 38
From project hawtdispatch, under directory /hawtdispatch/src/test/java/org/fusesource/hawtdispatch/internal/pool/.
Source file: StealingPool.java

/** * Creates a {@code ForkJoinPool} with the given parallelism . * @param parallelism the parallelism level * @throws IllegalArgumentException if parallelism less than orequal to zero, or greater than implementation limit */ public StealingPool(String name,int parallelism,int priority){ if (parallelism <= 0 || parallelism > MAX_THREADS) throw new IllegalArgumentException(); this.name=name; this.parallelism=parallelism; this.priority=priority; this.workerLock=new ReentrantLock(); this.termination=workerLock.newCondition(); this.stealCount=new AtomicLong(); this.submissionQueue=new LinkedTransferQueue<Task>(); threads=new StealingThread[parallelism]; for (int i=0; i < parallelism; ++i) { threads[i]=createWorker(i); } }
Example 39
From project hitchfs, under directory /hitchfs-test/src/test/java/gs/hitchin/hitchfs/.
Source file: IOFileSystemTest.java

@Test public void test() throws IOException { final AtomicLong currentTime=new AtomicLong(); IOFileSystem fs=new IOFileSystem(){ @Override public long currentTimeMillis(){ return currentTime.get(); } } ; String pathname="file"; fs.file(pathname).withProperty(byteArrayContent()); Writer w=fs.writer(pathname); currentTime.set(12345); String msg="hello, world."; w.write(msg); w.close(); FakeFile f=fs.file(pathname); assertTrue(f.exists()); assertTrue(f.isFile()); assertFalse(f.isDirectory()); assertEquals(12345,f.lastModified()); assertEquals(msg.length(),f.length()); assertTrue(f.canRead()); assertTrue(f.canWrite()); assertTrue(f.canExecute()); char[] buffer=new char[msg.length() + 5]; Reader r=fs.reader(pathname); int len=r.read(buffer); r.close(); assertEquals(msg.length(),len); assertEquals(msg,new String(buffer,0,len)); }
Example 40
From project hoop, under directory /hoop-server/src/main/java/com/cloudera/lib/service/instrumentation/.
Source file: InstrumentationService.java

void init(int size,Variable<Long> variable){ this.variable=variable; values=new long[size]; sum=new AtomicLong(); last=0; }
Example 41
public UidServer(Configuration conf,long value) throws IOException { this.atom=new AtomicLong(value); this.conf=conf; try { String address=conf.get(UID_SERVER_ADDRESS,"0.0.0.0"); int port=conf.getInt(UID_SERVER_PORT,UID_SERVER_PORT_DEFAULT); sleeptime=conf.getInt("uidserver.sleeptime",500); this.server=RPC.getServer(this,address,port,conf.getInt("uidserver.handler.count",10),false,conf); } catch ( IOException e) { throw e; } }
Example 42
From project httpcore, under directory /httpcore-nio/src/examples/org/apache/http/examples/nio/.
Source file: NHttpReverseProxy.java

public ProxyRequestHandler(final HttpHost target,final HttpAsyncRequester executor,final BasicNIOConnPool connPool){ super(); this.target=target; this.executor=executor; this.connPool=connPool; this.counter=new AtomicLong(1); }
Example 43
From project httptunnel, under directory /src/main/java/com/yammer/httptunnel/util/.
Source file: SaturationManager.java

public SaturationManager(long desaturationPoint,long saturationPoint){ this.desaturationPoint=new AtomicLong(desaturationPoint); this.saturationPoint=new AtomicLong(saturationPoint); queueSize=new AtomicLong(0); saturated=new AtomicBoolean(false); }
Example 44
From project ihbase, under directory /src/main/java/org/apache/hadoop/hbase/regionserver/.
Source file: IdxRegion.java

/** * See {@link HRegion#HRegion(org.apache.hadoop.fs.Path,HLog,org.apache.hadoop.fs.FileSystem,org.apache.hadoop.hbase.HBaseConfiguration,org.apache.hadoop.hbase.HRegionInfo,FlushRequester)}. <p/> Initializes the index manager and the expression evaluator. */ public IdxRegion(Path basedir,HLog log,FileSystem fs,HBaseConfiguration conf,HRegionInfo regionInfo,FlushRequester flushListener){ super(basedir,log,fs,conf,regionInfo,flushListener); indexManager=new IdxRegionIndexManager(this); expressionEvaluator=new IdxExpressionEvaluator(); numberOfOngoingIndexedScans=new AtomicInteger(0); totalIndexedScans=new AtomicLong(0); totalNonIndexedScans=new AtomicLong(0); buildTimes=new long[INDEX_BUILD_TIME_HISTORY_SIZE]; resetIndexBuildTimes(); }
Example 45
From project iPage, under directory /src/main/java/com/github/zhongl/api/.
Source file: Ephemerons.java

protected Ephemerons(){ id=new AtomicLong(0L); map=new ConcurrentHashMap<Key,Record>(); flowControl=new Semaphore(0,true); flushing=new AtomicBoolean(false); asyncRemovingService=Executors.newCachedThreadPool(new ThreadFactory(){ @Override public Thread newThread( Runnable r){ Thread thread=new Thread(r,"async-removing"); thread.setDaemon(true); return thread; } } ); }
Example 46
From project iudex_1, under directory /iudex-barc/src/main/java/iudex/barc/.
Source file: BARCFile.java

public BARCFile(File file) throws IOException { file.createNewFile(); _rafile=new RandomAccessFile(file,"rw"); _channel=_rafile.getChannel(); _end=new AtomicLong(_channel.size()); }
Example 47
From project jafka, under directory /src/main/java/com/sohu/jafka/consumer/.
Source file: ZookeeperConsumerConnector.java

/** * @param currentTopicRegistry * @param topicDirs * @param brokerPartition broker-partition format * @param topic * @param consumerThreadId */ private void addPartitionTopicInfo(Pool<String,Pool<Partition,PartitionTopicInfo>> currentTopicRegistry,ZkGroupTopicDirs topicDirs,String brokerPartition,String topic,String consumerThreadId){ Partition partition=Partition.parse(brokerPartition); Pool<Partition,PartitionTopicInfo> partTopicInfoMap=currentTopicRegistry.get(topic); final String znode=topicDirs.consumerOffsetDir + "/" + partition.getName(); String offsetString=ZkUtils.readDataMaybeNull(zkClient,znode); long offset=0L; if (offsetString == null) { if (OffsetRequest.SMALLES_TTIME_STRING.equals(config.getAutoOffsetReset())) { offset=earliestOrLatestOffset(topic,partition.brokerId,partition.partId,OffsetRequest.EARLIES_TTIME); } else if (OffsetRequest.LARGEST_TIME_STRING.equals(config.getAutoOffsetReset())) { offset=earliestOrLatestOffset(topic,partition.brokerId,partition.partId,OffsetRequest.LATES_TTIME); } else { throw new InvalidConfigException("Wrong value in autoOffsetReset in ConsumerConfig"); } } else { offset=Long.parseLong(offsetString); } BlockingQueue<FetchedDataChunk> queue=queues.get(new StringTuple(topic,consumerThreadId)); AtomicLong consumedOffset=new AtomicLong(offset); AtomicLong fetchedOffset=new AtomicLong(offset); PartitionTopicInfo partTopicInfo=new PartitionTopicInfo(topic,partition,queue,consumedOffset,fetchedOffset); partTopicInfoMap.put(partition,partTopicInfo); logger.debug(partTopicInfo + " selected new offset " + offset); }
Example 48
From project jboss-common-beans, under directory /src/main/java/org/jboss/common/beans/property/.
Source file: AtomicLongEditor.java

@Override public void setAsText(final String text){ if (BeanUtils.isNull(text)) { setValue(null); } else { try { setValue(new AtomicLong(Long.decode(text))); } catch ( NumberFormatException e) { throw new IllegalArgumentException("Failed to parse"); } } }
Example 49
From project jena-tdb, under directory /src/main/java/com/hp/hpl/jena/tdb/base/file/.
Source file: BlockAccessBase.java

public BlockAccessBase(String filename,int blockSize){ file=FileBase.create(filename); this.blockSize=blockSize; this.label=FileOps.basename(filename); long filesize=file.size(); long longBlockSize=blockSize; numFileBlocks=filesize / longBlockSize; seq=new AtomicLong(numFileBlocks); if (numFileBlocks > Integer.MAX_VALUE) getLog().warn(format("File size (%d) exceeds tested block number limits (%d)",filesize,blockSize)); if (filesize % longBlockSize != 0) throw new BlockException(format("File size (%d) not a multiple of blocksize (%d)",filesize,blockSize)); if (filesize == 0) isEmpty=true; }
Example 50
From project lilith, under directory /lilith-engine/src/main/java/de/huxhorn/lilith/engine/impl/eventproducer/.
Source file: AbstractMessageBasedEventProducer.java

public AbstractMessageBasedEventProducer(SourceIdentifier sourceIdentifier,AppendOperation<EventWrapper<T>> eventQueue,SourceIdentifierUpdater<T> sourceIdentifierUpdater,InputStream inputStream,boolean compressing){ super(sourceIdentifier,eventQueue,sourceIdentifierUpdater); this.dataInput=new DataInputStream(new BufferedInputStream(inputStream)); this.compressing=compressing; this.decoder=createDecoder(); this.heartbeatTimestamp=new AtomicLong(); }
Example 51
From project moji, under directory /src/main/java/fm/last/moji/tracker/pool/.
Source file: ManagedTrackerHost.java

ManagedTrackerHost(InetSocketAddress address,Timer resetTimer,Clock clock){ lastUsed=new AtomicLong(); lastFailed=new AtomicLong(); hostRetryInterval=1; hostRetryIntervalTimeUnit=MINUTES; this.resetTimer=resetTimer; resetTaskFactory=new ResetTaskFactory(); this.clock=clock; this.address=address; }
Example 52
From project mongodb-examples, under directory /mongo-java-tailable-cursor-example/src/main/com/deftlabs/examples/mongo/.
Source file: TailableCursorExample.java

public static void main(final String[] pArgs) throws Exception { final Mongo mongo=new Mongo(new MongoURI("mongodb://127.0.0.1:27017")); mongo.getDB("testTailableCursor").dropDatabase(); final BasicDBObject conf=new BasicDBObject("capped",true); conf.put("size",20971520); mongo.getDB("testTailableCursor").createCollection("test",conf); final AtomicBoolean readRunning=new AtomicBoolean(true); final AtomicBoolean writeRunning=new AtomicBoolean(true); final AtomicLong writeCounter=new AtomicLong(0); final AtomicLong readCounter=new AtomicLong(0); final ArrayList<Thread> writeThreads=new ArrayList<Thread>(); final ArrayList<Thread> readThreads=new ArrayList<Thread>(); for (int idx=0; idx < 10; idx++) { final Thread writeThread=new Thread(new Writer(mongo,writeRunning,writeCounter)); final Thread readThread=new Thread(new Reader(mongo,readRunning,readCounter)); writeThread.start(); readThread.start(); writeThreads.add(writeThread); readThreads.add(readThread); } Thread.sleep(20000); writeRunning.set(false); Thread.sleep(5000); readRunning.set(false); Thread.sleep(5000); for ( final Thread readThread : readThreads) readThread.interrupt(); for ( final Thread writeThread : writeThreads) writeThread.interrupt(); System.out.println("----- write count: " + writeCounter.get()); System.out.println("----- read count: " + readCounter.get()); }
Example 53
From project narya, under directory /core/src/main/java/com/threerings/presents/peer/server/.
Source file: PeerManager.java

@Override public Stats clone(){ try { Stats cstats=(Stats)super.clone(); cstats.peerMessagesIn=new AtomicLong(peerMessagesIn.get()); return cstats; } catch ( Exception e) { throw new RuntimeException(e); } }
Example 54
From project ning-service-skeleton, under directory /log4j/src/main/java/com/ning/jetty/log4j/.
Source file: LogLevelCounter.java

public LogLevelCounter(){ levelCountsEnabled=new boolean[LevelIndex.values().length]; levelCounts=new AtomicLong[LevelIndex.values().length]; for (int i=0; i < levelCountsEnabled.length; i++) { levelCountsEnabled[i]=i >= LevelIndex.WARN_INDEX.getIndex(); levelCounts[i]=new AtomicLong(0L); } }
Example 55
From project org.openscada.aurora, under directory /org.openscada.utils/src/org/openscada/utils/concurrent/.
Source file: NamedThreadFactory.java

public NamedThreadFactory(final String name,final boolean daemon,final boolean logExceptions){ this.logExceptions=logExceptions; this.counter=new AtomicLong(); this.name=name; this.daemon=daemon; if (name == null) { throw new IllegalArgumentException(String.format("'name' must not be null")); } }
Example 56
From project parasim, under directory /extensions/remote-impl/src/main/java/org/sybila/parasim/extension/remote/impl/.
Source file: RemoteHostActivityImpl.java

public RemoteHostActivityImpl(long time,TimeUnit unit){ Validate.isTrue(time >= 0,"The time can't be a negative number."); Validate.notNull(unit); this.timeout=unit.toMillis(time); this.time=new AtomicLong(this.timeout + System.currentTimeMillis()); }
Example 57
From project rate-limit, under directory /src/main/java/com/eternus/ratelimit/circuitbreaker/.
Source file: CircuitBreakerImpl.java

/** * Creates a new {@link CircuitBreakerImpl} with the specified threshold and timeout. * @param threshold a positive number of failures allowed before this {@link CircuitBreaker} will trip * @param timeout the time in milliseconds needed for this tripped {@link CircuitBreaker} to attempt a reset */ public CircuitBreakerImpl(int threshold,int timeout){ this.threshold=threshold; this.timeout=timeout; this.tripCount=new AtomicLong(); this.listeners=new ArrayList<CircuitBreakerListener>(); this.state=new AtomicReference<CircuitBreakerState>(new ClosedState(threshold)); }
Example 58
From project servicemix-utils, under directory /src/main/java/org/apache/servicemix/executors/impl/.
Source file: ManagedExecutor.java

public ManagedExecutor(String id,ExecutorImpl internalExecutor,ExecutorConfig config) throws javax.management.NotCompliantMBeanException { super(ManagedExecutorMBean.class); this.id=id; this.internalExecutor=internalExecutor; this.config=config; this.rejectedExecutions=new AtomicLong(0L); if (this.internalExecutor != null) { setupWrapper(); } }
Example 59
From project SimianArmy, under directory /src/test/java/com/netflix/simianarmy/basic/.
Source file: TestBasicScheduler.java

@Test public void testRunner() throws InterruptedException { BasicScheduler sched=new TestBasicScheduler(); Monkey mockMonkey=mock(Monkey.class); when(mockMonkey.context()).thenReturn(new TestMonkeyContext(Enums.MONKEY)); when(mockMonkey.type()).thenReturn(Enums.MONKEY).thenReturn(Enums.MONKEY); final AtomicLong counter=new AtomicLong(0L); sched.start(mockMonkey,new Runnable(){ public void run(){ counter.incrementAndGet(); } } ); Thread.sleep(1000); Assert.assertEquals(counter.get(),1); Thread.sleep(2000); Assert.assertEquals(counter.get(),2); sched.stop(mockMonkey); Thread.sleep(2000); Assert.assertEquals(counter.get(),2); }
Example 60
public long deleteDocuments(final String indexName,Query query,final boolean autoCommit) throws CorruptIndexException, IOException { IndexReader reader=new IndexReader(indexName).reopen(); IndexSearcher searcher=new IndexSearcher(reader); final AtomicLong numRemoved=new AtomicLong(0); final ByteBuffer idKey=CassandraUtils.hashKeyBytes(indexName.getBytes("UTF-8"),CassandraUtils.delimeterBytes,"ids".getBytes("UTF-8")); final Map<ByteBuffer,RowMutation> workingMutations=new HashMap<ByteBuffer,RowMutation>(); final RowMutation rm=new RowMutation(CassandraUtils.keySpace,idKey); workingMutations.put(idKey,rm); Collector collector=new Collector(){ @Override public void setScorer( Scorer scorer) throws IOException { } @Override public void setNextReader( org.apache.lucene.index.IndexReader reader, int docBase) throws IOException { } @Override public void collect( int docNumber) throws IOException { deleteLucandraDocument(indexName,docNumber,autoCommit); numRemoved.incrementAndGet(); rm.delete(new QueryPath(CassandraUtils.schemaInfoColumnFamily,ByteBufferUtil.bytes(Integer.toString(docNumber))),System.currentTimeMillis() - 1); } @Override public boolean acceptsDocsOutOfOrder(){ return false; } } ; searcher.search(query,collector); appendMutations(indexName,workingMutations); if (autoCommit) commit(indexName,false); return numRemoved.get(); }
Example 61
From project Spout, under directory /src/main/java/org/spout/engine/scheduler/.
Source file: SpoutParallelTaskManager.java

public SpoutParallelTaskManager(Engine engine){ if (engine == null) { throw new IllegalArgumentException("Engine cannot be set to null"); } upTime=new AtomicLong(0); this.engine=engine; this.world=null; this.scheduler=engine.getScheduler(); }
Example 62
From project streetlights, under directory /streetlights-client-android/simple-xml-2.6.3/test/src/org/simpleframework/xml/transform/.
Source file: DateFormatterTest.java

public void testPerformance() throws Exception { CountDownLatch simpleDateFormatGate=new CountDownLatch(CONCURRENCY); CountDownLatch simpleDateFormatFinisher=new CountDownLatch(CONCURRENCY); AtomicLong simpleDateFormatCount=new AtomicLong(); for (int i=0; i < CONCURRENCY; i++) { new Thread(new SimpleDateFormatTask(simpleDateFormatFinisher,simpleDateFormatGate,simpleDateFormatCount,FORMAT)).start(); } simpleDateFormatFinisher.await(); CountDownLatch synchronizedGate=new CountDownLatch(CONCURRENCY); CountDownLatch synchronizedFinisher=new CountDownLatch(CONCURRENCY); AtomicLong synchronizedCount=new AtomicLong(); SimpleDateFormat format=new SimpleDateFormat(FORMAT); for (int i=0; i < CONCURRENCY; i++) { new Thread(new SynchronizedTask(synchronizedFinisher,synchronizedGate,synchronizedCount,format)).start(); } synchronizedFinisher.await(); CountDownLatch formatterGate=new CountDownLatch(CONCURRENCY); CountDownLatch formatterFinisher=new CountDownLatch(CONCURRENCY); AtomicLong formatterCount=new AtomicLong(); DateFormatter formatter=new DateFormatter(FORMAT,CONCURRENCY); for (int i=0; i < CONCURRENCY; i++) { new Thread(new FormatterTask(formatterFinisher,formatterGate,formatterCount,formatter)).start(); } formatterFinisher.await(); System.err.printf("pool: %s, new: %s, synchronized: %s",formatterCount.get(),simpleDateFormatCount.get(),synchronizedCount.get()); }
Example 63
From project Tanks_1, under directory /src/org/apache/mina/filter/statistic/.
Source file: ProfilerTimerFilter.java

/** * Creates a new instance of TimerWorker. */ public TimerWorker(){ total=new AtomicLong(); callsNumber=new AtomicLong(); minimum=new AtomicLong(); maximum=new AtomicLong(); }
Example 64
From project titanium_modules, under directory /beintoosdk/mobile/android/gson/google-gson-read-only/gson/src/test/java/com/google/gson/.
Source file: GsonTypeAdapterTest.java

public void testTypeAdapterThrowsException() throws Exception { try { gson.toJson(new AtomicLong(0)); fail("Type Adapter should have thrown an exception"); } catch ( IllegalStateException expected) { } try { gson.fromJson("123",AtomicLong.class); fail("Type Adapter should have thrown an exception"); } catch ( JsonParseException expected) { } }
Example 65
From project visural-common, under directory /src/main/java/com/visural/common/cache/impl/.
Source file: CacheStats.java

public CacheStats(long hitCount,long missCount,long loadCount,long totalLoadTime,long evictionCount){ this.hitCount=new AtomicLong(hitCount); this.missCount=new AtomicLong(missCount); this.loadCount=new AtomicLong(loadCount); this.totalLoadTime=new AtomicLong(totalLoadTime); this.evictionCount=new AtomicLong(evictionCount); }
Example 66
From project wissl, under directory /src/main/java/fr/msch/wissl/server/.
Source file: RuntimeStats.java

public RuntimeStats(){ this.uptime=Calendar.getInstance().getTime(); songCount=new AtomicLong(); albumCount=new AtomicLong(); artistCount=new AtomicLong(); playlistCount=new AtomicLong(); userCount=new AtomicLong(); playtime=new AtomicLong(); downloaded=new AtomicLong(); }
Example 67
From project xmemcached, under directory /benchmark/src/net/rubyeye/memcached/benchmark/java_memcached/.
Source file: JavaMemCached.java

public static void test(MemCachedClient memcachedClient,int length,int threads,int repeats,boolean print) throws Exception { memcachedClient.flushAll(); AtomicLong miss=new AtomicLong(0); AtomicLong fail=new AtomicLong(0); AtomicLong hit=new AtomicLong(0); CyclicBarrier barrier=new CyclicBarrier(threads + 1); for (int i=0; i < threads; i++) { new ReadWriteThread(memcachedClient,repeats,barrier,i * repeats,length,miss,fail,hit).start(); } barrier.await(); long start=System.nanoTime(); barrier.await(); if (print) { long duration=System.nanoTime() - start; long total=repeats * threads; printResult(length,threads,repeats,miss,fail,hit,duration,total); } }
Example 68
From project blueprint-namespaces, under directory /blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint/container/.
Source file: AggregateConverter.java

public Object convertToNumber(Number value,Class toType) throws Exception { toType=unwrap(toType); if (AtomicInteger.class == toType) { return new AtomicInteger((Integer)convertToNumber(value,Integer.class)); } else if (AtomicLong.class == toType) { return new AtomicLong((Long)convertToNumber(value,Long.class)); } else if (Integer.class == toType) { return value.intValue(); } else if (Short.class == toType) { return value.shortValue(); } else if (Long.class == toType) { return value.longValue(); } else if (Float.class == toType) { return value.floatValue(); } else if (Double.class == toType) { return value.doubleValue(); } else if (Byte.class == toType) { return value.byteValue(); } else if (BigInteger.class == toType) { return new BigInteger(value.toString()); } else if (BigDecimal.class == toType) { return new BigDecimal(value.toString()); } else { throw new Exception("Unable to convert number " + value + " to "+ toType); } }
Example 69
From project cloudhopper-commons-util, under directory /src/main/java/com/cloudhopper/commons/util/windowing/.
Source file: DefaultWindowFuture.java

/** * Creates a new DefaultWindowFuture. * @param window The window that created this future. Saved as a weakreference to prevent circular references. * @param windowLock The shared lock from the window * @param completedCondition The shared condition to wait on * @param key The key of the future * @param request The request of the future * @param callerStateHint The initial state of the caller hint * @param originalOfferTimeoutMillis * @param windowSize Size of the window after this request was added. Usefulfor calculating an estimated response time for this request rather than all requests ahead of it in the window. * @param offerTimestamp The timestamp when the request was offered * @param acceptTimestamp The timestamp when the request was accepted * @param expireTimestamp The timestamp when the request will expire or -1if no expiration is set */ protected DefaultWindowFuture(Window window,ReentrantLock windowLock,Condition completedCondition,K key,R request,int callerStateHint,long originalOfferTimeoutMillis,int windowSize,long offerTimestamp,long acceptTimestamp,long expireTimestamp){ this.window=new WeakReference<Window>(window); this.windowLock=windowLock; this.completedCondition=completedCondition; this.key=key; this.request=request; this.response=new AtomicReference<P>(); this.cause=new AtomicReference<Throwable>(); this.callerStateHint=new AtomicInteger(callerStateHint); this.done=new AtomicBoolean(false); this.originalOfferTimeoutMillis=originalOfferTimeoutMillis; this.windowSize=windowSize; this.offerTimestamp=offerTimestamp; this.acceptTimestamp=acceptTimestamp; this.expireTimestamp=expireTimestamp; this.doneTimestamp=new AtomicLong(0); }
Example 70
From project enterprise, under directory /com/src/main/java/org/neo4j/com/.
Source file: Server.java

protected ChannelBuffer mapSlave(Channel channel,RequestContext slave,RequestType<T> type){ channelGroup.add(channel); synchronized (connectedSlaveChannels) { if (slave != null && slave.machineId() != RequestContext.EMPTY.machineId()) { Pair<RequestContext,AtomicLong> previous=connectedSlaveChannels.get(channel); if (previous != null) { previous.other().set(System.currentTimeMillis()); } else { connectedSlaveChannels.put(channel,Pair.of(slave,new AtomicLong(System.currentTimeMillis()))); } } } return ChannelBuffers.dynamicBuffer(); }
Example 71
From project griffon, under directory /subprojects/griffon-shell/src/main/groovy/org/apache/felix/gogo/commands/converter/.
Source file: GriffonDefaultConverter.java

public Object convertToNumber(Number value,Class toType) throws Exception { toType=unwrap(toType); if (AtomicInteger.class == toType) { return new AtomicInteger((Integer)convertToNumber(value,Integer.class)); } else if (AtomicLong.class == toType) { return new AtomicLong((Long)convertToNumber(value,Long.class)); } else if (Integer.class == toType) { return value.intValue(); } else if (Short.class == toType) { return value.shortValue(); } else if (Long.class == toType) { return value.longValue(); } else if (Float.class == toType) { return value.floatValue(); } else if (Double.class == toType) { return value.doubleValue(); } else if (Byte.class == toType) { return value.byteValue(); } else if (BigInteger.class == toType) { return new BigInteger(value.toString()); } else if (BigDecimal.class == toType) { return new BigDecimal(value.toString()); } else { throw new Exception("Unable to convert number " + value + " to "+ toType); } }
Example 72
From project Honu, under directory /src/org/honu/datacollection/collector/streaming/.
Source file: ThriftCollectorLockFreeImpl.java

public ThriftCollectorLockFreeImpl() throws Exception { this.counters.put(chunkCountField,new AtomicLong(0L)); Configuration confLocalWriter=HonuConfigurationFactory.getInstance().getCollectorConfiguration(); String honuMode=System.getenv("HONU_MODE"); if (honuMode != null && honuMode.equalsIgnoreCase("debug")) { isDebug=true; } synchronized (lock) { if (writer == null) { writer=new LockFreeWriter("defaultGroup",chunkQueue); writer.init(confLocalWriter); ClientFinalizer clientFinalizer=new ClientFinalizer(writer); Runtime.getRuntime().addShutdownHook(clientFinalizer); isRunning=true; } } }
Example 73
From project human-task-poc-proposal, under directory /executor-service/src/test/java/org/jbpm/executor/.
Source file: BasicExecutorBaseTest.java

@Test public void callbackTest() throws InterruptedException { CommandContext commandContext=new CommandContext(); commandContext.setData("businessKey",UUID.randomUUID().toString()); cachedEntities.put((String)commandContext.getData("businessKey"),new AtomicLong(1)); commandContext.setData("callbacks","SimpleIncrementCallback"); executor.scheduleRequest("PrintOutCmd",commandContext); Thread.sleep(10000); List<RequestInfo> inErrorRequests=executor.getInErrorRequests(); assertEquals(0,inErrorRequests.size()); List<RequestInfo> queuedRequests=executor.getQueuedRequests(); assertEquals(0,queuedRequests.size()); List<RequestInfo> executedRequests=executor.getCompletedRequests(); assertEquals(1,executedRequests.size()); assertEquals(2,((AtomicLong)cachedEntities.get((String)commandContext.getData("businessKey"))).longValue()); }
Example 74
From project IronCount, under directory /src/main/java/com/jointhegrid/ironcount/manager/.
Source file: WorkerThread.java

public WorkerThread(WorkloadManager m,Workload w){ messagesProcessesed=new AtomicLong(0); processingTime=new AtomicLong(0); status=WorkerThreadStatus.NEW; wtId=UUID.randomUUID(); workload=w; goOn=true; this.m=m; executor=Executors.newFixedThreadPool(1); try { zk=new ZooKeeper(m.getProps().getProperty(WorkloadManager.ZK_SERVER_LIST),3000,this); } catch ( IOException ex) { logger.error(ex); throw new RuntimeException(ex); } MBeanServer mbs=ManagementFactory.getPlatformMBeanServer(); try { mbs.registerMBean(this,new ObjectName(MBEAN_OBJECT_NAME + ",uuid=" + wtId)); } catch ( Exception ex) { throw new RuntimeException(ex); } }
Example 75
From project jboss-reflect, under directory /src/main/java/org/jboss/reflect/plugins/.
Source file: SimpleProgressionConvertor.java

public Object doProgression(Class<? extends Object> target,Object value) throws Throwable { if (value == null || target == value.getClass()) { return value; } if (canProgress(target,value.getClass()) == false) { throw new IllegalArgumentException("This convertor only handles Numbers: " + target + "/"+ value); } Number source=(Number)value; if (Byte.class == target || byte.class == target) { return source.byteValue(); } else if (Double.class == target || double.class == target) { return source.doubleValue(); } else if (Float.class == target || float.class == target) { return source.floatValue(); } else if (Integer.class == target || int.class == target) { return source.intValue(); } else if (Long.class == target || long.class == target) { return source.longValue(); } else if (Short.class == target || short.class == target) { return source.shortValue(); } else if (AtomicInteger.class == target) { return new AtomicInteger(source.intValue()); } else if (AtomicLong.class == target) { return new AtomicLong(source.longValue()); } throw new IllegalArgumentException("Unsupported Number subclass: " + target); }
Example 76
From project jetty-project, under directory /jetty-reverse-http/reverse-http-gateway/src/test/java/org/mortbay/jetty/rhttp/gateway/.
Source file: GatewayLoadTest.java

private void updateLatencies(long start,long end){ long latency=end - start; long oldMinLatency=minLatency.get(); while (latency < oldMinLatency) { if (minLatency.compareAndSet(oldMinLatency,latency)) break; oldMinLatency=minLatency.get(); } long oldMaxLatency=maxLatency.get(); while (latency > oldMaxLatency) { if (maxLatency.compareAndSet(oldMaxLatency,latency)) break; oldMaxLatency=maxLatency.get(); } totLatency.addAndGet(latency); latencies.putIfAbsent(latency,new AtomicLong(0L)); latencies.get(latency).incrementAndGet(); }
Example 77
/** * @param period in millis */ public TPS(final long period,boolean autoupdate){ super(); count=new AtomicInteger(0); start=new AtomicLong(0L); this.period=period; this.autoupdate=autoupdate; start.set(System.nanoTime() / FROM_NANOS); if (autoupdate) { timer=new Timer(); timer.schedule(new TimerTask(){ public void run(){ calcTPS(period); } } ,period,period); } }
Example 78
From project karaf, under directory /shell/console/src/main/java/org/apache/karaf/shell/commands/converter/.
Source file: DefaultConverter.java

public Object convertToNumber(Number value,Class toType) throws Exception { toType=unwrap(toType); if (AtomicInteger.class == toType) { return new AtomicInteger((Integer)convertToNumber(value,Integer.class)); } else if (AtomicLong.class == toType) { return new AtomicLong((Long)convertToNumber(value,Long.class)); } else if (Integer.class == toType) { return value.intValue(); } else if (Short.class == toType) { return value.shortValue(); } else if (Long.class == toType) { return value.longValue(); } else if (Float.class == toType) { return value.floatValue(); } else if (Double.class == toType) { return value.doubleValue(); } else if (Byte.class == toType) { return value.byteValue(); } else if (BigInteger.class == toType) { return new BigInteger(value.toString()); } else if (BigDecimal.class == toType) { return new BigDecimal(value.toString()); } else { throw new Exception("Unable to convert number " + value + " to "+ toType); } }
Example 79
From project kryo-serializers, under directory /src/test/java/de/javakaffee/kryoserializers/.
Source file: TestClasses.java

public MyContainer(){ _int=1; _long=2; _boolean=true; _Boolean=Boolean.TRUE; _Class=String.class; _String="3"; _StringBuffer=new StringBuffer("foo"); _StringBuilder=new StringBuilder("foo"); _Long=new Long(4); _Integer=new Integer(5); _Character=new Character('c'); _Byte=new Byte("b".getBytes()[0]); _Double=new Double(6d); _Float=new Float(7f); _Short=new Short((short)8); _BigDecimal=new BigDecimal(9); _AtomicInteger=new AtomicInteger(10); _AtomicLong=new AtomicLong(11); _MutableInt=new MutableInt(12); _IntegerArray=new Integer[]{13}; _Date=new Date(System.currentTimeMillis() - 10000); _Calendar=Calendar.getInstance(); _Currency=Currency.getInstance("EUR"); _ArrayList=new ArrayList<String>(Arrays.asList("foo")); _HashSet=new HashSet<String>(); _HashSet.add("14"); _HashMap=new HashMap<String,Integer>(); _HashMap.put("foo",23); _HashMap.put("bar",42); _intArray=new int[]{1,2}; _longArray=new long[]{1,2}; _shortArray=new short[]{1,2}; _floatArray=new float[]{1,2}; _doubleArray=new double[]{1,2}; _byteArray="42".getBytes(); _charArray="42".toCharArray(); _StringArray=new String[]{"23","42"}; _PersonArray=new Person[]{createPerson("foo bar",Gender.MALE,42)}; }
Example 80
From project org.ops4j.pax.swissbox, under directory /pax-swissbox-converter/src/main/java/org/ops4j/pax/swissbox/converter/java/lang/.
Source file: ToNumberConverter.java

public Object convertToNumber(final Number sourceObject,final Class targetType) throws Exception { final Class type=unwrap(targetType); if (AtomicInteger.class == type) { return new AtomicInteger((Integer)convertToNumber(sourceObject,Integer.class)); } if (AtomicLong.class == type) { return new AtomicLong((Long)convertToNumber(sourceObject,Long.class)); } if (Integer.class == type) { return sourceObject.intValue(); } if (Short.class == type) { return sourceObject.shortValue(); } if (Long.class == type) { return sourceObject.longValue(); } if (Float.class == type) { return sourceObject.floatValue(); } if (Double.class == type) { return sourceObject.doubleValue(); } if (Byte.class == type) { return sourceObject.byteValue(); } if (BigInteger.class == type) { return new BigInteger(sourceObject.toString()); } if (BigDecimal.class == type) { return new BigDecimal(sourceObject.toString()); } throw new Exception(String.format("Unable to convert number %s to %s",sourceObject,type)); }
Example 81
From project serialization, under directory /writer/src/main/java/com/ning/metrics/serialization/writer/.
Source file: DiskSpoolEventWriter.java

public DiskSpoolEventWriter(final EventHandler eventHandler,final String spoolPath,final boolean flushEnabled,final long flushIntervalInSeconds,final ScheduledExecutorService executor,final SyncType syncType,final int syncBatchSize,final CompressionCodec codec,final EventSerializer eventSerializer){ this.eventHandler=eventHandler; this.syncType=syncType; this.syncBatchSize=syncBatchSize; this.spoolDirectory=new File(spoolPath); this.executor=executor; this.tmpSpoolDirectory=new File(spoolDirectory,"_tmp"); this.quarantineDirectory=new File(spoolDirectory,"_quarantine"); this.lockDirectory=new File(spoolDirectory,"_lock"); this.flushEnabled=new AtomicBoolean(flushEnabled); this.flushIntervalInSeconds=new AtomicLong(flushIntervalInSeconds); this.codec=codec; this.eventSerializer=eventSerializer; writeTimerName=new MetricName(DiskSpoolEventWriter.class,spoolPath); writeTimer=Metrics.newTimer(writeTimerName,TimeUnit.MILLISECONDS,TimeUnit.SECONDS); createSpoolDir(spoolDirectory); createSpoolDir(tmpSpoolDirectory); createSpoolDir(quarantineDirectory); createSpoolDir(lockDirectory); if (!spoolDirectory.exists() || !tmpSpoolDirectory.exists() || !quarantineDirectory.exists()|| !lockDirectory.exists()) { throw new IllegalArgumentException("Eventwriter misconfigured - couldn't create the spool directories"); } scheduleFlush(); recoverFiles(); acceptsEvents=true; }
Example 82
From project sulky, under directory /sulky-io/src/main/java/de/huxhorn/sulky/io/.
Source file: TimeoutOutputStream.java

public TimeoutOutputStream(OutputStream stream,int timeout){ watchdogThreadRunning=new AtomicBoolean(false); if (stream == null) { throw new IllegalArgumentException("stream must not be null!"); } if (timeout <= 0) { throw new IllegalArgumentException("timeout must be a positive value!"); } this.stream=stream; this.timeout=timeout; operationStartTime=new AtomicLong(-1); closed=new AtomicBoolean(false); Runnable timeoutRunnable=new TimeoutRunnable(); watchdogThread=new Thread(timeoutRunnable,"TimeoutOutputStream Watchdog-Thread"); watchdogThread.start(); try { Thread.sleep(10); } catch ( InterruptedException e) { Thread.currentThread().interrupt(); } }
Example 83
From project thymeleaf, under directory /src/main/java/org/thymeleaf/cache/.
Source file: StandardCache.java

public StandardCache(final String name,final boolean useSoftReferences,final int initialCapacity,final int maxSize,final ICacheEntryValidityChecker<? super K,? super V> entryValidityChecker,final Logger logger){ super(); Validate.notEmpty(name,"Name cannot be null or empty"); Validate.isTrue(initialCapacity > 0,"Initial capacity must be > 0"); Validate.isTrue(maxSize != 0,"Cache max size must be either -1 (no limit) or > 0"); this.name=name; this.useSoftReferences=useSoftReferences; this.maxSize=maxSize; this.entryValidityChecker=entryValidityChecker; this.logger=logger; this.traceExecution=(logger == null ? false : logger.isTraceEnabled()); this.dataContainer=new CacheDataContainer<K,V>(this.name,initialCapacity,maxSize,this.traceExecution,this.logger); this.getCount=new AtomicLong(0); this.putCount=new AtomicLong(0); this.hitCount=new AtomicLong(0); this.missCount=new AtomicLong(0); if (this.logger != null) { if (this.maxSize < 0) { this.logger.debug("[THYMELEAF][CACHE_INITIALIZE] Initializing cache {}. Soft references {}.",this.name,(this.useSoftReferences ? "are used" : "not used")); } else { this.logger.debug("[THYMELEAF][CACHE_INITIALIZE] Initializing cache {}. Max size: {}. Soft references {}.",new Object[]{this.name,Integer.valueOf(this.maxSize),(this.useSoftReferences ? "are used" : "not used")}); } } }
Example 84
From project AndroidLab, under directory /libs/unboundid/docs/examples/.
Source file: AuthRateThread.java

/** * Creates a new auth rate thread with the provided information. * @param threadNumber The thread number for this thread. * @param searchConnection The connection to use for the searches. * @param bindConnection The connection to use for the binds. * @param baseDN The value pattern to use for the base DNs. * @param scope The scope to use for the searches. * @param filter The value pattern for the filters. * @param attributes The set of attributes to return. * @param userPassword The password to use for the bind operations. * @param authType The type of authentication to perform. * @param startBarrier A barrier used to coordinate starting between allof the threads. * @param authCounter A value that will be used to keep track of thetotal number of authentications performed. * @param authDurations A value that will be used to keep track of thetotal duration for all authentications. * @param errorCounter A value that will be used to keep track of thenumber of errors encountered while searching. * @param rcCounter The result code counter to use for keeping trackof the result codes for failed operations. * @param rateBarrier The barrier to use for controlling the rate ofauthorizations. {@code null} if no rate-limitingshould be used. */ AuthRateThread(final int threadNumber,final LDAPConnection searchConnection,final LDAPConnection bindConnection,final ValuePattern baseDN,final SearchScope scope,final ValuePattern filter,final String[] attributes,final String userPassword,final String authType,final CyclicBarrier startBarrier,final AtomicLong authCounter,final AtomicLong authDurations,final AtomicLong errorCounter,final ResultCodeCounter rcCounter,final FixedRateBarrier rateBarrier){ setName("AuthRate Thread " + threadNumber); setDaemon(true); this.searchConnection=searchConnection; this.bindConnection=bindConnection; this.baseDN=baseDN; this.filter=filter; this.userPassword=userPassword; this.authCounter=authCounter; this.authDurations=authDurations; this.errorCounter=errorCounter; this.rcCounter=rcCounter; this.startBarrier=startBarrier; fixedRateBarrier=rateBarrier; searchConnection.setConnectionName("search-" + threadNumber); bindConnection.setConnectionName("bind-" + threadNumber); if (authType.equalsIgnoreCase("cram-md5")) { this.authType=AUTH_TYPE_CRAM_MD5; } else if (authType.equalsIgnoreCase("digest-md5")) { this.authType=AUTH_TYPE_DIGEST_MD5; } else if (authType.equalsIgnoreCase("plain")) { this.authType=AUTH_TYPE_PLAIN; } else { this.authType=AUTH_TYPE_SIMPLE; } resultCode=new AtomicReference<ResultCode>(null); authThread=new AtomicReference<Thread>(null); stopRequested=new AtomicBoolean(false); searchRequest=new SearchRequest("",scope,Filter.createPresenceFilter("objectClass"),attributes); }
Example 85
From project arquillian-rusheye, under directory /rusheye-impl/src/main/java/org/jboss/rusheye/result/statistics/.
Source file: OverallStatistics.java

@Override public void onSuiteCompleted(){ printerWriter.println(); printerWriter.println("====================="); printerWriter.println(" Overall Statistics:"); for ( Entry<ResultConclusion,AtomicLong> entry : conclusionStatistics.entrySet()) { long count=entry.getValue().get(); if (count > 0) { printerWriter.println(" " + entry.getKey() + ": "+ count); } } printerWriter.println("====================="); printerWriter.flush(); }
Example 86
From project bonecp, under directory /bonecp/src/test/java/com/jolbox/bonecp/.
Source file: TestStatistics.java

/** * @param stats * @throws IllegalAccessException */ private void checkValuesSetToZero(Statistics stats) throws IllegalAccessException { for ( Field field : Statistics.class.getDeclaredFields()) { if (field.getType().equals(AtomicLong.class)) { field.setAccessible(true); assertEquals(0,((AtomicLong)field.get(stats)).get()); } } }
Example 87
private static ThreadFactory createThreadFactory(final String format,final AtomicLong threadPoolCounter){ return new ThreadFactory(){ public Thread newThread( Runnable runnable){ Thread thread=new Thread(runnable); thread.setName(String.format(format,threadPoolCounter.getAndIncrement())); return thread; } } ; }
Example 88
From project disruptor, under directory /src/main/java/com/lmax/disruptor/.
Source file: WorkProcessor.java

/** * Construct a {@link WorkProcessor}. * @param ringBuffer to which events are published. * @param sequenceBarrier on which it is waiting. * @param workHandler is the delegate to which events are dispatched. * @param exceptionHandler to be called back when an error occurs * @param workSequence from which to claim the next event to be worked on. It should always be initialisedas {@link Sequencer#INITIAL_CURSOR_VALUE} */ public WorkProcessor(final RingBuffer<T> ringBuffer,final SequenceBarrier sequenceBarrier,final WorkHandler<T> workHandler,final ExceptionHandler exceptionHandler,final AtomicLong workSequence){ this.ringBuffer=ringBuffer; this.sequenceBarrier=sequenceBarrier; this.workHandler=workHandler; this.exceptionHandler=exceptionHandler; this.workSequence=workSequence; }
Example 89
From project droolsjbpm-integration, under directory /drools-grid/drools-grid-impl/src/test/java/org/drools/io/mina/.
Source file: MinaTest.java

@Test public void test1() throws Exception { SystemEventListener l=SystemEventListenerFactory.getSystemEventListener(); MessageReceiverHandler accHandler=new MessageReceiverHandler(){ private String id; private AtomicLong counter=new AtomicLong(); public void messageReceived( Conversation conversation, Message msgIn){ conversation.respond("echo: " + msgIn.getBody()); } public void exceptionReceived( Conversation conversation, ExceptionMessage msg){ } } ; Acceptor acc=new MinaAcceptor(); acc.open(new InetSocketAddress("127.0.0.1",8000),accHandler,l); ConversationManager cm=new ConversationManagerImpl(new GridImpl("peer"),l); Conversation cv=cm.startConversation("s1",new InetSocketAddress("127.0.0.1",8000),"r1"); BlockingMessageResponseHandler blockHandler=new BlockingMessageResponseHandler(); cv.sendMessage("hello",blockHandler); Message msg=blockHandler.getMessage(100,5000); System.out.println(msg.getBody()); cv.endConversation(); if (acc.isOpen()) { acc.close(); } assertEquals(false,acc.isOpen()); }
Example 90
From project g414-hash, under directory /src/main/java/com/g414/hash/file2/impl/.
Source file: FileOperations2.java

public HashEntry readHashEntry(final DataInputStream input,final AtomicLong pos){ try { int keyLength=0; if (!isAssociative) { keyLength=(int)read(input,header.getKeySize()); pos.addAndGet(header.getKeySize().getSize()); } int dataLength=(int)read(input,header.getValueSize()); pos.addAndGet(header.getValueSize().getSize()); byte[] key=new byte[0]; if (!header.isAssociative()) { key=new byte[keyLength]; input.readFully(key); pos.addAndGet(keyLength); } byte[] data=new byte[dataLength]; input.readFully(data); pos.addAndGet(dataLength); int padding=4 - ((header.getKeySize().getSize() + header.getValueSize().getSize() + keyLength+ dataLength) % 4); if (padding == 4) { padding=0; } input.read(new byte[padding]); pos.addAndGet(padding); return new HashEntry(key,data); } catch ( IOException ioException) { throw new IllegalArgumentException("invalid HashFile format"); } }
Example 91
From project mcore, under directory /src/com/massivecraft/mcore4/xlib/bson/.
Source file: BasicBSONEncoder.java

protected void putNumber(String name,Number n){ if (n instanceof Integer || n instanceof Short || n instanceof Byte|| n instanceof AtomicInteger) { _put(NUMBER_INT,name); _buf.writeInt(n.intValue()); } else if (n instanceof Long || n instanceof AtomicLong) { _put(NUMBER_LONG,name); _buf.writeLong(n.longValue()); } else if (n instanceof Float || n instanceof Double) { _put(NUMBER,name); _buf.writeDouble(n.doubleValue()); } else { throw new IllegalArgumentException("can't serialize " + n.getClass()); } }
Example 92
/** * Gets the type byte for a given object. * @param o the object * @return the byte value associated with the type, or -1 if no type is matched */ @SuppressWarnings("deprecation") public static byte getType(Object o){ if (o == null) return NULL; if (o instanceof DBPointer) return REF; if (o instanceof Integer || o instanceof Short || o instanceof Byte|| o instanceof AtomicInteger) { return NUMBER_INT; } if (o instanceof Long || o instanceof AtomicLong) { return NUMBER_LONG; } if (o instanceof Number) return NUMBER; if (o instanceof String) return STRING; if (o instanceof java.util.List) return ARRAY; if (o instanceof byte[]) return BINARY; if (o instanceof ObjectId) return OID; if (o instanceof Boolean) return BOOLEAN; if (o instanceof java.util.Date) return DATE; if (o instanceof BSONTimestamp) return TIMESTAMP; if (o instanceof java.util.regex.Pattern) return REGEX; if (o instanceof DBObject || o instanceof DBRefBase) return OBJECT; if (o instanceof Code) return CODE; if (o instanceof CodeWScope) return CODE_W_SCOPE; return -1; }
Example 93
From project service-discovery, under directory /client/src/main/java/com/nesscomputing/service/discovery/client/internal/.
Source file: ServiceDiscoveryAnnouncer.java

@Override void determineGeneration(final AtomicLong generation,final long tick){ final long currentAnnouncementGeneration=announcementGeneration.get(); if (lastAnnouncementGeneration < currentAnnouncementGeneration) { generation.incrementAndGet(); lastAnnouncementGeneration=currentAnnouncementGeneration; } }
Example 94
From project spark, under directory /spark-http-client/src/test/java/spark/protocol/.
Source file: SparqlConnections.java

public TestWorker(Runnable task,boolean[] flags,int index,AtomicLong timer,AtomicInteger counter){ this.task=task; this.flags=flags; this.index=index; this.timer=timer; this.counter=counter; flags[index]=false; }
Example 95
From project universal-binary-json-java, under directory /src/main/java/org/ubjson/io/reflect/.
Source file: ObjectWriter.java

protected void writeNumber(UBJOutputStream out,String name,Class<?> type,Number value) throws IOException { if (sstack.peek() != ScopeType.ARRAY) out.writeString(name); if (isAssignable(type,Byte.class)) out.writeByte((Byte)value); else if (isAssignable(type,Short.class)) out.writeInt16((Short)value); else if (isAssignable(type,Integer.class)) out.writeInt32((Integer)value); else if (isAssignable(type,Long.class)) out.writeInt64((Long)value); else if (isAssignable(type,Float.class)) out.writeFloat((Float)value); else if (isAssignable(type,Double.class)) out.writeDouble((Double)value); else if (isAssignable(type,BigInteger.class)) out.writeHuge((BigInteger)value); else if (isAssignable(type,BigDecimal.class)) out.writeHuge((BigDecimal)value); else if (isAssignable(type,AtomicInteger.class)) out.writeInt32(((AtomicInteger)value).get()); else if (isAssignable(type,AtomicLong.class)) out.writeInt64(((AtomicLong)value).get()); else throw new IllegalArgumentException("Unsupported numeric type [" + type + "]"); }
Example 96
From project zk-service-registry-server, under directory /lib/zk-service-registry-server/zookeeper-3.3.3/contrib/bookkeeper/src/java/org/apache/bookkeeper/proto/.
Source file: PerChannelBookieClient.java

public PerChannelBookieClient(OrderedSafeExecutor executor,ClientSocketChannelFactory channelFactory,InetSocketAddress addr,AtomicLong totalBytesOutstanding){ this.addr=addr; this.executor=executor; this.totalBytesOutstanding=totalBytesOutstanding; this.channelFactory=channelFactory; connect(channelFactory); }