本文整理汇总了Scala中java.util.concurrent.atomic.AtomicLong类的典型用法代码示例。如果您正苦于以下问题:Scala AtomicLong类的具体用法?Scala AtomicLong怎么用?Scala AtomicLong使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了AtomicLong类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Scala代码示例。
示例1: AtomicLongAccumulator
//设置package包名称以及导入依赖的类
package org.hammerlab.spark
import java.util.concurrent.atomic.AtomicLong
import org.apache.spark.util.AccumulatorV2
case class AtomicLongAccumulator(initialValue: Long = 0)
extends AccumulatorV2[Long, Long] {
private var _value = new AtomicLong(initialValue)
override def value: Long = _value.get
override def isZero: Boolean = value == 0
override def copy(): AccumulatorV2[Long, Long] = AtomicLongAccumulator(value)
override def reset(): Unit = _value = new AtomicLong(0)
override def add(v: Long): Unit = _value.addAndGet(v)
override def merge(other: AccumulatorV2[Long, Long]): Unit = add(other.value)
}
开发者ID:hammerlab,项目名称:spark-util,代码行数:18,代码来源:AtomicLongAccumulator.scala
示例2: LazyVar
//设置package包名称以及导入依赖的类
package lazyvar2
import scala.collection.mutable.ArrayBuffer
import java.util.concurrent.locks.ReentrantLock
import java.util.concurrent.atomic.AtomicLong
object LazyVar {
var n = new AtomicLong(0L)
def apply[T](v : T) = new LazyVar[T](v)
}
class LazyVar[T](var value : T) {
val order = LazyVar.n.getAndIncrement
var buffer = ArrayBuffer[T => T]()
val lock = new ReentrantLock()
def force = {
if(buffer.size > 0) {
lock.lock()
for(f <- buffer)
value = f(value)
buffer = ArrayBuffer[T => T]() //clear()
lock.unlock()
}
}
}
开发者ID:utwente-fmt,项目名称:lazy-persistent-trie,代码行数:28,代码来源:LazyVar.scala
示例3: DataUseLogger
//设置package包名称以及导入依赖的类
package se.gigurra.dcs.remote.util
import java.nio.file.{Files, Paths, StandardOpenOption}
import java.util.concurrent.atomic.AtomicLong
import com.twitter.finagle.util.DefaultTimer
import com.twitter.io.Charsets
import com.twitter.util.Duration
import scala.util.Try
import scala.collection.JavaConversions._
case class DataUseLogger(outputFilePath: String, dtFlush: Duration, enabled: Boolean) {
private val atomicDelta = new AtomicLong(0L)
private val path = Paths.get(outputFilePath)
if (enabled) {
DefaultTimer.twitter.schedule(dtFlush) {
val delta = atomicDelta.getAndSet(0)
val prevBytes = Try(Files.readAllLines(path, Charsets.Utf8).head.toLong).getOrElse(0L)
val newVal = ((prevBytes + delta).toString + "\n").getBytes(Charsets.Utf8)
Files.write(path, newVal, StandardOpenOption.WRITE, StandardOpenOption.CREATE)
}
}
def log(nBytes: Long): Unit = {
atomicDelta.addAndGet(nBytes)
}
}
开发者ID:GiGurra,项目名称:dcs-remote2,代码行数:30,代码来源:DataUseLogger.scala
示例4: ServerApp
//设置package包名称以及导入依赖的类
package org.danielwojda.server
import java.util.concurrent.atomic.AtomicLong
import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import akka.http.scaladsl.model._
import akka.http.scaladsl.server.Directives._
import akka.stream.ActorMaterializer
import scala.io.StdIn
object ServerApp extends App{
implicit val system = ActorSystem("server-system")
implicit val materializer = ActorMaterializer()
implicit val executionContext = system.dispatcher
val hostname = java.net.InetAddress.getLocalHost.getHostName
val getHostnameRequestsCounter = new AtomicLong()
val route =
get {
path("hostname") {
getHostnameRequestsCounter.incrementAndGet()
complete(HttpEntity(ContentTypes.`text/html(UTF-8)`, hostname))
} ~
path("counter") {
complete(HttpEntity(ContentTypes.`text/html(UTF-8)`, getHostnameRequestsCounter.get().toString))
}
}
val bindingFuture = Http().bindAndHandle(route, "0.0.0.0", 8080)
println(s"Server online at http://localhost:8080/\nPress RETURN to stop...")
StdIn.readLine() // let it run until user presses return
bindingFuture
.flatMap(_.unbind()) // trigger unbinding from the port
.onComplete(_ => system.terminate()) // and shutdown when done
}
开发者ID:wojda,项目名称:AkkaHttpDnsInvestigation,代码行数:40,代码来源:ServerApp.scala
示例5: SectorRepository
//设置package包名称以及导入依赖的类
package com.stovokor.editor.model.repository
import com.stovokor.editor.model.Sector
import java.util.concurrent.atomic.AtomicLong
import com.stovokor.editor.model.Point
object SectorRepository {
var instance = new SectorRepository()
def apply() = instance
}
class SectorRepository {
var idGenerator = new AtomicLong(0)
var sectors: Map[Long, Sector] = Map()
val index = SectorIndex()
def add(sector: Sector) = {
val id = idGenerator.getAndIncrement
sectors = sectors.updated(id, sector)
index.indexSector(id, sector)
id
}
def update(id: Long, sector: Sector) = {
sectors = sectors.updated(id, sector)
index.indexSector(id, sector)
sector // maybe should return old?
}
def remove(id: Long) = {
val old = sectors(id)
sectors = sectors - id
index.removeSector(id)
old
}
def get(id: Long) = {
sectors(id)
}
def find(point: Point) = {
index.find(point).map(id => (id, () => get(id)))
}
}
开发者ID:jcfandino,项目名称:leveleditor,代码行数:48,代码来源:SectorRepository.scala
示例6: BorderRepository
//设置package包名称以及导入依赖的类
package com.stovokor.editor.model.repository
import com.stovokor.editor.model.Sector
import java.util.concurrent.atomic.AtomicLong
import com.stovokor.editor.model.Border
import com.stovokor.editor.model.Line
import com.stovokor.editor.model.Point
object BorderRepository {
val instance = new BorderRepository()
def apply() = instance
}
class BorderRepository {
var idGenerator = new AtomicLong(0)
var borders: Map[Long, Border] = Map()
def add(border: Border) = {
val id = idGenerator.getAndIncrement
borders = borders.updated(id, border)
// index.indexSector(id, border)
id
}
def update(id: Long, border: Border) = {
borders = borders.updated(id, border)
// index.indexSector(id, border)
border // maybe should return old?
}
def remove(id: Long) = {
val old = borders(id)
borders = borders - id
// index.removeSector(id)
old
}
def get(id: Long) = {
borders(id)
}
def findFrom(sectorId: Long): List[(Long, Border)] = {
find((id, border) => border.sectorA == sectorId) // Only from sectorId
}
def findTo(sectorId: Long): List[(Long, Border)] = {
find((id, border) => border.sectorB == sectorId) // Only to sectorId
}
def find(point: Point): List[(Long, Border)] = {
find((id, border) => border.line.isEnd(point))
}
def find(line: Line): List[(Long, Border)] = {
find((id, border) => border.line == line)
}
def find(filterFunc: (Long, Border) => Boolean) = {
borders.filter(pair => pair match { case (i, s) => filterFunc(i, s) }).toList
}
}
开发者ID:jcfandino,项目名称:leveleditor,代码行数:62,代码来源:BorderRepository.scala
示例7: Id64
//设置package包名称以及导入依赖的类
package utils
import scala.util.Random
import java.security.SecureRandom
import java.util.concurrent.atomic.AtomicLong
import org.joda.time.DateTimeUtils
object Id64 {
val EPOCH = 1288834974657L //Twepoch (4 Nov 2010 01:42:54.657 GMT)
val RANDOM_BIT = 22
val MAX_RANDOM = 1 << RANDOM_BIT
val MAX_TIME = 1L << (63 - RANDOM_BIT)
private val sr = new SecureRandom()
private val counterStart = Random.nextInt(MAX_RANDOM)
private val counter = new AtomicLong(counterStart)
def time() = DateTimeUtils.currentTimeMillis()
def nextAscId() = nextSeqAscId()
def nextDescId() = nextSeqDescId()
def nextSeqAscId(now: Long = time()) =
makeAscId(now, (counter.getAndIncrement % MAX_RANDOM).toInt)
def nextSeqDescId(now: Long = time()) = {
val r = (counterStart - counter.getAndIncrement) % MAX_RANDOM
makeDescId(now, (if (r < 0) r + MAX_RANDOM else r).toInt)
}
def nextPseRandId(make: (Long, Int) => Long = makeAscId, now: Long = time()) =
make(now, Random.nextInt(MAX_RANDOM))
def nextSecRandId(make: (Long, Int) => Long = makeAscId, now: Long = time()) =
make(now, sr.nextInt(MAX_RANDOM))
def parseId(id: Long, descending: Boolean = false): (Long, Int) = {
val ts = id >> RANDOM_BIT
val time = if (descending) MAX_TIME - (ts - EPOCH) else EPOCH + ts
val rand = id & (MAX_RANDOM - 1)
(time, rand.toInt)
}
def makeAscId(now: Long, rnd: Int): Long = {
val sinceEpoch = now - EPOCH
(sinceEpoch << RANDOM_BIT) | rnd
}
def makeDescId(now: Long, rnd: Int): Long = {
val ts = MAX_TIME - (now - EPOCH)
(ts << RANDOM_BIT) | rnd
}
}
开发者ID:FScoward,项目名称:ticketman,代码行数:56,代码来源:Id64.scala
示例8: RequestCalculatorFilter
//设置package包名称以及导入依赖的类
package $package$.filter
import java.util.concurrent.atomic.AtomicLong
import javax.inject.Inject
import akka.stream.Materializer
import play.api.Logger
import play.api.mvc.{Filter, RequestHeader, Result}
import play.api.libs.concurrent.Execution.Implicits._
import scala.concurrent.Future
class RequestCalculatorFilter @Inject()(implicit val mat: Materializer) extends Filter {
private val counter = new AtomicLong(0)
override def apply(f: (RequestHeader) => Future[Result])(rh: RequestHeader): Future[Result] = {
val value = counter.incrementAndGet()
f(rh).map { result =>
Logger.info("Request #" + value)
result
}
}
}
开发者ID:mielientiev,项目名称:play_intro_template.g8,代码行数:25,代码来源:RequestCalculatorFilter.scala
示例9: increaseTimeout
//设置package包名称以及导入依赖的类
package rere.driver.pool.impl
import java.util.concurrent.atomic.AtomicLong
import scala.concurrent.duration.FiniteDuration
trait BackoffStrategy {
def increaseTimeout(): Unit
def resetTimeout(): Unit
def getTimeout(): FiniteDuration
}
class LinearBackoffStrategy(oneStep: FiniteDuration, maxSteps: Long) extends BackoffStrategy {
private val backoffCounter = new AtomicLong(0L)
override def increaseTimeout(): Unit = {
backoffCounter.getAndIncrement()
()
}
override def resetTimeout(): Unit = {
backoffCounter.set(0L)
}
override def getTimeout(): FiniteDuration = {
oneStep * Math.min(backoffCounter.get(), maxSteps)
}
}
开发者ID:pbaun,项目名称:rere,代码行数:29,代码来源:BackoffStrategy.scala
示例10: TransactionGenerator
//设置package包名称以及导入依赖的类
package com.bwsw.sj.transaction.generator.server
import java.io.{DataInputStream, DataOutputStream}
import java.net.Socket
import java.util.concurrent.atomic.{AtomicBoolean, AtomicInteger, AtomicLong}
import com.bwsw.sj.common.utils.TransactionGeneratorLiterals
class TransactionGenerator(socket: Socket, doesServerWork: AtomicBoolean) extends Runnable {
private val counter = new AtomicInteger(0)
private val currentMillis = new AtomicLong(0)
private val inputStream = new DataInputStream(socket.getInputStream)
private val outputStream = new DataOutputStream(socket.getOutputStream)
private val scale = TransactionGeneratorLiterals.scale
override def run(): Unit = {
try {
while (doesServerWork.get()) {
if (isClientAvailable) {
val id = generateID()
send(id)
} else {
close()
return
}
}
} catch {
case ex: Exception =>
close()
}
}
private def isClientAvailable = {
val clientRequestStatus = inputStream.read()
clientRequestStatus != -1
}
private def generateID() = this.synchronized {
val now = System.currentTimeMillis()
if (now - currentMillis.get > 0) {
currentMillis.set(now)
counter.set(0)
}
now * scale + counter.getAndIncrement()
}
private def send(id: Long) {
outputStream.writeLong(id)
}
private def close() = {
inputStream.close()
outputStream.close()
socket.close()
}
}
开发者ID:bwsw,项目名称:sj-platform,代码行数:58,代码来源:TransactionGenerator.scala
示例11: notifyConsumerTransactionCompleted
//设置package包名称以及导入依赖的类
package com.bwsw.tstreamstransactionserver.netty.server.consumerService
import java.util.concurrent.Executors
import java.util.concurrent.atomic.AtomicLong
import com.bwsw.tstreamstransactionserver.netty.server.streamService.StreamCRUD
import com.bwsw.tstreamstransactionserver.rpc.ConsumerTransaction
import scala.concurrent.ExecutionContext
trait ConsumerTransactionStateNotifier {
private implicit lazy val notifierConsumerContext: ExecutionContext = scala.concurrent.ExecutionContext.fromExecutorService(Executors.newSingleThreadExecutor())
private val consumerNotifies = new java.util.concurrent.ConcurrentHashMap[Long, ConsumerTransactionNotification](0)
private lazy val consumerNotifierSeq = new AtomicLong(0L)
final def notifyConsumerTransactionCompleted(onNotificationCompleted: ConsumerTransaction => Boolean, func: => Unit): Long = {
val consumerNotification = new ConsumerTransactionNotification(onNotificationCompleted, scala.concurrent.Promise[Unit]())
val id = consumerNotifierSeq.getAndIncrement()
consumerNotifies.put(id, consumerNotification)
consumerNotification.notificationPromise.future.map{ onCompleteSuccessfully =>
consumerNotifies.remove(id)
func
}
id
}
final def removeConsumerTransactionNotification(id :Long): Boolean = consumerNotifies.remove(id) != null
private[consumerService] final def areThereAnyConsumerNotifies = !consumerNotifies.isEmpty
private[consumerService] final def tryCompleteConsumerNotify: ConsumerTransactionRecord => Unit => Unit = {
consumerTransactionRecord =>
_ =>
consumerNotifies.values().forEach(notify =>
if (notify.notifyOn(consumerTransactionRecord)) notify.notificationPromise.trySuccess(value = Unit))
}
}
private class ConsumerTransactionNotification(val notifyOn: ConsumerTransaction => Boolean,
val notificationPromise: scala.concurrent.Promise[Unit])
开发者ID:bwsw,项目名称:tstreams-transaction-server,代码行数:44,代码来源:ConsumerTransactionStateNotifier.scala
示例12: Batch
//设置package包名称以及导入依赖的类
package com.bwsw.tstreamstransactionserver.netty.server.db.rocks
import java.util.concurrent.atomic.AtomicLong
import org.rocksdb.{ColumnFamilyHandle, TtlDB, WriteBatch, WriteOptions}
class Batch(client: TtlDB, databaseHandlers: Seq[ColumnFamilyHandle], idGenerator: AtomicLong) {
val id: Long = idGenerator.getAndIncrement()
private val batch = new WriteBatch()
def put(index: Int, key: Array[Byte], data: Array[Byte]): Boolean = {
batch.put(databaseHandlers(index), key, data)
true
}
def remove(index: Int, key: Array[Byte]): Unit = batch.remove(databaseHandlers(index), key)
def write(): Boolean = {
val writeOptions = new WriteOptions()
val status = scala.util.Try(client.write(writeOptions, batch)) match {
case scala.util.Success(_) => true
case scala.util.Failure(throwable) =>
throwable.printStackTrace()
false
}
writeOptions.close()
batch.close()
status
}
}
开发者ID:bwsw,项目名称:tstreams-transaction-server,代码行数:31,代码来源:Batch.scala
示例13: OpenTransactionStateNotifier
//设置package包名称以及导入依赖的类
package com.bwsw.tstreamstransactionserver.netty.server.subscriber
import java.util.concurrent.atomic.AtomicLong
import com.bwsw.tstreamstransactionserver.protocol._
import scala.util.Random
final class OpenTransactionStateNotifier(observer: SubscribersObserver,
notifier: SubscriberNotifier
) {
private val uniqueMasterId =
Random.nextInt()
private val counters =
new java.util.concurrent.ConcurrentHashMap[StreamPartitionUnit, AtomicLong]()
def notifySubscribers(stream: Int,
partition: Int,
transactionId: Long,
count: Int,
status: TransactionState.Status,
ttlMs: Long,
authKey: String,
isNotReliable: Boolean
): Unit = {
// 1. manage next counter for (stream, part)
val streamPartitionUnit = StreamPartitionUnit(stream, partition)
val currentCounter = counters.computeIfAbsent(
streamPartitionUnit, _ => new AtomicLong(-1L)
).incrementAndGet()
// 2. create state (open)
val transactionState = new TransactionState(
transactionId,
partition,
uniqueMasterId,
currentCounter,
count,
status,
ttlMs,
isNotReliable,
authKey
)
// 3. send it via notifier to subscribers
observer.addSteamPartition(stream, partition)
val subscribersOpt = observer
.getStreamPartitionSubscribers(stream, partition)
subscribersOpt.foreach(subscribers =>
notifier.broadcast(subscribers, transactionState)
)
}
}
开发者ID:bwsw,项目名称:tstreams-transaction-server,代码行数:55,代码来源:OpenTransactionStateNotifier.scala
示例14: notifyProducerTransactionCompleted
//设置package包名称以及导入依赖的类
package com.bwsw.tstreamstransactionserver.netty.server.transactionMetadataService
import java.util.concurrent.Executors
import java.util.concurrent.atomic.AtomicLong
import com.bwsw.tstreamstransactionserver.netty.server.streamService.StreamCRUD
import com.bwsw.tstreamstransactionserver.rpc.ProducerTransaction
import scala.concurrent.ExecutionContext
trait ProducerTransactionStateNotifier {
private implicit lazy val notifierProducerContext: ExecutionContext = scala.concurrent.ExecutionContext.fromExecutorService(Executors.newSingleThreadExecutor())
private val producerNotifies = new java.util.concurrent.ConcurrentHashMap[Long, ProducerTransactionNotification](0)
private lazy val producerSeq = new AtomicLong(0L)
final def notifyProducerTransactionCompleted(onNotificationCompleted: ProducerTransaction => Boolean, func: => Unit): Long = {
val producerNotification = new ProducerTransactionNotification(onNotificationCompleted, scala.concurrent.Promise[Unit]())
val id = producerSeq.getAndIncrement()
producerNotifies.put(id, producerNotification)
producerNotification.notificationPromise.future.map { onCompleteSuccessfully =>
producerNotifies.remove(id)
func
}
id
}
final def removeProducerTransactionNotification(id: Long): Boolean = producerNotifies.remove(id) != null
private[transactionMetadataService] final def areThereAnyProducerNotifies = !producerNotifies.isEmpty
private[transactionMetadataService] final def tryCompleteProducerNotify: ProducerTransactionRecord => Unit => Unit = { producerTransactionRecord =>
_ =>
producerNotifies.values().forEach(notify =>
if (notify.notifyOn(producerTransactionRecord)) notify.notificationPromise.trySuccess(value = Unit))
}
}
private class ProducerTransactionNotification(val notifyOn: ProducerTransaction => Boolean,
val notificationPromise: scala.concurrent.Promise[Unit])
开发者ID:bwsw,项目名称:tstreams-transaction-server,代码行数:43,代码来源:ProducerTransactionStateNotifier.scala
示例15: makeTradingDecision
//设置package包名称以及导入依赖的类
package highperfscala.free
import java.util.concurrent.atomic.AtomicLong
import java.util.concurrent.locks.LockSupport
trait TradingStrategy {
def makeTradingDecision(e: BboUpdated): Option[Either[Bid, Offer]]
}
class ProductionStrategy(counter: AtomicLong) extends TradingStrategy {
def makeTradingDecision(e: BboUpdated): Option[Either[Bid, Offer]] = {
val c = counter.getAndIncrement()
c % 1000 == 0 match {
case true =>
Thread.sleep(10)
Some(Right(e.offer))
case false =>
LockSupport.parkNanos(20000) // 0.02ms
c % 3 == 0 match {
case true => Some(Left(e.bid))
case false => None
}
}
}
}
开发者ID:PacktPublishing,项目名称:Scala-High-Performance-Programming,代码行数:26,代码来源:tradingStrategies.scala
示例16: ContactDaoMapImpl
//设置package包名称以及导入依赖的类
package cruddysimple
import java.util.concurrent.atomic.AtomicLong
import scala.collection.concurrent.TrieMap
object ContactDaoMapImpl extends ContactDao {
val store = new TrieMap[Long, Contact]()
val idSequence = new AtomicLong(0)
override def getContacts: List[Contact] = store.values.toList
override def getContact(id: Long): Option[Contact] = store.get(id)
override def updateContact(contact: Contact): Option[Contact] = {
if (store.contains(contact.id)) {
store.put(contact.id, contact)
Some(contact)
} else {
None
}
}
override def insertContact(contactForm: ContactForm): Contact = {
val id = idSequence.incrementAndGet()
val contact = Contact(id, contactForm.name, Option(contactForm.surname), Option(contactForm.address), Option(contactForm.email))
store.put(id, contact)
contact
}
}
开发者ID:tomwadeson,项目名称:cruddy-simple,代码行数:32,代码来源:ContactDaoMapImpl.scala
示例17: Importer
//设置package包名称以及导入依赖的类
package org.sarlacc.controllers
import java.io._
import java.util.concurrent.atomic.AtomicLong
import java.time._
import play.api.mvc._
import play.api.libs.json._
import play.api.Logger._
import scala.util.{Try, Failure}
import org.sarlacc.services._
object Importer extends Controller {
DataProcessor.init()
var n = new AtomicLong(0L)
//This is pretty ugly, but I'm doing it this way to avoid allocating any more
//memory than necessary during parsing. A more straightforward approach would simply use
// json formatters to transform the json directly into case classes (which is what
// I'm trying to avoid here)
def ingestData() = Action { request: Request[AnyContent] =>
for {
body <- request.body.asJson
ls <- body.asOpt[JsArray]
values = ls.value
value <- values
ts <- (value \ "timestamp").asOpt[Long].map{x =>
//assuming local zone given. Alternatively UTC would work
val inst = Instant.ofEpochMilli(x)
inst.atZone(ZoneId.systemDefault).toLocalDateTime
}
id <- (value \ "itemId").asOpt[Int]
}{
Try {
DataProcessor.submit(ts, id)
} match {
case Failure(e) =>
val sw = new StringWriter
e.printStackTrace(new PrintWriter(sw))
println(sw.toString)
case _ =>
val x = n.incrementAndGet
if(x % 10000 == 0)
info(s"${LocalDateTime.now().toString} -> $x")
}
}
Ok("Sarlacc consumed the data.")
}
}
开发者ID:ChrisCoffey,项目名称:sarlacc,代码行数:53,代码来源:IngestController.scala
示例18: Id64
//设置package包名称以及导入依赖的类
package util
import scala.util.Random
import java.security.SecureRandom
import java.util.concurrent.atomic.AtomicLong
import org.joda.time.DateTimeUtils
object Id64 {
val EPOCH = 1288834974657L //Twepoch (4 Nov 2010 01:42:54.657 GMT)
val RANDOM_BIT = 22
val MAX_RANDOM = 1 << RANDOM_BIT
val MAX_TIME = 1L << (63 - RANDOM_BIT)
private val sr = new SecureRandom()
private val counterStart = Random.nextInt(MAX_RANDOM)
private val counter = new AtomicLong(counterStart)
def time() = DateTimeUtils.currentTimeMillis()
def nextAscId() = nextSeqAscId()
def nextDescId() = nextSeqDescId()
def nextSeqAscId(now: Long = time()) =
makeAscId(now, (counter.getAndIncrement % MAX_RANDOM).toInt)
def nextSeqDescId(now: Long = time()) = {
val r = (counterStart - counter.getAndIncrement) % MAX_RANDOM
makeDescId(now, (if (r < 0) r + MAX_RANDOM else r).toInt)
}
def nextPseRandId(make: (Long, Int) => Long = makeAscId, now: Long = time()) =
make(now, Random.nextInt(MAX_RANDOM))
def nextSecRandId(make: (Long, Int) => Long = makeAscId, now: Long = time()) =
make(now, sr.nextInt(MAX_RANDOM))
def parseId(id: Long, descending: Boolean = false): (Long, Int) = {
val ts = id >> RANDOM_BIT
val time = if (descending) MAX_TIME - (ts - EPOCH) else EPOCH + ts
val rand = id & (MAX_RANDOM - 1)
(time, rand.toInt)
}
def makeAscId(now: Long, rnd: Int): Long = {
val sinceEpoch = now - EPOCH
(sinceEpoch << RANDOM_BIT) | rnd
}
def makeDescId(now: Long, rnd: Int): Long = {
val ts = MAX_TIME - (now - EPOCH)
(ts << RANDOM_BIT) | rnd
}
}
开发者ID:FScoward,项目名称:billets-en-concert,代码行数:56,代码来源:Id64.scala
示例19: Id64
//设置package包名称以及导入依赖的类
package util
import scala.util.Random
import java.security.SecureRandom
import java.util.concurrent.atomic.AtomicLong
import org.joda.time.DateTimeUtils
object Id64 {
val EPOCH = 1288834974657L //Twepoch (4 Nov 2010 01:42:54.657 GMT)
val RANDOM_BIT = 22
val MAX_RANDOM = 1 << RANDOM_BIT
val MAX_TIME = 1L << (63 - RANDOM_BIT)
private val sr = new SecureRandom()
private val counterStart = Random.nextInt(MAX_RANDOM)
private val counter = new AtomicLong(counterStart)
def time() = DateTimeUtils.currentTimeMillis()
def nextAscId() = nextSeqAscId()
def nextDescId() = nextSeqDescId()
def nextSeqAscId(now: Long = time()) =
makeAscId(now, (counter.getAndIncrement % MAX_RANDOM).toInt)
def nextSeqDescId(now: Long = time()) = {
val r = (counterStart - counter.getAndIncrement) % MAX_RANDOM
makeDescId(now, (if (r < 0) r + MAX_RANDOM else r).toInt)
}
def nextPseRandId(make: (Long,Int) => Long = makeAscId, now: Long = time()) =
make(now, Random.nextInt(MAX_RANDOM))
def nextSecRandId(make: (Long,Int) => Long = makeAscId, now: Long = time()) =
make(now, sr.nextInt(MAX_RANDOM))
def parseId(id: Long, descending: Boolean = false): (Long, Int) = {
val ts = id >> RANDOM_BIT
val time = if (descending) MAX_TIME - (ts - EPOCH) else EPOCH + ts
val rand = id & (MAX_RANDOM - 1)
(time, rand.toInt)
}
def makeAscId(now: Long, rnd: Int): Long = {
val sinceEpoch = now - EPOCH
(sinceEpoch << RANDOM_BIT) | rnd
}
def makeDescId(now: Long, rnd: Int): Long = {
val ts = MAX_TIME - (now - EPOCH)
(ts << RANDOM_BIT) | rnd
}
}
开发者ID:FScoward,项目名称:tuner,代码行数:55,代码来源:Id64.scala
示例20: InMemoryTodoItemRepository
//设置package包名称以及导入依赖的类
package com.tomwadeson.todobackend.persistence
import java.util.concurrent.atomic.AtomicLong
import com.tomwadeson.todobackend.domain.{TodoItem, TodoItemPatchForm, TodoItemPostForm}
import scala.collection.concurrent.TrieMap
class InMemoryTodoItemRepository extends TodoItemRepository {
private val repository = TrieMap[Long, TodoItem]()
private val idSequence = new AtomicLong()
override def getAll: Seq[TodoItem] =
repository.values.toSeq
override def getById(id: Long): Option[TodoItem] =
repository.get(id)
override def create(todoItemForm: TodoItemPostForm): TodoItem = {
val id = idSequence.getAndIncrement
val todoItem = TodoItem(id, todoItemForm)
repository.put(id, todoItem)
todoItem
}
override def delete(id: Long): Unit =
repository.remove(id)
override def deleteAll: Unit =
synchronized {
idSequence.set(0)
repository.clear()
}
override def update(id: Long, todoItemForm: TodoItemPatchForm): Option[TodoItem] = {
val item = repository.get(id).map(_.update(todoItemForm))
item.foreach(repository.update(id, _))
item
}
}
开发者ID:tomwadeson,项目名称:todobackend-http4s,代码行数:42,代码来源:InMemoryTodoItemRepository.scala
注:本文中的java.util.concurrent.atomic.AtomicLong类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论