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

Scala ReentrantReadWriteLock类代码示例

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

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



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

示例1: ConsensusRouteSpec

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

import java.util.concurrent.locks.ReentrantReadWriteLock

import com.wavesplatform.BlockGen
import com.wavesplatform.history.HistoryWriterImpl
import com.wavesplatform.http.ApiMarshallers._
import com.wavesplatform.settings.FunctionalitySettings
import com.wavesplatform.state2._
import com.wavesplatform.state2.reader.StateReader
import org.scalamock.scalatest.MockFactory
import org.scalatest.prop.PropertyChecks
import play.api.libs.json.JsObject
import scorex.api.http.BlockNotExists
import scorex.consensus.nxt.api.http.NxtConsensusApiRoute
import scorex.crypto.encode.Base58

class ConsensusRouteSpec extends RouteSpec("/consensus") with RestAPISettingsHelper with PropertyChecks with MockFactory with BlockGen with HistoryTest {
  private val state = mock[StateReader]

  private val history = HistoryWriterImpl(None, new ReentrantReadWriteLock()).get
  appendGenesisBlock(history)
  for (i <- 1 to 10) appendTestBlock(history)

  private val route = NxtConsensusApiRoute(restAPISettings, state, history, FunctionalitySettings.TESTNET).route

  routePath("/generationsignature") - {
    "for last block" in {
      Get(routePath("/generationsignature")) ~> route ~> check {
        (responseAs[JsObject] \ "generationSignature").as[String] shouldEqual Base58.encode(history.lastBlock.get.consensusData.generationSignature)
      }
    }

    "for existed block" in {
      val block = history.blockAt(3).get
      Get(routePath(s"/generationsignature/${block.uniqueId.base58}")) ~> route ~> check {
        (responseAs[JsObject] \ "generationSignature").as[String] shouldEqual Base58.encode(block.consensusData.generationSignature)
      }
    }

    "for not existed block" in {
      Get(routePath(s"/generationsignature/brggwg4wg4g")) ~> route should produce(BlockNotExists)
    }
  }

  routePath("/basetarget") - {
    "for existed block" in {
      val block = history.blockAt(3).get
      Get(routePath(s"/basetarget/${block.uniqueId.base58}")) ~> route ~> check {
        (responseAs[JsObject] \ "baseTarget").as[Long] shouldEqual block.consensusData.baseTarget
      }
    }

    "for not existed block" in {
      Get(routePath(s"/basetarget/brggwg4wg4g")) ~> route should produce(BlockNotExists)
    }
  }
} 
开发者ID:wavesplatform,项目名称:Waves,代码行数:59,代码来源:ConsensusRouteSpec.scala


示例2: newState

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

import java.util.concurrent.locks.ReentrantReadWriteLock

import com.wavesplatform.history.HistoryWriterImpl
import com.wavesplatform.settings.FunctionalitySettings
import com.wavesplatform.state2.reader.{CompositeStateReader, StateReader}
import scorex.block.Block
import scorex.settings.TestFunctionalitySettings
import scorex.transaction.{History, ValidationError}

package object diffs {

  private val lock = new ReentrantReadWriteLock()

  def newState(): StateWriterImpl = new StateWriterImpl(StateStorage(None, dropExisting = false).get, lock)

  def newHistory(): History = HistoryWriterImpl(None, lock).get

  val ENOUGH_AMT: Long = Long.MaxValue / 3

  def assertDiffEi(preconditions: Seq[Block], block: Block, fs: FunctionalitySettings = TestFunctionalitySettings.Enabled)(assertion: Either[ValidationError, BlockDiff] => Unit): Unit = {
    val differ: (StateReader,  Block) => Either[ValidationError, BlockDiff] = (s, b) => BlockDiffer.fromBlock(fs, s, None)(b)

    val state = newState()

    preconditions.foreach { precondition =>
      val preconditionDiff = differ(state,  precondition).explicitGet()
      state.applyBlockDiff(preconditionDiff)
    }
    val totalDiff1 = differ(state,  block)
    assertion(totalDiff1)

    val preconditionDiff = BlockDiffer.unsafeDiffMany(fs, newState(), None)(preconditions)
    val compositeState = new CompositeStateReader(newState(), preconditionDiff)
    val totalDiff2 = differ(compositeState, block)
    assertion(totalDiff2)
  }

  def assertDiffAndState(preconditions: Seq[Block], block: Block, fs: FunctionalitySettings = TestFunctionalitySettings.Enabled)(assertion: (BlockDiff, StateReader) => Unit): Unit = {
    val differ: (StateReader, Block) => Either[ValidationError, BlockDiff] = (s, b) => BlockDiffer.fromBlock(fs, s, None)(b)

    val state = newState()
    preconditions.foreach { precondition =>
      val preconditionDiff = differ(state,  precondition).explicitGet()
      state.applyBlockDiff(preconditionDiff)
    }
    val totalDiff1 = differ(state,  block).explicitGet()
    state.applyBlockDiff(totalDiff1)
    assertion(totalDiff1, state)

    val preconditionDiff = BlockDiffer.unsafeDiffMany(fs, newState(), None)(preconditions)
    val compositeState = new CompositeStateReader(newState(), preconditionDiff)
    val totalDiff2 = differ(compositeState,  block).explicitGet()
    assertion(totalDiff2, new CompositeStateReader(compositeState, totalDiff2))
  }

  def produce(errorMessage: String): ProduceError = new ProduceError(errorMessage)
} 
开发者ID:wavesplatform,项目名称:Waves,代码行数:60,代码来源:package.scala


示例3: StateReaderEffectiveBalanceTest

//设置package包名称以及导入依赖的类
package com.wavesplatform.state2.reader

import java.util.concurrent.locks.ReentrantReadWriteLock

import com.wavesplatform.state2.StateStorage
import com.wavesplatform.state2.StateStorage._
import org.scalatest.{Matchers, Outcome, fixture}
import scorex.account.Address


class StateReaderEffectiveBalanceTest extends fixture.FunSuite with Matchers {

  val acc: Address = Address.fromPublicKey(Array.emptyByteArray)
  val stateHeight = 100

  override type FixtureParam = StateStorage

  override protected def withFixture(test: OneArgTest): Outcome = {
    val storage = StateStorage(None, dropExisting = false).get
    storage.setHeight(stateHeight)
    test(storage)
  }

  test("exposes minimum of all 'current' and  one 'previous' of oldest record") { storage =>
    storage.balanceSnapshots.put(accountIndexKey(acc, 20), (0, 0, 1))
    storage.balanceSnapshots.put(accountIndexKey(acc, 75), (20, 0, 200))
    storage.balanceSnapshots.put(accountIndexKey(acc, 90), (75, 0, 100))
    storage.lastBalanceSnapshotHeight.put(acc.bytes, 90)

    new StateReaderImpl(storage, new ReentrantReadWriteLock()).effectiveBalanceAtHeightWithConfirmations(acc, stateHeight, 50) shouldBe 1
  }

  test("exposes current effective balance if no records in past N blocks are made") { storage =>
    storage.balanceSnapshots.put(accountIndexKey(acc, 20), (0, 0, 1))
    storage.portfolios.put(acc.bytes, (1, (0, 0), Map.empty))
    storage.lastBalanceSnapshotHeight.put(acc.bytes, 20)

    new StateReaderImpl(storage, new ReentrantReadWriteLock()).effectiveBalanceAtHeightWithConfirmations(acc, stateHeight, 50) shouldBe 1
  }

  test("doesn't include info older than N blocks") { storage =>
    storage.balanceSnapshots.put(accountIndexKey(acc, 20), (0, 0, 1000))
    storage.balanceSnapshots.put(accountIndexKey(acc, 50), (20, 0, 50000))
    storage.balanceSnapshots.put(accountIndexKey(acc, 75), (50, 0, 100000))
    storage.lastBalanceSnapshotHeight.put(acc.bytes, 75)

    new StateReaderImpl(storage, new ReentrantReadWriteLock()).effectiveBalanceAtHeightWithConfirmations(acc, stateHeight, 50) shouldBe 50000
  }

  test("includes most recent update") { storage =>
    storage.balanceSnapshots.put(accountIndexKey(acc, 20), (0, 0, 1000))
    storage.balanceSnapshots.put(accountIndexKey(acc, 51), (20, 0, 50000))
    storage.balanceSnapshots.put(accountIndexKey(acc, 100), (51, 0, 1))
    storage.lastBalanceSnapshotHeight.put(acc.bytes, 100)

    new StateReaderImpl(storage, new ReentrantReadWriteLock()).effectiveBalanceAtHeightWithConfirmations(acc, stateHeight, 50) shouldBe 1
  }
} 
开发者ID:wavesplatform,项目名称:Waves,代码行数:59,代码来源:StateReaderEffectiveBalanceTest.scala


示例4: StateWriterSpec

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

import java.util.concurrent.locks.ReentrantReadWriteLock

import org.scalacheck.Gen
import org.scalatest.prop.GeneratorDrivenPropertyChecks
import org.scalatest.{FunSuite, Matchers}

class StateWriterSpec extends FunSuite with Matchers with GeneratorDrivenPropertyChecks {
  test("increase height when applying block diff") {
    val storage = StateStorage(None, dropExisting = false).get
    val writer = new StateWriterImpl(storage, new ReentrantReadWriteLock())
    forAll(Gen.choose(0, Int.MaxValue)) { heightDiff =>
      val h = writer.height
      writer.applyBlockDiff(BlockDiff(Diff.empty, heightDiff, Map.empty))
      writer.height shouldBe h + heightDiff
      storage.getHeight shouldBe h + heightDiff
    }
  }
} 
开发者ID:wavesplatform,项目名称:Waves,代码行数:21,代码来源:StateWriterSpec.scala


示例5: withLock

//设置package包名称以及导入依赖的类
package io.hydrosphere.mist.master.data

import java.util.concurrent.locks.{Lock, ReentrantReadWriteLock}

trait RwLock {

  private val rwLock = new ReentrantReadWriteLock()

  protected def withLock[T](l: Lock, f: => T): T = {
    l.lock()
    try {
      f
    } finally {
      l.unlock()
    }
  }

  protected def withReadLock[T](f: => T): T = withLock(rwLock.readLock, f)
  protected def withWriteLock[T](f: => T): T = withLock(rwLock.writeLock, f)
} 
开发者ID:Hydrospheredata,项目名称:mist,代码行数:21,代码来源:RwLock.scala


示例6: CachedValue

//设置package包名称以及导入依赖的类
package io.ahamdy.taskforce.common

import java.time.ZonedDateTime
import java.util.concurrent.atomic.AtomicReference
import java.util.concurrent.locks.ReentrantReadWriteLock

import io.ahamdy.taskforce.syntax.zonedDateTime._
import cats.syntax.flatMap._
import fs2.interop.cats._
import fs2.Task

import scala.concurrent.duration.FiniteDuration

class CachedValue[A](source: Task[A], ttl: FiniteDuration, time: Time) {
  val currentValue = new AtomicReference[Task[A]]()
  val lastUpdated = new AtomicReference[ZonedDateTime](time.epoch)
  val lock = new ReentrantReadWriteLock()

  def value: Task[A] =
    time.now.flatMap{ now =>
      if (lastUpdated.get().isBefore(now.minus(ttl))){
        try{
          lock.writeLock().lock()
          source.unsafeRunSync() match {
            case Right(a) =>
              Task.delay(lastUpdated.set(now)) >>
                Task.delay {
                  currentValue.set(Task.now(a))
                  a
                }
            case Left(_) => source
          }
        }finally {
          lock.writeLock().unlock()
        }
      }else{
        try{
          lock.readLock().lock()
          currentValue.get()
        }finally {
          lock.readLock().unlock()
        }
      }
    }
} 
开发者ID:ahamdy88,项目名称:JobForce,代码行数:46,代码来源:CachedValue.scala


示例7: RWLock

//设置package包名称以及导入依赖的类
package org.rebeam.tree.server.util

import java.util.concurrent.locks.ReentrantReadWriteLock

class RWLock() {
  private val lock: ReentrantReadWriteLock = new ReentrantReadWriteLock()

  def write[T](w: =>T): T = {
    lock.writeLock().lock()
    try {
      return w
    } finally {
      lock.writeLock().unlock()
    }
  }

  def read[T](r: =>T): T = {
    lock.readLock().lock()
    try {
      return r
    } finally {
      lock.readLock().unlock()
    }
  }
}

object RWLock {
  def apply() = new RWLock()
} 
开发者ID:trepidacious,项目名称:tree,代码行数:30,代码来源:RWLock.scala



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Scala RandomForestModel类代码示例发布时间:2022-05-23
下一篇:
Scala Params类代码示例发布时间: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