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

Scala ReentrantLock类代码示例

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

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



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

示例1: SubscriberRunner

//设置package包名称以及导入依赖的类
package com.bwsw.tstreams.velocity

import java.net.InetSocketAddress
import java.util.UUID
import java.util.concurrent.locks.ReentrantLock

import com.bwsw.tstreams.agents.consumer.Offsets.Oldest
import com.bwsw.tstreams.agents.consumer.subscriber.{Callback, SubscribingConsumer}
import com.bwsw.tstreams.agents.consumer.{ConsumerOptions, SubscriberCoordinationOptions}


object SubscriberRunner {
  def main(args: Array[String]) {
    import Common._
    val consumerOptions = new ConsumerOptions[String](transactionsPreload = 10, dataPreload = 7, arrayByteToStringConverter, RoundRobinPolicyCreator.getRoundRobinPolicy(stream, List(0)), Oldest, LocalGeneratorCreator.getGen(), useLastOffset = true)

    val lock = new ReentrantLock()
    var cnt = 0
    var timeNow = System.currentTimeMillis()
    val callback = new Callback[String] {
      override def onEvent(subscriber: SubscribingConsumer[String], partition: Int, transactionUuid: UUID): Unit = {
        lock.lock()
        if (cnt % 1000 == 0) {
          val time = System.currentTimeMillis()
          val diff = time - timeNow
          println(s"subscriber_time = $diff; cnt=$cnt")
          timeNow = time
        }
        cnt += 1
        lock.unlock()
      }
    }

    val subscribeConsumer = new SubscribingConsumer[String](
      name = "test_consumer",
      stream = stream,
      options = consumerOptions,
      subscriberCoordinationOptions =
        new SubscriberCoordinationOptions(agentAddress = "t-streams-4.z1.netpoint-dc.com:8588",
          zkRootPath = "/velocity",
          zkHosts = List(new InetSocketAddress(zkHost, 2181)),
          zkSessionTimeout = 7,
          zkConnectionTimeout = 7),
      callBack = callback,
      persistentQueuePath = "persistent_queue_path")
    subscribeConsumer.start()
  }
} 
开发者ID:bwsw,项目名称:t-streams-pts-benchmark,代码行数:49,代码来源:SubscriberRunner.scala


示例2: TestEnv

//设置package包名称以及导入依赖的类
package tech.artemisia.core

import java.util.concurrent.locks.{ReentrantLock, Lock}
import scala.collection.mutable



object TestEnv extends Env {

  override val osUtil: OSUtil = new TestOsUtil

  class TestOsUtil extends OSUtil {

    private[this] val systemVariableMap: mutable.Map[String,String] = mutable.Map("foo" -> "bar")
    private[this] val systemPropertiesMap: mutable.Map[String,String] = mutable.Map("user.home" -> System.getProperty("user.home"))
    private[this] val lock :Lock = new ReentrantLock()

    override def getSystemVariable(variable: String): Option[String] = {
      systemVariableMap get variable
    }

    def getSystemProperties(variable: String): Option[String] = {
      systemPropertiesMap get variable
    }

    def withSysVar(map: scala.collection.Map[String,String])(body : => Unit): Unit = {
      try {
        lock.lock()
        systemVariableMap.clear()
        systemVariableMap ++= map.toSeq
        body
      }
      catch {
        case e: Throwable => throw e
      }
      finally {
        lock.unlock()
      }
    }
  }

} 
开发者ID:gitter-badger,项目名称:artemisia,代码行数:43,代码来源:TestEnv.scala


示例3: 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


示例4: lock

//设置package包名称以及导入依赖的类
package com.citypay.pan.search.util

import java.util.concurrent.locks.{Condition, ReentrantLock}

trait Lockable {

  protected val lock: ReentrantLock = new ReentrantLock(true)
  protected val cond1: Condition = lock.newCondition()

  def lock[X](func: => X): X = {
    lock.lock()
    try {
      func
    } finally {
      lock.unlock()
    }
  }

} 
开发者ID:citypay,项目名称:citypay-pan-search,代码行数:20,代码来源:Lockable.scala


示例5: Future

//设置package包名称以及导入依赖的类
package ppl.delite.runtime.messages

import java.util.concurrent.locks.ReentrantLock

class Future[T] {

  private var notReady: Boolean = true
  private var _result: T = _

  private val lock = new ReentrantLock
  private val cond = lock.newCondition

  def get: T = {
    if (notReady) block
    _result
  }

  private def block {
    val lock = this.lock
    lock.lock
    try {
      while (notReady)
        cond.await
    }
    finally {
      lock.unlock
    }
  }

  def set(result: T) {
    val lock = this.lock
    lock.lock
    try {
      _result = result
      notReady = false
      cond.signalAll
    }
    finally {
      lock.unlock
    }
  }

} 
开发者ID:leratojeffrey,项目名称:OptiSDR-Compiler,代码行数:44,代码来源:Future.scala


示例6: put

//设置package包名称以及导入依赖的类
package ppl.delite.runtime.graph.ops

import java.util.concurrent.locks.ReentrantLock
import ppl.delite.runtime.graph.targets.Targets


  private val lock = new ReentrantLock
  private val end = lock.newCondition
  private var notDone: Boolean = true
  private var result: Any = null

  def put(res: Any) {
    lock.lock
    try {
      notDone = false
      result = res
      end.signal
    }
    finally {
      lock.unlock
    }
  }

  def take(): Any = {
    var res: Any = null
    lock.lock
    try {
      while (notDone) end.await
      notDone = true //reset for re-use
      res = result
      result = null
    }
    finally {
      lock.unlock
    }
    res
  }  
}

object EOP_Kernel {

  def apply[T](): T = apply(null.asInstanceOf[T])

  def apply[T](result: T): T = {
    EOP_Global.put(result)
    result
  }

} 
开发者ID:leratojeffrey,项目名称:OptiSDR-Compiler,代码行数:50,代码来源:EOP.scala


示例7: ExampleForeachHeader

//设置package包名称以及导入依赖的类
package ppl.delite.runtime.codegen.kernels.scala.examples

import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.locks.ReentrantLock



object ExampleForeachHeader {
  def apply(in0: Array[Int], in1: Array[Double], in2: Double) = new ExampleForeachHeader(in0, in1, in2)
}

final class ExampleForeachHeader(in0: Array[Int], in1: Array[Double], in2: Double) {

  //this is the apply method of another (kernel) object: shouldn't be generated
  def kernel_apply(in0: Array[Int], in1: Array[Double], in2: Double): Foreach = {
    new Foreach {
      def in = in0
      def foreach(elem: Int) { in1(elem) = (in1(elem-1) + in1(elem) + in1(elem+1))/3 }
      def sync(idx: Int) = List(in0(idx-1), in0(idx), in0(idx+1))
    }
  }

  abstract class Foreach {
    def in: Array[Int]
    def foreach(elem: Int)
    def sync(idx: Int): List[Any]
  }

  val closure = kernel_apply(in0, in1, in2)
  val lockMap = new ConcurrentHashMap[Any, ReentrantLock]
}

object ExampleForeach {

  def apply(foreach: ExampleForeachHeader) {
    val in = foreach.closure.in
    val size = in.size
    var i = size*2/4 //size*chunkIdx/numChunks
    val end = size*3/4 //size*(chunkIdx+1)/numChunks

    while (i < end) {
      val sync = foreach.closure.sync(i).sortBy(System.identityHashCode(_)) //TODO: optimize locking mechanism
      for (e <- sync) {
        foreach.lockMap.putIfAbsent(e, new ReentrantLock)
        foreach.lockMap.get(e).lock
      }

      foreach.closure.foreach(in(i))

      for (e <- sync.reverse) {
        foreach.lockMap.get(e).unlock
      }

      i += 1
    }
  }
} 
开发者ID:leratojeffrey,项目名称:OptiSDR-Compiler,代码行数:58,代码来源:ExampleForeach.scala


示例8: TransfersService

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

import java.time.OffsetDateTime
import java.util.concurrent.locks.ReentrantLock

import com.peim.model.Transfer
import com.peim.repository.TransfersRepository
import scaldi.{Injectable, Injector}

import scala.concurrent.duration._
import scala.concurrent.{Await, ExecutionContext}
import scala.util.{Failure, Success, Try}

class TransfersService(implicit inj: Injector, executionContext: ExecutionContext) extends Injectable {

  private val createLock = new ReentrantLock()
  private val approveLock = new ReentrantLock()
  private val transfersRepository = inject[TransfersRepository]

  def createTransfer(transfer: Transfer): Try[Int] = {
    createLock.lock()
    val transferId = try {
      Await.result(transfersRepository.create(transfer), 5.seconds)
    } finally {
      createLock.unlock()
    }
    Try(transferId) match {
      case Success(newId) =>
        approveLock.lock()
        try {
          val createdTransfer = transfer.approved(newId)
          Try(Await.result(transfersRepository.approve(createdTransfer), 5.seconds))
        } finally {
          approveLock.unlock()
        }
      case Failure(error) => Failure(error)
    }
  }

  def rollbackFailedTransfers(): Runnable = new Runnable {
    override def run(): Unit = {
      transfersRepository.rollback(OffsetDateTime.now().minusSeconds(10))
    }
  }
} 
开发者ID:peim,项目名称:money-transfer-service,代码行数:46,代码来源:TransfersService.scala


示例9: Philosopher

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

import java.util.concurrent.locks.ReentrantLock

import org.junit.runner.RunWith
import org.scalatest.FunSuite
import org.scalatest.concurrent.Eventually
import org.scalatest.junit.JUnitRunner
import org.scalatest.time.{Millis, Seconds, Span}

import com.twitter.util.{Await, Promise}

class Philosopher {
  val ready = new Promise[Unit]
  private val lock = new ReentrantLock()
  def dine(neighbor: Philosopher): Unit = {
    lock.lockInterruptibly()
    ready.setValue(Unit)
    Await.ready(neighbor.ready)
    neighbor.dine(this)
    lock.unlock()
  }
}

@RunWith(classOf[JUnitRunner])
class ContentionTest extends FunSuite with Eventually {

  implicit override val patienceConfig =
    PatienceConfig(timeout = scaled(Span(15, Seconds)), interval = scaled(Span(5, Millis)))

  test("Deadlocks") {
    val c = new ContentionSnapshot()

    val descartes = new Philosopher()
    val plato = new Philosopher()

    val d = new Thread(new Runnable() {
      def run() { descartes.dine(plato) }
    })
    d.start()

    val p = new Thread(new Runnable() {
      def run() { plato.dine(descartes) }
    })
    p.start()
    Await.all(descartes.ready, plato.ready)

    eventually { assert(c.snap().deadlocks.size == 2) }
    d.interrupt()
    p.interrupt()
    p.join()
    d.join()
    assert(c.snap().deadlocks.size == 0)
  }
} 
开发者ID:lanshuijuntuan,项目名称:Java.util,代码行数:56,代码来源:ContentionTest.scala


示例10: Lock

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

import java.util.concurrent.locks.ReentrantLock

class Lock {
  private val lock: ReentrantLock = new ReentrantLock()
  def apply[T](w: =>T): T = run(w)
  def run[T](w: =>T): T = {
    lock.lock()
    try {
      return w
    } finally {
      lock.unlock()
    }
  }
}

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



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

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