• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Scala ThreadLocalRandom类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



在下文中一共展示了ThreadLocalRandom类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Scala代码示例。

示例1: Main

//设置package包名称以及导入依赖的类
package lazyvar2

import java.util.concurrent.ThreadLocalRandom

object Main {
  val txcount = 100000
  
  def main(args : Array[String]) : Unit = {
    val state = Array.ofDim[LazyVar[Int]](100)
    for(i <- 0 until state.length)
      state(i) = new LazyVar(0)
    
    // note: lazy reads do not improve performance in this model, because they must be locked anyway, so they could be read immediately
    // they do improve performance if they can actually be read lazily
    
    while(true) {
      val begin = System.nanoTime()
      for(i <- (0 to txcount).par) {
        val rnd = ThreadLocalRandom.current()
        
        val tx = new Transaction()
        for(i <- 1 to 10)
          tx.update(state(rnd.nextInt(state.size)), (x : Int) => x + 1)
        tx.commit
      }
      val end = System.nanoTime()
      
      val time = (end - begin) / 1000000000.0
      
      println(txcount / time)
    }
  }
} 
开发者ID:utwente-fmt,项目名称:lazy-persistent-trie,代码行数:34,代码来源:Main.scala


示例2: Util

//设置package包名称以及导入依赖的类
package lazytx.benchmark.tpcc

import java.util.concurrent.ThreadLocalRandom

object Util {
  val nameParts = Array("BAR", "OUGHT", "ABLE", "PRI", "PRES", "ESE", "ANTI", "CALLY", "ATION", "EING")
  var names = Array.ofDim[String](1000)
  for(i <- 0 to 999) {
    names(i) = genname(i)
  }
  
  def c(a : Int) = rand(0, ThreadLocalRandom.current.nextInt(a))
  
  def rand(a : Int, b : Int) : Int = ThreadLocalRandom.current().nextInt(b - a + 1) + a
  
  def randa(length : Int) : String = {
    var result = new StringBuilder(length)
    val rnd = ThreadLocalRandom.current
    for(i <- 1 to length) {
      result.append(String.valueOf(('a' + rnd.nextInt(26)).toChar))
    }
    result.toString()
  }
  
  def randOriginal() : String = {
    var r = randa(rand(26, 50))
    if(rand(1, 10) == 1) {
      r
    } else {
      val start = r.length() - 8
      r.substring(0, start) + "ORIGINAL" + r.substring(start + 8, r.length)
    }
  }
  
  def nurand(a : Int, x : Int, y : Int) = (((rand(0, a) | rand(x, y)) + c(a)) % (y - x + 1)) + x
  
  def genname(n : Int) = nameParts(n / 100) + nameParts((n / 10) % 10) + nameParts(n % 10)
  
  def name(n : Int) = names(n)
  
  def permutation(count : Int) = {
    var result = Array.ofDim[Int](count)
    val rnd = ThreadLocalRandom.current
    for(i <- 1 to count) {
      result(i - 1) = i
    }
    for(i <- 0 to count - 1) {
      val temp = result(i)
      val s = i + (rnd.nextInt(count - i)).toInt
      result(i) = result(s)
      result(s) = temp
    }
    result
  }
  
  def new_order_key(w_id : Long, d_id : Long, o_id : Long) =
    (w_id << 40) + (d_id << 32) + o_id
} 
开发者ID:utwente-fmt,项目名称:lazy-persistent-trie,代码行数:59,代码来源:Util.scala


示例3: Base

//设置package包名称以及导入依赖的类
package com.spooky.inbound

import java.math.BigInteger
import java.util.concurrent.ThreadLocalRandom
import java.nio.charset.Charset

abstract class Base {
  protected val DH_P = "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A63A36210000000000090563"
  protected val DH_G = "02"
  protected val DH_L = 160

  protected val UTF8 = Charset.forName("UTF8");
  protected val KEYA_IV = "keyA".getBytes(UTF8)
  protected val KEYB_IV = "keyB".getBytes(UTF8)
  protected val REQ1_IV = "req1".getBytes(UTF8)
  protected val REQ2_IV = "req2".getBytes(UTF8)
  protected val REQ3_IV = "req3".getBytes(UTF8)
  protected val VC = Array[Byte](0, 0, 0, 0, 0, 0, 0, 0)

  protected val RC4_STREAM_ALG = "RC4";

  protected val DH_P_BI = new BigInteger(DH_P, 16)
  protected val DH_G_BI = new BigInteger(DH_G, 16)

  protected val DH_SIZE_BYTES = DH_P.length() / 2

  protected val CRYPTO_PLAIN: Byte = Plain.id
  protected val CRYPTO_RC4: Byte = RC4.id

  protected val PADDING_MAX = 512

  private def randomPaddingSize: Int = {
    val random = ThreadLocalRandom.current
    Math.abs(random.nextInt % PADDING_MAX)
  }

  protected def randomPadding(): Array[Byte] = {
    val padding = Array.ofDim[Byte](randomPaddingSize)
    val random = ThreadLocalRandom.current
    random.nextBytes(padding)
    padding
  }
} 
开发者ID:zpooky,项目名称:bittorrent,代码行数:44,代码来源:Base.scala


示例4: SessionUtil

//设置package包名称以及导入依赖的类
package com.softwaremill.session

import java.math.BigInteger
import java.util.concurrent.ThreadLocalRandom
import javax.xml.bind.DatatypeConverter

object SessionUtil {
  def randomString(length: Int) = {
    // http://stackoverflow.com/questions/41107/how-to-generate-a-random-alpha-numeric-string
    val random = ThreadLocalRandom.current()
    new BigInteger(length * 5, random).toString(32) // because 2^5 = 32
  }

  
  def randomServerSecret() = randomString(128)

  // Do not change this unless you understand the security issues behind timing attacks.
  // This method intentionally runs in constant time if the two strings have the same length.
  // If it didn't, it would be vulnerable to a timing attack.
  def constantTimeEquals(a: String, b: String) = {
    if (a.length != b.length) {
      false
    }
    else {
      var equal = 0
      for (i <- Array.range(0, a.length)) {
        equal |= a(i) ^ b(i)
      }
      equal == 0
    }
  }

  def toHexString(array: Array[Byte]): String = {
    DatatypeConverter.printHexBinary(array)
  }

  def hexStringToByte(hexString: String): Array[Byte] = {
    DatatypeConverter.parseHexBinary(hexString)
  }
} 
开发者ID:adamw,项目名称:testpr,代码行数:41,代码来源:SessionUtil.scala


示例5: rnd

//设置package包名称以及导入依赖的类
package scaladays.akka.support

import java.util.concurrent.ThreadLocalRandom

import scala.util.Random

trait MakingUpData {

  private def rnd = ThreadLocalRandom.current()

  private def char = rnd.nextInt(65, 91).toChar

  def shortNameId(): String = s"$char$char$char"

  def shortName(): String = s"${char.toUpper}${char.toLower}${char.toLower}${char.toLower}${char.toLower}"

  def lipsum(): String = Random.shuffle(lipsumWords).take(rnd.nextInt(5, 20)).mkString(" ") + "."

  def int(): Int = rnd.nextInt(0, 101)


  val lipsumWords = List(
    "a", "ac", "accumsan", "ad", "adipiscing",
    "aenean", "aliquam", "aliquet", "amet", "ante", "aptent", "arcu",
    "at", "auctor", "augue", "bibendum", "blandit", "class", "commodo",
    "condimentum", "congue", "consectetur", "consequat", "conubia",
    "convallis", "cras", "cubilia", "cum", "curabitur", "curae",
    "cursus", "dapibus", "diam", "dictum", "dictumst", "dignissim",
    "dis", "dolor", "donec", "dui", "duis", "egestas", "eget",
    "eleifend", "elementum", "elit", "enim", "erat", "eros", "est",
    "et", "etiam", "eu", "euismod", "facilisi", "facilisis", "fames",
    "faucibus", "felis", "fermentum", "feugiat", "fringilla", "fusce",
    "gravida", "habitant", "habitasse", "hac", "hendrerit",
    "himenaeos", "iaculis", "id", "imperdiet", "in", "inceptos",
    "integer", "interdum", "ipsum", "justo", "lacinia", "lacus",
    "laoreet", "lectus", "leo", "libero", "ligula", "litora",
    "lobortis", "lorem", "luctus", "maecenas", "magna", "magnis",
    "malesuada", "massa", "mattis", "mauris", "metus", "mi",
    "molestie", "mollis", "montes", "morbi", "mus", "nam", "nascetur",
    "natoque", "nec", "neque", "netus", "nibh", "nisi", "nisl", "non",
    "nostra", "nulla", "nullam", "nunc", "odio", "orci", "ornare",
    "parturient", "pellentesque", "penatibus", "per", "pharetra",
    "phasellus", "placerat", "platea", "porta", "porttitor", "posuere",
    "potenti", "praesent", "pretium", "primis", "proin", "pulvinar",
    "purus", "quam", "quis", "quisque", "rhoncus", "ridiculus",
    "risus", "rutrum", "sagittis", "sapien", "scelerisque", "sed",
    "sem", "semper", "senectus", "sit", "sociis", "sociosqu",
    "sodales", "sollicitudin", "suscipit", "suspendisse", "taciti",
    "tellus", "tempor", "tempus", "tincidunt", "torquent", "tortor",
    "tristique", "turpis", "ullamcorper", "ultrices", "ultricies",
    "urna", "ut", "varius", "vehicula", "vel", "velit", "venenatis",
    "vestibulum", "vitae", "vivamus", "viverra", "volutpat",
    "vulputate"
    )
} 
开发者ID:ktoso,项目名称:scaladays-berlin-akka-streams,代码行数:56,代码来源:MakingUpData.scala


示例6: BbcId

//设置package包名称以及导入依赖的类
package bbcid

import scala.concurrent.duration._

import io.gatling.core.Predef._
import io.gatling.http.Predef._

object BbcId {

  import java.util.concurrent.ThreadLocalRandom

  def register(pageToReturnTo: String = "/") = {

    val encodedPageToReturnTo = java.net.URLEncoder.encode(pageToReturnTo, "UTF-8")

    exec(_.set("email", s"[email protected]${ThreadLocalRandom.current.nextInt(Int.MaxValue)}.com"))
    .exec(http("getBbcIdRegister")
    .get("/id/register"))
    .exec(http("postBbcIdRegister")
    .post("/id/register?ptrt=" + encodedPageToReturnTo)
      .formParam("email", "${email}")
      .formParam("confirmpassword", "wwtest")
      .formParam("confirmpassword_confirm", "wwtest")
      .formParam("personalisedupdates", "0")
      .formParam("personalisedupdates", "1")
      .formParam("bbcid_submit_button", "Register")
      .check(status is 200, css("#orb-modules h2") is "Your registration is complete"))
  }

  def signIn(pageToReturnTo: String = "/",
              validation: String = "Welcome to the BBC") = {

    val encodedPageToReturnTo = java.net.URLEncoder.encode(pageToReturnTo, "UTF-8")

    val feeder = csv("bbcid/bbcid_emails.txt").circular

    feed(feeder)
    .exec(http("getBbcIdSignIn")
    .get("/id/signin"))
    .exec(http("postBbcIdSignIn")
    .post("/id/signin?ptrt=" + encodedPageToReturnTo)
      .formParam("unique", "${email}")
      .formParam("password", "loadtest")
      .formParam("rememberme", "1")
      .check(status is 200, substring(validation)))

  }

} 
开发者ID:narlas01,项目名称:Mirrored,代码行数:50,代码来源:BbcId.scala


示例7: ComputerWorld

//设置package包名称以及导入依赖的类
package bbc.kraftwerk

import scala.concurrent.duration._

import io.gatling.core.Predef._
import io.gatling.http.Predef._

import java.util.concurrent.ThreadLocalRandom

class ComputerWorld extends Simulation {

  val httpProtocol = http
    .baseURL("http://computer-database.gatling.io")
    .acceptHeader("""text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8""")
    .acceptEncodingHeader("""gzip, deflate""")
    .acceptLanguageHeader("""en-gb,en;q=0.5""")
    .userAgentHeader("""Mozilla/5.0 (Macintosh; Intel Mac OS X 10.9; rv:31.0) Gecko/20100101 Firefox/31.0""")

  val computerDbScn = scenario("Computer Scenario") 
    .exec(http("getComputers")
    .get("/computers")
      .check(
        status is 200,
        regex("""\d+ computers found"""),
        css("#add", "href").saveAs("addComputer")))

    .exec(http("addNewComputer")
    .get("${addComputer}")
      .check(substring("Add a computer")))

    .exec(_.set("homeComputer", s"homeComputer_${ThreadLocalRandom.current.nextInt(Int.MaxValue)}"))
    .exec(http("postComputers") 
    .post("/computers")
      .formParam("name", "${homeComputer}") 
      .formParam("introduced", "2015-10-10") 
      .formParam("discontinued", "2017-10-10") 
      .formParam("company", "") 
      .check(substring("${homeComputer}")))

  setUp(computerDbScn.inject(
    constantUsersPerSec(2) during(10 minutes)
  ).protocols(httpProtocol)) 
} 
开发者ID:narlas01,项目名称:Mirrored,代码行数:44,代码来源:ComputerWorld.scala


示例8: random

//设置package包名称以及导入依赖的类
package com.github.jeroenr.tepkin.util

import java.util.concurrent.ThreadLocalRandom

trait Randomizer {

  def random: ThreadLocalRandom = ThreadLocalRandom.current()

  def randomString(alphabet: String)(n: Int): String = {
    Stream.continually(random.nextInt(alphabet.size)).map(alphabet).take(n).mkString
  }

  def randomString(n: Int): String = {
    randomString {
      """!"#$%&'()*+-./0123456789:;<=>[email protected][\]^_`abcdefghijklmnopqrstuvwxyz{|}~"""
    }(n)
  }
} 
开发者ID:dgouyette,项目名称:tepkin,代码行数:19,代码来源:Randomizer.scala


示例9: ComputerWorld

//设置package包名称以及导入依赖的类
package computerdatabase

import scala.concurrent.duration._

import java.util.concurrent.ThreadLocalRandom

import io.gatling.core.Predef._
import io.gatling.http.Predef._

class ComputerWorld extends Simulation {

  val httpProtocol = http
    .baseURL("http://computer-database.gatling.io")
    .acceptHeader("""text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8""")
    .acceptEncodingHeader("""gzip, deflate""")
    .acceptLanguageHeader("""en-gb,en;q=0.5""")
    .userAgentHeader("""Mozilla/5.0 (Macintosh; Intel Mac OS X 10.9; rv:31.0) Gecko/20100101 Firefox/31.0""")

  val computerDbScn = scenario("Computer Scenario") 
    .exec(http("getComputers")
    .get("/computers")
      .check(
        status is 200,
        regex("""\d+ computers found"""),
        css("#add", "href").saveAs("addComputer")))

    .exec(http("addNewComputer")
    .get("${addComputer}")
      .check(substring("Add a computer")))

    .exec(_.set("homeComputer", s"homeComputer_${ThreadLocalRandom.current.nextInt(Int.MaxValue)}"))
    .exec(http("postComputers") 
    .post("/computers")
      .formParam("name", "${homeComputer}") 
      .formParam("introduced", "2015-10-10") 
      .formParam("discontinued", "2017-10-10") 
      .formParam("company", "") 
      .check(substring("${homeComputer}")))

  setUp(computerDbScn.inject(
    constantUsersPerSec(2) during(1 minute)
  ).protocols(httpProtocol)) 
} 
开发者ID:devagorilla,项目名称:gitbucket-load-test,代码行数:44,代码来源:ComputerWorld.scala


示例10: ComputerWorld

//设置package包名称以及导入依赖的类
package bbc.kraftwerk

import scala.concurrent.duration._

import java.util.concurrent.ThreadLocalRandom

import io.gatling.core.Predef._
import io.gatling.http.Predef._

class ComputerWorld extends Simulation {

  val httpProtocol = http
    .baseURL("http://computer-database.herokuapp.com")
    .acceptHeader("""text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8""")
    .acceptEncodingHeader("""gzip, deflate""")
    .acceptLanguageHeader("""en-gb,en;q=0.5""")
    .contentTypeHeader("application/x-www-form-urlencoded")
    .userAgentHeader("""Mozilla/5.0 (Macintosh; Intel Mac OS X 10.9; rv:31.0) Gecko/20100101 Firefox/31.0""")

  val computers = http("computers") 
    .get("/computers")
    .check(
      status.is(200),
      regex("""\d+ computers found"""),
      css("#add", "href").saveAs("addComputer"))
    
  val addNewComputer = http("addNewComputer")
    .get("${addComputer}")
    .check(substring("Add a computer"))

  val addNewComputerPost = http("addNewComputerPost") 
    .post("/computers")
    .formParam("name", "${homeComputer}") 
    .formParam("introduced", "2015-10-10") 
    .formParam("discontinued", "2017-10-10") 
    .formParam("company", "") 
    .check(substring("${homeComputer}"))
  
  val computerDatabaseScn = scenario("computerDatabaseScn") 
    .exec(_.set("homeComputer", s"homeComputer_${ThreadLocalRandom.current.nextInt(Int.MaxValue)}"))
    .exec(computers)
    .exec(addNewComputer)
    .exec(addNewComputerPost)
    
  setUp(computerDatabaseScn.inject(
    constantUsersPerSec(2) during(1 minutes)
  ).protocols(httpProtocol)) 
} 
开发者ID:yabols,项目名称:bbcGatling,代码行数:49,代码来源:ComputerWorld.scala


示例11: sample

//设置package包名称以及导入依赖的类
package npv

import java.util.concurrent.ThreadLocalRandom


trait Distribution {
  def sample(): Double
  def getMax(): Double
  def getMin(): Double
}

class SingleValueDistribution(value: Double) extends Distribution {
  override def sample(): Double = value
  override def getMax(): Double = value
  override def getMin(): Double = value
}

class TriangleDistribution(min: Double, likely: Double, max: Double)
        extends Distribution {

  assert(max >= likely)
  assert(likely >= min)

  val fc: Double = (likely - min) / (max - min)

  override def sample(): Double = {
    val u = ThreadLocalRandom.current().nextDouble()
    if (u < fc) {
      min + Math.sqrt(u * (max - min) * (likely - min))
    } else {
      max - Math.sqrt((1 - u) * (max - min) * (max - likely))
    }
  }

  override def getMin(): Double = min

  def getLikely(): Double = likely

  override def getMax(): Double = max

} 
开发者ID:phaller,项目名称:reactive-async,代码行数:42,代码来源:Distribution.scala


示例12: ExponentialBackOff

//设置package包名称以及导入依赖的类
package com.snapswap.retry

import java.util.concurrent.ThreadLocalRandom

import scala.concurrent.duration.{Duration, FiniteDuration}

object ExponentialBackOff {
  def apply(minBackoff: FiniteDuration, maxBackoff: FiniteDuration, randomFactor: Double): ExponentialBackOff =
    new ExponentialBackOff(minBackoff, maxBackoff, randomFactor, 1)
}

case class ExponentialBackOff(protected val minBackoff: FiniteDuration,
                              protected val maxBackoff: FiniteDuration,
                              protected val randomFactor: Double,
                              override val currentAttemptNumber: Int = 1) extends AttemptParams {
  require(minBackoff > Duration.Zero, "minBackoff must be > 0")
  require(maxBackoff >= minBackoff, "maxBackoff must be >= minBackoff")
  require(0.0 <= randomFactor && randomFactor <= 1.0, "randomFactor must be between 0.0 and 1.0")

  override def nextAttemptDelay: FiniteDuration = {
    val rnd = 1.0 + ThreadLocalRandom.current().nextDouble() * randomFactor
    if (currentAttemptNumber >= 30) {
      // Duration overflow protection (> 100 years)
      maxBackoff
    } else {
      maxBackoff.min(minBackoff * math.pow(2, currentAttemptNumber.toDouble)) * rnd match {
        case f: FiniteDuration ? f
        case _ ? maxBackoff
      }
    }
  }

  override def nextAttemptParams: ExponentialBackOff = {
    copy(currentAttemptNumber = currentAttemptNumber + 1)
  }
} 
开发者ID:snap-swap,项目名称:akka-rescheduler,代码行数:37,代码来源:ExponentialBackOff.scala


示例13: Unique

//设置package包名称以及导入依赖的类
package org.hyperscala

import java.util.concurrent.ThreadLocalRandom

object Unique {
  val LettersLower = "abcdefghijklmnopqrstuvwxyz"
  val LettersUpper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  val Numbers = "0123456789"
  val LettersAndNumbers = s"$LettersLower$Numbers"
  val AllLettersAndNumbers = s"$LettersLower$LettersUpper$Numbers"

  private def r = ThreadLocalRandom.current()

  
  def poolSize(length: Int = 32, characters: String = AllLettersAndNumbers): Long = {
    math.pow(characters.length, length).toLong
  }
} 
开发者ID:outr,项目名称:hyperscala,代码行数:19,代码来源:Unique.scala


示例14: ComputerWorld

//设置package包名称以及导入依赖的类
import scala.concurrent.duration._

import io.gatling.core.Predef._
import io.gatling.http.Predef._

import java.util.concurrent.ThreadLocalRandom

class ComputerWorld extends Simulation {

  val httpProtocol = http
    .baseURL("http://computer-database.gatling.io")
    .acceptHeader("""text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8""")
    .acceptEncodingHeader("""gzip, deflate""")
    .acceptLanguageHeader("""en-gb,en;q=0.5""")
    .contentTypeHeader("application/x-www-form-urlencoded")
    .userAgentHeader("""Mozilla/5.0 (Macintosh; Intel Mac OS X 10.9; rv:31.0) Gecko/20100101 Firefox/31.0""")

  val computerDbScn = scenario("Computer Scenario") 
    .exec(http("getComputers")
    .get("/computers")
      .check(
        status is 200,
        regex("""\d+ computers found"""),
        css("#add", "href").saveAs("addComputer")))

    .exec(http("addNewComputer")
    .get("${addComputer}")
      .check(substring("Add a computer")))

    .exec(_.set("homeComputer", s"homeComputer_${ThreadLocalRandom.current.nextInt(Int.MaxValue)}"))
    .exec(http("postComputers") 
    .post("/computers")
      .formParam("name", "${homeComputer}") 
      .formParam("introduced", "2015-10-10") 
      .formParam("discontinued", "2017-10-10") 
      .formParam("company", "") 
      .check(substring("${homeComputer}")))

  setUp(computerDbScn.inject(
    constantUsersPerSec(2) during(1 minutes)
  ).protocols(httpProtocol)) 
} 
开发者ID:aidylewis,项目名称:gatling-sbt.g8,代码行数:43,代码来源:ComputerWorld.scala


示例15: DeviceRequest

//设置package包名称以及导入依赖的类
package worker

import java.util.UUID
import java.util.concurrent.ThreadLocalRandom
import scala.concurrent.duration._
import akka.actor.Actor
import akka.actor.ActorLogging
import akka.actor.ActorRef

import com.sandinh.paho.akka._
import com.sandinh.paho.akka.MqttPubSub._

object DeviceRequest {
  case object Tick
}

class DeviceRequest(mqttPubSub: ActorRef) extends Actor with ActorLogging {
  import DeviceRequest._
  import context.dispatcher

  def scheduler = context.system.scheduler
  def random = ThreadLocalRandom.current
  def nextWorkId(): String = UUID.randomUUID().toString

  override def preStart(): Unit = scheduler.scheduleOnce(5.seconds, self, Tick)

  // override postRestart so we don't call preStart and schedule a new Tick
  override def postRestart(reason: Throwable): Unit = ()

  def receive = {
    case Tick => {
      // Random pick from a list of serializable devices
      val deviceList: List[Device] = List(new Thermostat, new Lamp, new SecurityAlarm)
      val device = deviceList(random.nextInt(0, deviceList.size))
      val work = Work(nextWorkId(), device, "Adjust device")
      log.info("Device Request -> Device Id {} | Device State {}", device.getId, device.getState)

      val payload = MqttConfig.writeToByteArray(work)

      log.info("Device Request -> Publishing MQTT Topic {}: Device Id {} | Device State {}", MqttConfig.topic, work.device.getId, work.device.getState)

      mqttPubSub ! new Publish(MqttConfig.topic, payload)

      context.become(waitAccepted(work, payload), discardOld = false)
    }
  }

  def waitAccepted(work: Work, payload: Array[Byte]): Actor.Receive = {
    case IotAgent.Ok =>
      context.unbecome()
      scheduler.scheduleOnce(random.nextInt(3, 10).seconds, self, Tick)
    case IotAgent.NotOk =>
      log.info("Device Request -> ALERT: Work Id {} from Device Id {} NOT ACCEPTED, retrying ... ", work.workId, work.device.getId)
      scheduler.scheduleOnce(3.seconds, mqttPubSub, new Publish(MqttConfig.topic, payload))
  }
} 
开发者ID:oel,项目名称:akka-iot-mqtt,代码行数:57,代码来源:DeviceRequest.scala


示例16: random

//设置package包名称以及导入依赖的类
package worker

import java.io.Serializable
import java.util.concurrent.ThreadLocalRandom

sealed trait Device extends Serializable {
  def random = ThreadLocalRandom.current
  def getId: String
  def getState: String
}

// Thermostat with random id & state
class Thermostat extends Device {
  val states = List("HEAT", "COOL")
  val id = "thermostat-" + (1000 + super.random.nextInt(0, 100)).toString
  val state = states(super.random.nextInt(0, states.size))

  def getId: String = id
  def getState: String = state
}

// Lamp with random id & state
class Lamp extends Device {
  val states = List("ON", "OFF")
  val id = "lamp-" + (5000 + super.random.nextInt(0, 500)).toString
  val state = states(super.random.nextInt(0, states.size))

  def getId: String = id
  def getState: String = state
}

// Security alarm with random id & state
class SecurityAlarm extends Device {
  val states = List("ON", "OFF")
  val id = "security-alarm-" + (9000 + super.random.nextInt(0, 100)).toString
  val state = states(super.random.nextInt(0, states.size))

  def getId: String = id
  def getState: String = state
} 
开发者ID:oel,项目名称:akka-iot-mqtt,代码行数:41,代码来源:Device.scala


示例17: WorkProcessor

//设置package包名称以及导入依赖的类
package worker

import akka.actor.Actor
import java.util.concurrent.ThreadLocalRandom

class WorkProcessor extends Actor {
  def random = ThreadLocalRandom.current

  def receive = {
    case device: Device => {
      val result = adjust(device)
      sender() ! Worker.WorkComplete(result)
    }
    case _ =>
  }

  def adjust(device: Device): String = device match {
    case t: Thermostat => {
      val changes = List("RAISE temperature by ", "LOWER temperature by ", "NO CHANGE")
      val change = changes(random.nextInt(0, changes.size))
      val byDegF = 1 + random.nextInt(0, 3)
      if (change == "NO CHANGE") "NO CHANGE" else
        change + byDegF + "F"
    }
    case l: Lamp => {
      val states = List(0, 1)
      val state = states(random.nextInt(0, states.size))
      val opposite = if (device.getState == "ON") "OFF" else "ON"
      if (state == 0) "NO CHANGE" else
        "Switch light to " + opposite
    }
    case s: SecurityAlarm => {
      val states = List(0, 1)
      val state = states(random.nextInt(0, states.size))
      val opposite = if (device.getState == "ON") "OFF" else "ON"
      if (state == 0) "NO CHANGE" else
        "Switch light to " + opposite
    }
    case _ => "NO CHANGE"
  }
} 
开发者ID:oel,项目名称:akka-iot-mqtt,代码行数:42,代码来源:WorkProcessor.scala


示例18: nextRandomInt

//设置package包名称以及导入依赖的类
package chana.mq

import chana.mq.amqp.model.VirtualHost
import java.util.concurrent.ThreadLocalRandom

package object amqp {

  def nextRandomInt(max: Int) = ThreadLocalRandom.current.nextInt(max + 1)
  def nextRandomInt(min: Int, max: Int) = min + ThreadLocalRandom.current.nextInt(max - min + 1)

  trait Command extends Serializable {
    def id: String
  }
  trait VHostCommand extends Serializable {
    def vhost: String
    def id: String
    def entityId = if (vhost.isEmpty) {
      id
    } else {
      s"${vhost}${VirtualHost.sep}${id}"
    }
  }

  private[amqp] case object ActiveCheckTick
  private[amqp] case object Loaded
  private[amqp] case object Unlock
} 
开发者ID:qingmang-team,项目名称:chanamq,代码行数:28,代码来源:package.scala


示例19: ComputerWorld

//设置package包名称以及导入依赖的类
import scala.concurrent.duration._

import java.util.concurrent.ThreadLocalRandom

import io.gatling.core.Predef._
import io.gatling.http.Predef._
import net.liftweb.json.DefaultFormats

class ComputerWorld extends Simulation {

implicit val formats = DefaultFormats


  val httpProtocol = http
    .baseURL("http://computer-database.gatling.io")
    .acceptHeader("""text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8""")
    .acceptEncodingHeader("""gzip, deflate""")
    .acceptLanguageHeader("""en-gb,en;q=0.5""")
    .userAgentHeader("""Mozilla/5.0 (Macintosh; Intel Mac OS X 10.9; rv:31.0) Gecko/20100101 Firefox/31.0""")

  val computerDbScn = scenario("Computer Scenario")
    .exec(http("getComputers")
    .get("/computers")
      .check(
        status is 200,
        regex("""\d+ computers found"""),
        css("#add", "href").saveAs("addComputer")))

    .exec(http("addNewComputer")
    .get("${addComputer}")
      .check(substring("Add a computer")))

    .exec(_.set("homeComputer", s"homeComputer_${ThreadLocalRandom.current.nextInt(Int.MaxValue)}"))
    .exec(http("postComputers")
    .post("/computers")
      .formParam("name", "${homeComputer}")
      .formParam("introduced", "2015-10-10")
      .formParam("discontinued", "2017-10-10")
      .formParam("company", "")
      .check(substring("${homeComputer}")))

    // print all session values
    // .exec { session => println(session(session)); session }

    // print a session value
    // .exec { session => println(session("homeComputer").as[String]); session }

  setUp(computerDbScn.inject(
    constantUsersPerSec(2) during(2 minutes)
  ).protocols(httpProtocol))
} 
开发者ID:sagardutta,项目名称:taurus-files-example,代码行数:52,代码来源:ComputerWorld.scala


示例20: Util

//设置package包名称以及导入依赖的类
package lazytrie.test

import lazytrie.SmallIntKey
import lazytrie.Map
import java.util.concurrent.ThreadLocalRandom
import lazytrie.StringKey

object Util {
  def createIntMap(size : Int, leafWidth : Int = 0, branchWidth : Int = 5) = {
    val rnd = ThreadLocalRandom.current()
    val discr = new SmallIntKey(Math.ceil(Math.log(size) / Math.log(2)).toInt)
    var map = Map[Int,Int](discr, leafWidth, branchWidth)
    for(i <- 0 to size - 1) {
      map.putInPlace(i, rnd.nextInt(1000000))
    }
    map
  }
  
  def createStringMap(size : Int, leafWidth : Int = 0, branchWidth : Int = 5) = {
    val rnd = ThreadLocalRandom.current()
    val discr = new StringKey()
    var map = Map[String,Int](discr, leafWidth, branchWidth)
    for(i <- 0 to size - 1) {
      map.putInPlace(i.toString, rnd.nextInt(1000000))
    }
    map
  }
  
  def skewedRandom(max : Int, p : Double) : Int = {
    val rnd = ThreadLocalRandom.current()
    var low = 0
    var high = max - 1
    while(low != high) {
    	if(rnd.nextDouble() < p) {
    		high = (low + high) / 2
    	} else {
    		low = (low + high + 1) / 2
    	}
    }
    low
  }
} 
开发者ID:utwente-fmt,项目名称:lazy-transactions-IDEAS16,代码行数:43,代码来源:Util.scala



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Scala Maps类代码示例发布时间:2022-05-23
下一篇:
Scala GraphLoader类代码示例发布时间:2022-05-23
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap