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


Scala Promise类代码示例

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


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

示例1: FutureUtils

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

import java.util.concurrent.Executor

import scala.concurrent.{ExecutionContext, Future, Promise}
import scala.util.Try


object FutureUtils {

  import com.google.common.util.concurrent.{ListenableFuture => GuavaFuture}

  def toFuture[T](f: GuavaFuture[T])(implicit executor: ExecutionContext): Future[T] = {
    val pr = Promise[T]()
    f.addListener(new Runnable {
      def run() = pr.complete(Try(f.get()))
    }, executor match {
      case e: Executor => e
      case _ => new ExecutionContextExecutor(executor)
    })

    pr.future
  }

  def toFutureUnit[T](f: GuavaFuture[T])(implicit executor: ExecutionContext): Future[Unit] = {
    val pr = Promise[Unit]()
    f.addListener(new Runnable {
      def run() = pr.complete(Try(f.get()))
    }, executor match {
      case e: Executor => e
      case _ => new ExecutionContextExecutor(executor)
    })

    pr.future
  }

  private class ExecutionContextExecutor(executonContext: ExecutionContext) extends java.util.concurrent.Executor {
    def execute(command: Runnable): Unit = executonContext.execute(command)
  }

} 
开发者ID:DmytroOrlov,项目名称:devgym,代码行数:42,代码来源:FutureUtils.scala

示例2: NanoboardPow

//设置package包名称以及导入依赖的类
package com.karasiq.nanoboard.captcha

import java.util.concurrent.{Executors, RejectedExecutionException}

import akka.util.ByteString
import com.karasiq.nanoboard.NanoboardMessage
import com.karasiq.nanoboard.encoding.NanoboardCrypto.{BCDigestOps, sha256}
import com.typesafe.config.{Config, ConfigFactory}
import org.bouncycastle.crypto.digests.SHA256Digest

import scala.concurrent.{ExecutionContext, Future, Promise}
import scala.util.Random

object NanoboardPow {
  
  def calculate(message: ByteString): Future[ByteString] = {
    val preHashed = sha256.updated(message)
    val result = Promise[ByteString]

    def submitTasks(): Unit = {
      try {
        Future.sequence(for (_ ? 0 to 100) yield Future {
          val array = Array.ofDim[Byte](NanoboardMessage.POW_LENGTH)
          Random.nextBytes(array)
          val data = ByteString(array)
          if (verify(data, new SHA256Digest(preHashed))) {
            result.success(data)
          }
        }).foreach { _ ?
          if (!result.isCompleted) {
            submitTasks()
          }
        }
      } catch {
        case _: RejectedExecutionException ?
          // Pass

        case e: Throwable ?
          result.failure(e)
      }
    }

    submitTasks()
    result.future
  }
} 
开发者ID:Karasiq,项目名称:nanoboard,代码行数:47,代码来源:NanoboardPow.scala

示例3: TcpAssociationHandle

//设置package包名称以及导入依赖的类
package akka.remote.transport.netty

import akka.actor.Address
import akka.remote.transport.AssociationHandle
import akka.remote.transport.AssociationHandle.{ HandleEvent, HandleEventListener, Disassociated, InboundPayload }
import akka.remote.transport.Transport.AssociationEventListener
import akka.util.ByteString
import java.net.InetSocketAddress
import org.jboss.netty.buffer.{ ChannelBuffers, ChannelBuffer }
import org.jboss.netty.channel._
import scala.concurrent.{ Future, Promise }
import scala.util.{ Success, Failure }


private[remote] class TcpAssociationHandle(val localAddress: Address,
                                           val remoteAddress: Address,
                                           val transport: NettyTransport,
                                           private val channel: Channel)
  extends AssociationHandle {
  import transport.executionContext

  override val readHandlerPromise: Promise[HandleEventListener] = Promise()

  override def write(payload: ByteString): Boolean =
    if (channel.isWritable && channel.isOpen) {
      channel.write(ChannelBuffers.wrappedBuffer(payload.asByteBuffer))
      true
    } else false

  override def disassociate(): Unit = NettyTransport.gracefulClose(channel)
} 
开发者ID:love1314sea,项目名称:akka-2.3.16,代码行数:32,代码来源:TcpSupport.scala

示例4: BlockingIO

//设置package包名称以及导入依赖的类
package walfie.gbf.raidfinder.util

import java.util.concurrent.atomic.AtomicLong
import java.util.concurrent.{Executors, ThreadFactory}
import scala.concurrent.{ExecutionContext, ExecutionContextExecutor, Future, Promise, blocking}
import scala.util.control.NonFatal
import monix.execution.Scheduler

// https://github.com/alexandru/scala-best-practices/blob/master/sections/4-concurrency-parallelism.md
object BlockingIO {
  private val ioThreadPool = Scheduler.io(name = "io-thread")

  def future[T](t: => T): Future[T] = {
    val p = Promise[T]()

    val runnable = new Runnable {
      def run() = try {
        p.success(blocking(t))
      } catch {
        case NonFatal(ex) => p.failure(ex)
      }
    }

    ioThreadPool.execute(runnable)

    p.future
  }
} 
开发者ID:walfie,项目名称:gbf-raidfinder,代码行数:29,代码来源:BlockingIO.scala

示例5: GuavaFutures

//设置package包名称以及导入依赖的类
package akka.stream.alpakka.cassandra

import com.google.common.util.concurrent.{FutureCallback, Futures, ListenableFuture}

import scala.concurrent.{Future, Promise}

private[cassandra] object GuavaFutures {
  implicit final class GuavaFutureOpts[A](val guavaFut: ListenableFuture[A]) extends AnyVal {
    def asScala(): Future[A] = {
      val p = Promise[A]()
      val callback = new FutureCallback[A] {
        override def onSuccess(a: A): Unit = p.success(a)
        override def onFailure(err: Throwable): Unit = p.failure(err)
      }
      Futures.addCallback(guavaFut, callback)
      p.future
    }
  }
} 
开发者ID:akka,项目名称:alpakka,代码行数:20,代码来源:GuavaFutures.scala

示例6: Helpers

//设置package包名称以及导入依赖的类
package com.github.mmolimar.vkitm.utils

import java.util.Properties
import java.util.concurrent.{CancellationException, TimeUnit, Future => JFuture}

import com.typesafe.config.Config
import org.jboss.netty.util.{HashedWheelTimer, Timeout, TimerTask}

import scala.concurrent.{Future, Promise}
import scala.util.Try

object Helpers {

  private val pollIntervalMs = 50L
  private val timer = new HashedWheelTimer(pollIntervalMs, TimeUnit.MILLISECONDS)

  implicit class JFutureHelpers[T](jf: JFuture[T]) {
    def asScala: Future[T] = {
      val promise = Promise[T]()

      def checkCompletion(): Unit = {
        if (jf.isCancelled) {
          promise.failure(new CancellationException())
        } else if (jf.isDone) {
          promise.complete(Try(jf.get))
        } else {
          scheduleTimeout()
        }
        ()
      }

      def scheduleTimeout(): Unit = {
        timer.newTimeout(new TimerTask {
          override def run(timeout: Timeout): Unit = checkCompletion()
        }, pollIntervalMs, TimeUnit.MILLISECONDS)
        ()
      }

      checkCompletion()
      promise.future
    }
  }

  implicit def propsFromConfig(config: Config): Properties = {
    import scala.collection.JavaConversions._

    val props = new Properties()

    val map: Map[String, Object] = config.entrySet().map({ entry =>
      entry.getKey -> entry.getValue.unwrapped()
    })(collection.breakOut)

    props.putAll(map)
    props
  }

} 
开发者ID:mmolimar,项目名称:vkitm,代码行数:58,代码来源:Helpers.scala

示例7: Parallel_fibo

//设置package包名称以及导入依赖的类
import scala.concurrent.{Await, Future, Promise}
import scala.concurrent.duration._
import scala.concurrent.ExecutionContext.Implicits.global


object Parallel_fibo
{
  def fibonacci(n: Int): Int =
    if (n < 2) 1
    else fibonacci(n - 1) + fibonacci(n - 2)

  def parallel_fibonacci(n: Int): Int =
    if (n < 2) 1
    
    else 
    {
      //Future runs algorithms concurrently. It returns at some point. Promise gurantees that it returns. 
      //Future starts running concurrently when you create it. 
      val f1 = Future { fibonacci(n - 1) }
      val f2 = Future { fibonacci(n - 2) }

      //Promise makes sure the result is returned. 
      val sum = Promise[Int]
      f1 onSuccess {
        case a =>
          f2 onSuccess {
            case b =>
            //If both of the cases are successful. Compute the sum. 
              sum.success(a + b)
          }
      }
      //Await the result. Duration is infinite
      Await.result(sum.future, Duration.Inf)
  }

  def time[R](block: => R): R = {  
        val t0 = System.nanoTime()
        val result = block    // call-by-name
        val t1 = System.nanoTime()
        println("Elapsed time: " + (t1 - t0) + "ns")
        result
  }

  def main(args: Array[String]): Unit = {
    val res = time {(parallel_fibonacci(10))}
    println(res)

    val runtime = Runtime.getRuntime
    println("** Used Memory in Parallel_fibo.scala:  " + (runtime.totalMemory - runtime.freeMemory))
  }
} 
开发者ID:vinzee,项目名称:language_comparison,代码行数:52,代码来源:Parallel_fibo.scala

示例8: Last

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

import knot.core.Collector

import scala.concurrent.{Future, Promise}

case class Last[T]() extends Collector[T, Future[T]] {

  private[this] var prev: T = null.asInstanceOf[T]
  private[this] val promise: Promise[T] = Promise()

  override def collect(): Future[T] = promise.future

  override def onUpstreamComplete(): Unit = {
    val result = prev
    prev = null.asInstanceOf[T]
    promise.trySuccess(result)
    context.complete()
  }

  override def onUpstreamError(cause: Throwable): Unit = {
    prev = null.asInstanceOf[T]
    promise.tryFailure(cause)
    context.error(cause)
  }

  override def onNext(element: T): Unit = {
    prev = element
  }
} 
开发者ID:defvar,项目名称:knot,代码行数:31,代码来源:Last.scala

示例9: RecursiveLeastSquaresStage

//设置package包名称以及导入依赖的类
package pl.gosub.akka.online.recursive.least.squares

import akka.Done
import akka.stream._
import akka.stream.stage._

import scala.concurrent.{Future, Promise}

class RecursiveLeastSquaresStage(val rls: RecursiveLeastSquresFilter)
  extends GraphStageWithMaterializedValue[FanInShape2[Double, Double, Double], Future[Done]] {

    // Stage syntax
    val dataIn: Inlet[Double] = Inlet("RecursiveLeastSquaresStage.dataIn")
    val resultsIn: Inlet[Double] = Inlet("RecursiveLeastSquaresStage.resultsIn")
    val predictionsOut: Outlet[Double] = Outlet("RecursiveLeastSquaresStage.predictionsOut")

    override val shape: FanInShape2[Double, Double, Double] = new FanInShape2(dataIn, resultsIn, predictionsOut)

    // Stage semantics
    override def createLogicAndMaterializedValue(inheritedAttributes: Attributes) = {
      // Completion notification
      val p: Promise[Done] = Promise()

      val logic = new GraphStageLogic(shape) {

        setHandler(resultsIn, new InHandler {
          @scala.throws[Exception](classOf[Exception])
          override def onPush(): Unit = {
            val nextResult = grab(resultsIn)
            read(dataIn)({ x =>
              if (isAvailable(predictionsOut)) push(predictionsOut, rls.predict(x, nextResult))
            }, () => {})
          }
        })

        setHandler(dataIn, new InHandler {
          override def onPush(): Unit = {
            val x = grab(dataIn)
            read(resultsIn)({previousResult =>
              if (isAvailable(predictionsOut)) push(predictionsOut, rls.predict(x, previousResult))
            }, () => {})
          }

          override def onUpstreamFinish(): Unit = {
            completeStage()
          }
        })

        setHandler(predictionsOut, new OutHandler {
          override def onPull(): Unit = {
            pull(dataIn)
          }
        })
      }

      (logic, p.future)
    }
  } 
开发者ID:gosubpl,项目名称:akka-online,代码行数:59,代码来源:RecursiveLeastSquaresStage.scala

示例10: FollowTheLeaderStage

//设置package包名称以及导入依赖的类
package pl.gosub.akka.online.follow.the.leader

import akka.Done
import akka.stream.stage.{GraphStageLogic, GraphStageWithMaterializedValue, InHandler, OutHandler}
import akka.stream.{Attributes, FanInShape2, Inlet, Outlet}

import scala.concurrent.{Future, Promise}

class FollowTheLeaderStage(private val ftl: FollowTheLeaderLogic) extends GraphStageWithMaterializedValue[FanInShape2[Double, Double, Double], Future[Done]]{

  // Stage syntax
  val dataIn: Inlet[Double] = Inlet("FollowTheLeaderStage.dataIn")
  val resultsIn: Inlet[Double] = Inlet("FollowTheLeaderStage.resultsIn")
  val predictionsOut: Outlet[Double] = Outlet("FollowTheLeaderStage.predictionsOut")

  override val shape: FanInShape2[Double, Double, Double] = new FanInShape2(dataIn, resultsIn, predictionsOut)

  @scala.throws[Exception](classOf[Exception])
  override def createLogicAndMaterializedValue(inheritedAttributes: Attributes): (GraphStageLogic, Future[Done]) = {
    // Completion notification
    val p: Promise[Done] = Promise()

    val logic = new GraphStageLogic(shape) {

      setHandler(resultsIn, new InHandler {
        @scala.throws[Exception](classOf[Exception])
        override def onPush(): Unit = {
          val nextResult = grab(resultsIn)
          read(dataIn)({ x =>
            if (isAvailable(predictionsOut)) push(predictionsOut, ftl.predict(x, nextResult))
          }, () => {})
        }
      })


      setHandler(dataIn, new InHandler {
        override def onPush(): Unit = {
          val x = grab(dataIn)
          read(resultsIn)({previousResult =>
            if (isAvailable(predictionsOut)) push(predictionsOut, ftl.predict(x, previousResult))
          }, () => {})
        }

        override def onUpstreamFinish(): Unit = {
          completeStage()
        }
      })

      setHandler(predictionsOut, new OutHandler {
        override def onPull(): Unit = {
          pull(dataIn)
        }
      })
    }

    (logic, p.future)
  }
} 
开发者ID:gosubpl,项目名称:akka-online,代码行数:59,代码来源:FollowTheLeaderStage.scala

示例11: CasbahJournal

//设置package包名称以及导入依赖的类
package akka.persistence.mongo.journal

import akka.actor.{ActorSystem, ActorLogging}
import akka.persistence._
import akka.persistence.journal.AsyncWriteJournal

import com.mongodb.casbah.Imports._
import com.typesafe.config.Config

import scala.collection.immutable
import scala.concurrent.{Promise, Future}
import scala.util.{Failure, Success, Try}

private[journal] class CasbahJournal extends AsyncWriteJournal
  with CasbahJournalRoot
  with CasbahRecovery
  with ActorLogging {

  import CasbahJournalRoot._

  override val actorSystem: ActorSystem = context.system

  override val config: Config = context.system.settings.config.getConfig(configRootKey)

  implicit val concern: WriteConcern = writeConcern

  implicit val rejectNonSerializableObjects: Boolean = rejectNonSerializableObjectId

  initialize()

  def asyncWriteMessages(messages: immutable.Seq[AtomicWrite]): Future[immutable.Seq[Try[Unit]]] = {

    val messagesToTryAndPersist: immutable.Seq[Try[DBObject]] = messages.flatMap(message =>
      message.payload.map(persistentReprToDBObject))

    val persistedMessages: Future[WriteResult] =
      Future(persistExecute(mongoCollection, messagesToTryAndPersist.flatMap(_.toOption)))

    val promise = Promise[immutable.Seq[Try[Unit]]]()

    persistedMessages.onComplete {
      case Success(_) if messagesToTryAndPersist.exists(_.isFailure)  =>
        promise.success(messagesToTryAndPersist.map(_ match {
          case Success(_) => Success((): Unit)
          case Failure(error) => Failure(error)
        }))
      case Success(_) =>
        promise.complete(Success(Nil))
      case Failure(e) => promise.failure(e)
    }
    promise.future
  }

  def asyncDeleteMessagesTo(persistenceId: String, toSequenceNr: Long): Future[Unit] = {
    Future(deleteTo(mongoCollection, concern, persistenceId, toSequenceNr))
  }

  override def postStop(): Unit = {
    shutdown()
  }
} 
开发者ID:asrulsibaoel,项目名称:akka-mongo,代码行数:62,代码来源:CasbahJournal.scala

示例12: KillServiceDelegate

//设置package包名称以及导入依赖的类
package mesosphere.marathon
package core.task.termination.impl

import akka.Done
import akka.actor.ActorRef
import mesosphere.marathon.core.instance.Instance
import mesosphere.marathon.core.task.Task
import mesosphere.marathon.core.task.termination.{ KillReason, KillService }
import org.slf4j.LoggerFactory

import scala.concurrent.{ Future, Promise }
import scala.collection.immutable.Seq

private[termination] class KillServiceDelegate(actorRef: ActorRef) extends KillService {
  import KillServiceDelegate.log
  import KillServiceActor._

  override def killInstances(instances: Seq[Instance], reason: KillReason): Future[Done] = {
    log.info(
      s"Killing ${instances.size} tasks for reason: $reason (ids: {} ...)",
      instances.take(3).map(_.instanceId).mkString(","))

    val promise = Promise[Done]
    actorRef ! KillInstances(instances, promise)

    promise.future
  }

  override def killInstance(instance: Instance, reason: KillReason): Future[Done] = {
    killInstances(Seq(instance), reason)
  }

  override def killUnknownTask(taskId: Task.Id, reason: KillReason): Unit = {
    log.info(s"Killing unknown task for reason: $reason (id: {})", taskId)
    actorRef ! KillUnknownTaskById(taskId)
  }
}

object KillServiceDelegate {
  private[impl] val log = LoggerFactory.getLogger(getClass)
} 
开发者ID:xiaozai512,项目名称:marathon,代码行数:42,代码来源:KillServiceDelegate.scala

示例13: CollectionStage

//设置package包名称以及导入依赖的类
package mesosphere.marathon.stream

import akka.stream.{ Attributes, Inlet, SinkShape }
import akka.stream.stage.{ GraphStageLogic, GraphStageWithMaterializedValue, InHandler }

import scala.collection.mutable
import scala.concurrent.{ Future, Promise }


private final class CollectionStage[T, C](buf: mutable.Builder[T, C])
    extends GraphStageWithMaterializedValue[SinkShape[T], Future[C]] {
  val in = Inlet[T]("collection.in")

  override def toString: String = "collectionStage"

  override val shape: SinkShape[T] = SinkShape.of(in)

  override protected def initialAttributes: Attributes = Attributes.name("setSink")

  override def createLogicAndMaterializedValue(inheritedAttributes: Attributes): (GraphStageLogic, Future[C]) = {
    val promise = Promise[C]()
    val logic = new GraphStageLogic(shape) {

      override def preStart(): Unit = pull(in)

      setHandler(in, new InHandler {
        override def onPush(): Unit = {
          buf += grab(in)
          pull(in)
        }

        override def onUpstreamFinish(): Unit = {
          promise.trySuccess(buf.result())
          completeStage()
        }

        override def onUpstreamFailure(ex: Throwable): Unit = {
          promise.tryFailure(ex)
          failStage(ex)
        }
      })
    }
    (logic, promise.future)
  }
} 
开发者ID:xiaozai512,项目名称:marathon,代码行数:46,代码来源:CollectionStage.scala

示例14: StopActor

//设置package包名称以及导入依赖的类
package mesosphere.marathon.upgrade

import akka.actor.{ ActorLogging, Terminated, Actor, ActorRef }
import mesosphere.marathon.upgrade.DeploymentActor.Cancel
import scala.concurrent.Promise

class StopActor(toStop: ActorRef, promise: Promise[Boolean], reason: Throwable) extends Actor with ActorLogging {

  override def preStart(): Unit = {
    context.watch(toStop)
    toStop ! Cancel(reason)
  }

  def receive: Receive = {
    case Terminated(`toStop`) =>
      promise.success(true)
      log.debug(s"$toStop has successfully been stopped.")
      context.unwatch(toStop)
      context.stop(self)
  }
} 
开发者ID:xiaozai512,项目名称:marathon,代码行数:22,代码来源:StopActor.scala

示例15: StopActorTest

//设置package包名称以及导入依赖的类
package mesosphere.marathon.upgrade

import akka.actor.{ ActorRef, Props }
import akka.testkit.TestActor.{ AutoPilot, NoAutoPilot }
import akka.testkit.TestProbe
import mesosphere.marathon.test.MarathonActorSupport
import mesosphere.marathon.upgrade.DeploymentActor.Cancel
import org.scalatest.{ FunSuiteLike, Matchers }

import scala.concurrent.duration._
import scala.concurrent.{ Await, Promise }

class StopActorTest extends MarathonActorSupport with FunSuiteLike with Matchers {

  test("Stop") {
    val promise = Promise[Boolean]()
    val probe = TestProbe()

    probe.setAutoPilot(new AutoPilot {
      def run(sender: ActorRef, msg: Any): AutoPilot = msg match {
        case Cancel(reason) =>
          system.stop(probe.ref)
          NoAutoPilot
      }
    })
    val ref = system.actorOf(Props(classOf[StopActor], probe.ref, promise, new Exception))

    watch(ref)
    expectTerminated(ref)

    Await.result(promise.future, 5.seconds) should be(true)
  }
} 
开发者ID:xiaozai512,项目名称:marathon,代码行数:34,代码来源:StopActorTest.scala


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