当前位置: 首页>>代码示例>>Scala>>正文


Scala AtomicLong类代码示例

本文整理汇总了Scala中java.util.concurrent.atomic.AtomicLong的典型用法代码示例。如果您正苦于以下问题:Scala AtomicLong类的具体用法?Scala AtomicLong怎么用?Scala AtomicLong使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了AtomicLong类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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


注:本文中的java.util.concurrent.atomic.AtomicLong类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。