本文整理汇总了Scala中java.util.concurrent.Callable类的典型用法代码示例。如果您正苦于以下问题:Scala Callable类的具体用法?Scala Callable怎么用?Scala Callable使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Callable类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Scala代码示例。
示例1: Server
//设置package包名称以及导入依赖的类
package com.scala.examples.datagurn.lesson08
import com.scala.examples.datagurn.lesson07.Teacher
import java.util.concurrent.Callable
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors
import scala.concurrent.impl.Future
import java.util.concurrent.FutureTask
import scala.concurrent.impl.Future
import com.scala.examples.datagurn.lesson07.Teacher
object Server {
// ????????????
val executorService: ExecutorService = Executors.newFixedThreadPool(10);
val teachers: List[Teacher] = List(
new Teacher("t1", 20),
new Teacher("t2", 30),
new Teacher("t1", 25),
new Teacher("t1", 21)
);
def concurrentFilterByName(name: String): FutureTask[List[Teacher]] = {
val futures = new FutureTask[List[Teacher]](new Callable[List[Teacher]]() {
def call(): List[Teacher] = {
return filterByName(name);
}
})
executorService.execute(futures);
return futures; // ?? Future
}
def filterByName(name: String) : List[Teacher] = {
teachers.synchronized {
for {
item <- teachers
if item.name == name
} yield item
}
}
def main(args: Array[String]): Unit = {
val teachers : List[Teacher] = concurrentFilterByName("t1").get
println(teachers)
executorService.shutdown();
}
}
示例2: ExecutorServiceBackboneCoordinator
//设置package包名称以及导入依赖的类
package ie.zalando.pipeline.backbone.concurrent
import java.util.concurrent.{ Callable, Future, ExecutorService }
import scala.util.Try
import scala.util.control.NonFatal
import org.slf4j.LoggerFactory
import cats.data.Xor
import ie.zalando.pipeline.backbone.Backbone
import ie.zalando.pipeline.backbone.Phases.{ LocalReleasePhase, TransformationPipelineFailure }
class ExecutorServiceBackboneCoordinator[DA](backbone: Backbone[DA], executor: ExecutorService) {
import ExecutorServiceBackboneCoordinator._
val localInitPhases = backbone.initializeTopLevelContexts
private class BackboneCallable(datum: DA) extends Callable[Xor[TransformationPipelineFailure, DA]] {
override def call(): Xor[TransformationPipelineFailure, DA] = {
val (dataPhases, releasePhases) = backbone.initializeInLocalContext(-1, localInitPhases).unzip
try {
backbone.transformDatum(backbone.createStateMonad(dataPhases), datum)
} finally {
releasePhases.foreach((phase: LocalReleasePhase) => {
Try({ phase.releaseLocalResources() }).recover { case NonFatal(ex) => log.warn(s"Release phase $phase failed:", ex) }
})
}
}
}
def process(datum: DA): Future[Xor[TransformationPipelineFailure, DA]] = {
executor.submit(new BackboneCallable(datum))
}
}
object ExecutorServiceBackboneCoordinator {
val log = LoggerFactory.getLogger(classOf[ExecutorServiceBackboneCoordinator[_]])
}
示例3: Blocking
//设置package包名称以及导入依赖的类
package org.zalando.benchmarks
import java.util.concurrent.{Callable, Executors}
import akka.actor.ActorSystem
import scala.concurrent.Await
import scala.concurrent.duration._
class Blocking(system: ActorSystem) {
import ComputationFollowedByAsyncPublishing._
def benchmark(coreFactor: Int): Unit = {
// let's do this Ye Olde Schoole Way
val exec = Executors newFixedThreadPool numWorkers(coreFactor)
try {
val futures = 1 to numTasks map Job map { job =>
exec.submit(new Callable[PublishResult] {
// explicitly turn async publishing operation into a blocking operation
override def call(): PublishResult = Await.result(Publisher publish (Computer compute job, system), 1 hour)
})
}
printResult(futures map (_.get))
} finally {
// never forget
exec.shutdown()
}
}
}
示例4: FailingKafkaStorage
//设置package包名称以及导入依赖的类
package io.amient.affinity.testutil.storage
import java.nio.ByteBuffer
import java.util.concurrent.{Callable, Executors, Future}
import com.typesafe.config.Config
import io.amient.affinity.core.storage.kafka.KafkaStorage
import org.apache.kafka.clients.producer.{ProducerRecord, RecordMetadata}
class FailingKafkaStorage(config: Config, partition: Int) extends KafkaStorage(config, partition) {
val executor = Executors.newFixedThreadPool(1)
override def write(key: ByteBuffer, value: ByteBuffer): Future[RecordMetadata] = {
val javaFuture: Future[RecordMetadata] = kafkaProducer.send(new ProducerRecord(topic, partition, key, value))
return executor.submit(new Callable[RecordMetadata]() {
override def call(): RecordMetadata = {
if (System.currentTimeMillis() % 10 == 0) {
throw new RuntimeException("Simulated Exception in FailingKafkaStorage")
} else {
javaFuture.get
}
}
})
}
}
示例5: DelegatingScheduledExecutorService
//设置package包名称以及导入依赖的类
package one.lockstep.util.concurrent
import java.util
import java.util.concurrent.{Callable, ScheduledExecutorService, ScheduledFuture}
import one.lockstep.util.japi._
import scala.concurrent.duration._
class DelegatingScheduledExecutorService(service: ScheduledExecutorService)
extends ScheduledExecutorService {
def prepareSchedule(delay: Long, unit: TimeUnit): Unit = ()
override def scheduleAtFixedRate(command: Runnable, initialDelay: Long, period: Long, unit: TimeUnit): ScheduledFuture[_] = {
prepareSchedule(List(initialDelay, period).max, unit)
service.scheduleAtFixedRate(command, initialDelay, period, unit)
}
override def schedule(command: Runnable, delay: Long, unit: TimeUnit): ScheduledFuture[_] = {
prepareSchedule(delay, unit)
service.schedule(command, delay, unit)
}
override def schedule[V](callable: Callable[V], delay: Long, unit: TimeUnit): ScheduledFuture[V] = {
prepareSchedule(delay, unit)
service.schedule(callable, delay, unit)
}
override def scheduleWithFixedDelay(command: Runnable, initialDelay: Long, delay: Long, unit: TimeUnit): ScheduledFuture[_] = {
prepareSchedule(List(initialDelay, delay).max, unit)
service.scheduleWithFixedDelay(command, initialDelay, delay, unit)
}
override def shutdown(): Unit = service.shutdown()
override def isTerminated: Boolean = service.isTerminated
override def awaitTermination(timeout: Long, unit: TimeUnit): Boolean =
service.awaitTermination(timeout, unit)
override def shutdownNow(): util.List[Runnable] = service.shutdownNow()
override def invokeAll[T](tasks: util.Collection[_ <: Callable[T]]): util.List[JFuture[T]] =
service.invokeAll(tasks)
override def invokeAll[T](tasks: util.Collection[_ <: Callable[T]], timeout: Long, unit: TimeUnit): util.List[JFuture[T]] =
service.invokeAll(tasks, timeout, unit)
override def invokeAny[T](tasks: util.Collection[_ <: Callable[T]]): T = service.invokeAny(tasks)
override def invokeAny[T](tasks: util.Collection[_ <: Callable[T]], timeout: Long, unit: TimeUnit): T =
service.invokeAny(tasks, timeout, unit)
override def isShutdown: Boolean = service.isShutdown
override def submit[T](task: Callable[T]): JFuture[T] = service.submit(task)
override def submit[T](task: Runnable, result: T): JFuture[T] = service.submit(task, result)
override def submit(task: Runnable): JFuture[_] = service.submit(task)
override def execute(command: Runnable): Unit = service.execute(command)
}
示例6: ImmediateExecutorService
//设置package包名称以及导入依赖的类
package one.lockstep.util.concurrent
import java.util.concurrent.{AbstractExecutorService, Callable, RunnableFuture}
import scala.concurrent.duration._
import one.lockstep.util.japi._
object ImmediateExecutorService extends AbstractExecutorService {
override def shutdown(): Unit = ()
override def isTerminated: Boolean = false
override def awaitTermination(timeout: Long, unit: TimeUnit): Boolean = true
override def shutdownNow(): JList[Runnable] = JCollections.emptyList()
override def isShutdown: Boolean = false
override def execute(command: Runnable): Unit = command.run()
override def newTaskFor[T](callable: Callable[T]): RunnableFuture[T] = new RunnableFuture[T] {
var result: Option[T] = None
override def run(): Unit = { result = Some(callable.call()) }
override def isCancelled: Boolean = false
override def get(): T = result.get
override def get(timeout: Long, unit: TimeUnit): T = result.get
override def cancel(mayInterruptIfRunning: Boolean): Boolean = ???
override def isDone: Boolean = result.isDefined
}
override def newTaskFor[T](runnable: Runnable, value: T): RunnableFuture[T] = new RunnableFuture[T] {
var result: Option[T] = None
override def run(): Unit = { runnable.run(); result = Some(value) }
override def isCancelled: Boolean = false
override def get(): T = result.get
override def get(timeout: Long, unit: TimeUnit): T = result.get
override def cancel(mayInterruptIfRunning: Boolean): Boolean = ???
override def isDone: Boolean = result.isDefined
}
}
示例7: FlatZincResultFormatter
//设置package包名称以及导入依赖的类
package yuck.flatzinc.runner
import java.util.concurrent.Callable
import scala.collection._
import yuck.core._
import yuck.flatzinc.ast._
import yuck.flatzinc.compiler.FlatZincCompilerResult
final class FlatZincResultFormatter(result: Result) extends Callable[Seq[String]] {
private val compilerResult = result.maybeUserData.get.asInstanceOf[FlatZincCompilerResult]
override def call = {
var sortedMap = new immutable.TreeMap[String, String]() // id -> value
for (decl <- compilerResult.ast.varDecls) {
for (annotation <- decl.annotations) {
annotation match {
case Annotation(Term("output_var", Nil)) =>
val x = compilerResult.vars(decl.id)
sortedMap = sortedMap + (decl.id -> value(x, decl).toString)
case Annotation(Term("output_array", List(ArrayConst(dimensions)))) =>
val ArrayType(Some(IntRange(1, n)), _) = decl.varType
val a =
"array%dd(%s, [%s])".format(
dimensions.size,
(for (IntSetConst(IntRange(lb, ub)) <- dimensions) yield
"%d..%d".format(lb, ub)).mkString(", "),
(for (idx <- 1 to n) yield
value(compilerResult.arrays(decl.id)(idx - 1), decl).toString).mkString(", "))
sortedMap = sortedMap + (decl.id -> a)
case _ =>
}
}
}
val lines = mutable.ArrayBuffer[String]()
for ((id, value) <- sortedMap) lines += "%s = %s;".format(id, value)
if (result.isSolution) {
lines += FLATZINC_SOLUTION_SEPARATOR
if (result.objective.isInstanceOf[HierarchicalObjective] && result.isGoodEnough) {
lines += FLATZINC_BEST_SOLUTION_FOUND_INDICATOR
}
} else {
lines += FLATZINC_NO_SOLUTION_FOUND_INDICATOR
}
lines.toSeq
}
private def value(x: AnyVariable, decl: VarDecl): AnyValue = decl.varType match {
case BoolType | ArrayType(_, BoolType) =>
if (result.bestProposal.value(IntegerValue.Traits.staticCast(x)) == Zero) True else False
case _ => result.bestProposal.anyValue(x)
}
}
示例8: StandardAnnealingScheduleFactory
//设置package包名称以及导入依赖的类
package yuck.annealing
import java.util.concurrent.Callable
import scala.collection._
import scala.math._
import yuck.core._
final class StandardAnnealingScheduleFactory
(numberOfSearchVariables: Int, randomGenerator: RandomGenerator)
extends Callable[AnnealingSchedule]
{
private val numberOfMovesPerVariableAndRound =
(numberOfSearchVariables * 256.0 / (log(numberOfSearchVariables) * log(2))).toInt
private val finalTemperature = 0.0001
private val maximumUphillAcceptanceRatio = 0.15
private val minimumUphillAcceptanceRatio = 0.0001
private val heatingRate = 1.2
private val coolingRate = 0.95
private def createAnnealingSchedule(divisor: Int): AnnealingSchedule = {
new AnnealingScheduleLoop(
new AnnealingScheduleSequence(
Vector(
new AdaptiveCoolingSchedule(
finalTemperature, minimumUphillAcceptanceRatio, coolingRate,
numberOfMovesPerVariableAndRound / divisor, 4 / divisor),
new GeometricHeatingSchedule(
maximumUphillAcceptanceRatio, heatingRate,
numberOfMovesPerVariableAndRound / divisor))),
4 / divisor)
}
override def call = {
val fastSchedule = createAnnealingSchedule(2)
val slowSchedule = createAnnealingSchedule(1)
val schedule = randomGenerator.nextInt(3) match {
case 0 => fastSchedule
case 1 => slowSchedule
case 2 => new AnnealingScheduleSequence(Vector(fastSchedule, slowSchedule))
}
def startTemperatures: Stream[Double] = Stream.cons(randomGenerator.nextProbability / 10, startTemperatures)
val startTemperature = startTemperatures.dropWhile(_ <= finalTemperature).head
schedule.start(startTemperature, 0)
schedule
}
}
示例9: ProcessRunner
//设置package包名称以及导入依赖的类
package yuck.util.testing
import scala.collection.JavaConversions
import java.util.concurrent.Callable
import yuck.util.logging.LazyLogger
class ProcessRunner(logger: LazyLogger, commandLine: Seq[String]) extends Callable[(List[String], List[String])] {
override def call = {
val processBuilder = new java.lang.ProcessBuilder(JavaConversions.seqAsJavaList(commandLine))
logger.log(JavaConversions.asScalaBuffer(processBuilder.command).toIterator.mkString(" "))
val process = processBuilder.start
val stdout = scala.io.Source.fromInputStream(process.getInputStream)
val stderr = scala.io.Source.fromInputStream(process.getErrorStream)
val outputLines = stdout.mkString.lines.toList
val (errorLines, warningLines) = stderr.mkString.lines.toList.partition(_.toLowerCase.contains("error"))
outputLines.foreach(logger.log(_))
warningLines.foreach(logger.log(_))
errorLines.foreach(logger.log(_))
(outputLines, errorLines)
}
}
示例10: withTime
//设置package包名称以及导入依赖的类
package io.github.maxkorolev.task
import java.util.concurrent.Callable
import scala.concurrent.duration.FiniteDuration
trait Task extends Callable[Any] with Serializable {
val time: Long
val timeout: FiniteDuration
def withTime(t: Long): Task = new Task {
val time: Long = t
val timeout: FiniteDuration = timeout
override def call(): AnyRef = call _
}
override def equals(any: Any): Boolean = {
any match {
case t: Task => time == t.time && timeout == t.timeout
case _ => false
}
}
override def hashCode: Int = {
val prime = 31
var result = 1
result = prime * result + time.toInt
result = prime * result + timeout.hashCode()
result
}
override def toString: String = s"Task(time: $time, timeout: ${timeout.toString})"
}
示例11: inetSocketAddress
//设置package包名称以及导入依赖的类
package com.wavesplatform
import java.net.{InetSocketAddress, SocketAddress, URI}
import java.util.concurrent.Callable
import com.wavesplatform.state2.ByteStr
import io.netty.channel.group.{ChannelGroup, ChannelMatchers}
import io.netty.channel.local.LocalAddress
import io.netty.channel.socket.SocketChannel
import io.netty.channel.{Channel, ChannelHandlerContext}
import io.netty.util.NetUtil.toSocketAddressString
import io.netty.util.concurrent.{EventExecutorGroup, ScheduledFuture}
import scorex.block.Block
import scorex.utils.ScorexLogging
import scala.concurrent.duration._
package object network extends ScorexLogging {
def inetSocketAddress(addr: String, defaultPort: Int): InetSocketAddress = {
val uri = new URI(s"node://$addr")
if (uri.getPort < 0) new InetSocketAddress(addr, defaultPort)
else new InetSocketAddress(uri.getHost, uri.getPort)
}
implicit class EventExecutorGroupExt(val e: EventExecutorGroup) extends AnyVal {
def scheduleWithFixedDelay(initialDelay: FiniteDuration, delay: FiniteDuration)(f: => Unit): ScheduledFuture[_] =
e.scheduleWithFixedDelay((() => f): Runnable, initialDelay.toNanos, delay.toNanos, NANOSECONDS)
def schedule[A](delay: FiniteDuration)(f: => A): ScheduledFuture[A] =
e.schedule((() => f): Callable[A], delay.length, delay.unit)
}
private def formatAddress(sa: SocketAddress) = sa match {
case null => ""
case l: LocalAddress => s" ${l.toString}"
case isa: InetSocketAddress => s" ${toSocketAddressString(isa)}"
}
def id(ctx: ChannelHandlerContext): String = id(ctx.channel())
def id(chan: Channel, prefix: String = ""): String = s"[$prefix${chan.id().asShortText()}${formatAddress(chan.remoteAddress())}]"
def formatBlocks(blocks: Seq[Block]): String = formatSignatures(blocks.view.map(_.uniqueId))
def formatSignatures(signatures: Seq[ByteStr]): String = if (signatures.isEmpty) ""
else if (signatures.size == 1) s"[${signatures.head}]"
else s"[${signatures.head}..${signatures.last}]"
implicit class ChannelHandlerContextExt(val ctx: ChannelHandlerContext) extends AnyVal {
def remoteAddress: InetSocketAddress = ctx.channel().asInstanceOf[SocketChannel].remoteAddress()
}
implicit class ChannelGroupExt(val allChannels: ChannelGroup) extends AnyVal {
def broadcast(message: AnyRef, except: Option[Channel] = None): Unit = {
log.trace(s"Broadcasting $message to ${allChannels.size()} channels${except.fold("")(c => s" (except ${id(c)})")}")
allChannels.writeAndFlush(message, except.fold(ChannelMatchers.all())(ChannelMatchers.isNot))
}
}
}
示例12: InputStreamingServer
//设置package包名称以及导入依赖的类
package com.bwsw.sj.engine.input.connection.tcp.server
import java.util.concurrent.{Callable, ArrayBlockingQueue}
import com.bwsw.sj.engine.core.input.InputStreamingExecutor
import io.netty.bootstrap.ServerBootstrap
import io.netty.buffer.ByteBuf
import io.netty.channel._
import io.netty.channel.nio.NioEventLoopGroup
import io.netty.channel.socket.nio.NioServerSocketChannel
import io.netty.handler.logging.{LogLevel, LoggingHandler}
import org.slf4j.LoggerFactory
import scala.collection.concurrent
class InputStreamingServer(host: String,
port: Int,
executor: InputStreamingExecutor,
channelContextQueue: ArrayBlockingQueue[ChannelHandlerContext],
bufferForEachContext: concurrent.Map[ChannelHandlerContext, ByteBuf]) extends Callable[Unit] {
private val logger = LoggerFactory.getLogger(this.getClass)
override def call() = {
logger.info(s"Launch input streaming server on: '$host:$port'\n")
val bossGroup: EventLoopGroup = new NioEventLoopGroup()
val workerGroup = new NioEventLoopGroup()
try {
val bootstrapServer = new ServerBootstrap()
bootstrapServer.group(bossGroup, workerGroup)
.channel(classOf[NioServerSocketChannel])
.handler(new LoggingHandler(LogLevel.INFO))
.childHandler(new InputStreamingChannelInitializer(executor, channelContextQueue, bufferForEachContext))
bootstrapServer.bind(host, port).sync().channel().closeFuture().sync()
} finally {
workerGroup.shutdownGracefully()
bossGroup.shutdownGracefully()
}
}
}
示例13: ArbitraryCompilationTest
//设置package包名称以及导入依赖的类
package com.avsystem.scex
package compiler
import java.util.concurrent.Callable
import java.{lang => jl, util => ju}
import org.scalatest.FunSuite
class ArbitraryCompilationTest extends FunSuite {
val compiler = new DefaultScexCompiler(new ScexSettings)
test("arbitrary source code compilation test") {
val code =
"""
|package com.avsystem.scex
|package test
|
|class Stuff extends java.util.concurrent.Callable[String] {
| def call = "stuff"
|}
|
""".stripMargin
val clazz = compiler.compileClass(code, "com.avsystem.scex.test.Stuff")
val callable = clazz.newInstance.asInstanceOf[Callable[String]]
assert("stuff" === callable.call())
}
}
示例14: MockScheduledExecutorService
//设置package包名称以及导入依赖的类
package com.twitter.jvm
import java.util.concurrent.{AbstractExecutorService, Callable, ScheduledExecutorService, ScheduledFuture, TimeUnit}
import scala.collection.mutable
// A mostly empty implementation so that we can successfully
// mock it.
class MockScheduledExecutorService extends AbstractExecutorService with ScheduledExecutorService {
val schedules = mutable.Buffer[(Runnable, Long, Long, TimeUnit)]()
def schedule[V](c: Callable[V], delay: Long, unit: TimeUnit) = throw new Exception
def schedule(command: Runnable, delay: Long, unit: TimeUnit) = throw new Exception
def scheduleWithFixedDelay(command: Runnable, initialDelay: Long, delay: Long, unit: TimeUnit) =
throw new Exception
def execute(command: Runnable) = throw new Exception
def awaitTermination(timeout: Long, unit: TimeUnit) = throw new Exception
def isTerminated() = throw new Exception
def isShutdown() = throw new Exception
def shutdownNow() = throw new Exception
def shutdown() = throw new Exception
def scheduleAtFixedRate(r: Runnable, initialDelay: Long, period: Long, unit: TimeUnit): ScheduledFuture[_] = {
schedules += ((r, initialDelay, period, unit))
null
}
}
示例15: TempFileWebCrawler
//设置package包名称以及导入依赖的类
package org.zella.web
import java.util.concurrent.Callable
import com.gargoylesoftware.htmlunit.WebClient
import com.gargoylesoftware.htmlunit.html.{HtmlAnchor, HtmlPage, HtmlSubmitInput}
import io.reactivex.Observable
class TempFileWebCrawler(webClient: WebClient) extends ITempFileWebCrawler {
override def clickButton(page: HtmlPage): HtmlPage = {
page
.getByXPath("//*[@id=\"cntMainCenterText\"]/form/table/tbody/tr/td/input[2]")
.get(0)
.asInstanceOf[HtmlSubmitInput]
.click()
.asInstanceOf[HtmlPage]
}
override def clickDownloadLink(page: HtmlPage): String = {
page
.getByXPath("//*[@id=\"cntMainCenterText\"]/center/b/a")
.get(0)
.asInstanceOf[HtmlAnchor]
.getHrefAttribute
}
override def clickButtonAsync(page: HtmlPage): Observable[HtmlPage] = {
Observable.fromCallable(new Callable[HtmlPage] {
override def call() = clickButton(page)
})
}
override def clickDownloadLinkAsync(page: HtmlPage): Observable[String] = {
Observable.fromCallable(new Callable[String] {
override def call() = clickDownloadLink(page)
})
}
}