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


Scala ThreadFactory类代码示例

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


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

示例1: NamedThreadFactory

//设置package包名称以及导入依赖的类
package com.kakao.mango.concurrent

import java.lang.Thread.UncaughtExceptionHandler
import java.util.concurrent.ThreadFactory

import com.kakao.shaded.guava.util.concurrent.ThreadFactoryBuilder


object NamedThreadFactory {
  def apply(prefix: String, daemon: Boolean = true): ThreadFactory = {
    new ThreadFactoryBuilder()
      .setDaemon(daemon)
      .setNameFormat(s"$prefix-%d")
      .setUncaughtExceptionHandler(new UncaughtExceptionHandler {
        override def uncaughtException(t: Thread, e: Throwable): Unit = {
          System.err.print(s"Uncaught ${e.getClass.getSimpleName} in thread ${t.getName}:")
          e.printStackTrace(System.err)
        }
      })
      .build()
  }
} 
开发者ID:kakao,项目名称:mango,代码行数:23,代码来源:NamedThreadFactory.scala

示例2: DispatcherThreadFactory

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

import java.util.concurrent.atomic.AtomicInteger
import java.util.concurrent.{ConcurrentHashMap, ThreadFactory}

object DispatcherThreadFactory {
  private val threadNumbers = new ConcurrentHashMap[String, AtomicInteger]()

  def getNewTheadNumber(prefix: String): Int = {
    threadNumbers.computeIfAbsent(prefix, _ => new AtomicInteger(1)).getAndIncrement()
  }
}

class DispatcherThreadFactory(val prefix: String) extends ThreadFactory {

  import DispatcherThreadFactory._

  override def newThread(r: Runnable): Thread = {

    val t = new Thread(r, s"knot-$prefix-${getNewTheadNumber(prefix)}")
    t.setDaemon(true)
    t.setPriority(Thread.NORM_PRIORITY)
    t
  }
} 
开发者ID:defvar,项目名称:knot,代码行数:26,代码来源:DispatcherThreadFactory.scala

示例3: NamedThreadFactory

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

import java.util.concurrent.ThreadFactory
import org.slf4j.LoggerFactory


class NamedThreadFactory(val name: String, daemon: Boolean, suppressExceptions: Boolean = false)
    extends ThreadFactory {
  private var counter = 0
  val log = LoggerFactory.getLogger(this.getClass)

  def newThread(r: Runnable) = this.synchronized {

    val thread = new Thread(r, name + "-" + counter) {
      override def run() {
        try {
          r.run()
        } catch {
          case e: Exception =>
            log.error("Unhandled exception in thread '" + getName + "'.", e)
            if (!suppressExceptions) throw e
        }
      }
    }

    counter += 1
    if (daemon)
      thread.setDaemon(true)
    thread
  }
} 
开发者ID:PagerDuty,项目名称:scala-threadpools,代码行数:32,代码来源:NamedThreadFactory.scala

示例4: ExecutionContextSchedulerTest

//设置package包名称以及导入依赖的类
package reactor.core.scala.scheduler

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

import org.scalatest.{FreeSpec, Matchers}
import reactor.core.scala.publisher.Mono
import reactor.test.StepVerifier

import scala.concurrent.ExecutionContext


class ExecutionContextSchedulerTest extends FreeSpec with Matchers {
  "ExecutionContextScheduler" - {
    "should create a Scheduler using provided ExecutionContext" in {
      val executionContext = ExecutionContext.fromExecutorService(Executors.newFixedThreadPool(1, new ThreadFactory {
        override def newThread(r: Runnable): Thread = new Thread(r, "THREAD-NAME")
      }))
      val mono = Mono.just(1)
        .subscribeOn(ExecutionContextScheduler(executionContext))
        .doOnNext(i => Thread.currentThread().getName shouldBe "THREAD-NAME")
      StepVerifier.create(mono)
        .expectNext(1)
        .verifyComplete()
    }
  }
} 
开发者ID:sinwe,项目名称:reactor-core-scala,代码行数:27,代码来源:ExecutionContextSchedulerTest.scala

示例5: NamedThreadFactory

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

import java.util.concurrent.ThreadFactory
import java.util.concurrent.atomic.AtomicInteger

object NamedThreadFactory {
  def apply(namingPolicy: Int ? String, daemon: Boolean = true): NamedThreadFactory =
    new NamedThreadFactory(namingPolicy, daemon)
}

class NamedThreadFactory(namingPolicy: Int ? String, daemon: Boolean = true) extends ThreadFactory {
  private val group: ThreadGroup = {
    val securityManager = System.getSecurityManager
    if (securityManager != null) securityManager.getThreadGroup else Thread.currentThread.getThreadGroup
  }
  private val threadNumber: AtomicInteger = new AtomicInteger(1)

  def newThread(r: Runnable): Thread = {
    val thread = new Thread(group, r, namingPolicy(threadNumber.getAndIncrement), 0)
    if (thread.isDaemon != daemon) thread.setDaemon(daemon)
    if (thread.getPriority != Thread.NORM_PRIORITY) thread.setPriority(Thread.NORM_PRIORITY)
    thread
  }
} 
开发者ID:lockstep-one,项目名称:vault,代码行数:25,代码来源:NamedThreadFactory.scala

示例6: ProxyThreadFactoryTest

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

import java.util.concurrent.ThreadFactory
import org.junit.runner.RunWith
import org.mockito.Matchers.any
import org.mockito.Mockito.verify
import org.scalatest.FunSuite
import org.scalatest.junit.JUnitRunner
import org.scalatest.mock.MockitoSugar

@RunWith(classOf[JUnitRunner])
class ProxyThreadFactoryTest extends FunSuite
  with MockitoSugar {

  private class RunnableCount extends Runnable {
    var runs = 0
    def run(): Unit =
      runs += 1
  }

  test("newProxiedRunnable") {
    var pre = 0
    var post = 0
    val mkProxy = ProxyThreadFactory.newProxiedRunnable(
      () => pre += 1,
      () => post += 1
    )

    val r = new RunnableCount()
    val newR = mkProxy(r)
    newR.run()
    assert(pre == 1)
    assert(post == 1)
    assert(r.runs == 1)
  }

  test("delegates to newRunnable and underlying ThreadFactory") {
    var created = 0
    val newR: Runnable => Runnable = { r =>
      created += 1
      r
    }

    val threadFactory = mock[ThreadFactory]
    val ptf = new ProxyThreadFactory(threadFactory, newR)

    val r = new RunnableCount()
    ptf.newThread(r)
    assert(r.runs == 0)
    assert(created == 1)
    verify(threadFactory).newThread(any())
  }

} 
开发者ID:wenkeyang,项目名称:finagle,代码行数:55,代码来源:ProxyThreadFactoryTest.scala

示例7: Blocking

//设置package包名称以及导入依赖的类
package io.gatling.keycloak

import java.util.concurrent.atomic.AtomicInteger
import java.util.concurrent.{ThreadFactory, Executors}

import io.gatling.core.validation.Success
import io.gatling.core.akka.GatlingActorSystem


object Blocking {
  GatlingActorSystem.instance.registerOnTermination(() => shutdown())

  private val threadPool = Executors.newCachedThreadPool(new ThreadFactory {
    val counter = new AtomicInteger();

    override def newThread(r: Runnable): Thread =
      new Thread(r, "blocking-thread-" + counter.incrementAndGet())
  })

  def apply(f: () => Unit) = {
    threadPool.execute(new Runnable() {
      override def run = {
        f()
      }
    })
    Success(())
  }

  def shutdown() = {
    threadPool.shutdownNow()
  }
} 
开发者ID:rvansa,项目名称:keycloak-benchmark,代码行数:33,代码来源:Blocking.scala

示例8: NamingThreadFactory

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

import java.util.concurrent.ThreadFactory
import java.util.concurrent.atomic.AtomicInteger


class NamingThreadFactory(prefix: String) extends ThreadFactory {
  private val group: ThreadGroup = {
    val s: SecurityManager = System.getSecurityManager
    if (s != null) s.getThreadGroup else Thread.currentThread.getThreadGroup
  }

  private val threadNo: AtomicInteger = new AtomicInteger(1)

  def newThread(r: Runnable) = {
    val t = new Thread(group, r, prefix + "-" + threadNo.getAndIncrement(), 0)
    if (t.isDaemon) t.setDaemon(false)
    if (t.getPriority != Thread.NORM_PRIORITY) t.setPriority(Thread.NORM_PRIORITY)
    t
  }
} 
开发者ID:AVSystem,项目名称:scex,代码行数:22,代码来源:NamingThreadFactory.scala

示例9: util

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

import java.util.Calendar
import java.util.concurrent.atomic.AtomicInteger
import java.util.concurrent.{ThreadFactory, Executors, TimeUnit, ExecutorService}

object util {
  final def addTimeStamp(str: String): String = Calendar.getInstance().getTime() + "  " + str

  def log(x: Any): Unit = println(addTimeStamp(x.toString))

  def logg(s: String)(x: Any): Unit = println(addTimeStamp(s + "\t= " + x.toString))

  final def logException(exce: Exception)(x: Any): Unit = System.err.println(addTimeStamp(x.toString + " = " + exce))

  // mod: positive remainder of division, i.e. mod(-3)(4) = 1 and mod(3)(4) = 3
  final def mod(n: Int)(m: Int): Int = ((n % m) + m) % m

  // some stuff for the executors
  final def esUnlimited: ExecutorService = Executors.newCachedThreadPool(new ThreadFactory {
    val counter = new AtomicInteger(0)

    def newThread(r: Runnable): Thread = {
      val t = new Thread(r, s"PAR-thread-${counter.getAndIncrement}")
      t.setDaemon(true)
      t
    }
  })


  final def shutExecService(debug: Boolean = false)(execService: ExecutorService): Unit = {
    if (debug) {
      logg("Shutting down now executor service")(execService.toString)
      logg(execService.toString + ".shutdown()")(execService.shutdown())
      logg(execService.toString + ".shutdownNow()")(execService.shutdownNow())
      if (!execService.awaitTermination(8, TimeUnit.SECONDS))
        logException(new Exception)("Executor Service did not terminate \n" + execService.toString)
      else logg("Executor terminated.")(execService.toString)
    }
    else {
      execService.shutdown()
      val x: java.util.List[Runnable] = execService.shutdownNow()
    }
  }
} 
开发者ID:kaelte,项目名称:playingWithScala,代码行数:46,代码来源:util.scala

示例10: NamedPoolThreadFactory

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

import java.util.concurrent.ThreadFactory
import java.util.concurrent.atomic.AtomicInteger


class NamedPoolThreadFactory(name: String, makeDaemons: Boolean) extends ThreadFactory {
  def this(name: String) = this(name, false)

  val group: ThreadGroup = new ThreadGroup(Thread.currentThread().getThreadGroup(), name)
  val threadNumber: AtomicInteger = new AtomicInteger(1)

  def newThread(r: Runnable): Thread = {
    val thread = new Thread(group, r, name + "-" + threadNumber.getAndIncrement())
    thread.setDaemon(makeDaemons)
    if (thread.getPriority != Thread.NORM_PRIORITY) {
      thread.setPriority(Thread.NORM_PRIORITY)
    }
    thread
  }
} 
开发者ID:lanshuijuntuan,项目名称:Java.util,代码行数:22,代码来源:NamedPoolThreadFactory.scala

示例11: TeleporterDispatcher

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

import java.util.concurrent.ThreadFactory

import com.typesafe.config.Config


object TeleporterDispatcher

class CacheThreadPoolExecutorConfigurator(config: Config, prerequisites: DispatcherPrerequisites) extends ExecutorServiceConfigurator(config, prerequisites) {
  def createExecutorServiceFactory(id: String, threadFactory: ThreadFactory): ExecutorServiceFactory =
    new CacheThreadPoolFactoryProvider().createExecutorServiceFactory(id, threadFactory)
}

class SizeScaleThreadPoolExecutorConfigurator(config: Config, prerequisites: DispatcherPrerequisites) extends ExecutorServiceConfigurator(config, prerequisites) {

  val sizeScaleThreadPoolConfig: SizeScaleThreadPoolConfig = createThreadPoolConfig(config.getConfig("size-scale-pool-executor"), prerequisites)

  protected def createThreadPoolConfig(config: Config, prerequisites: DispatcherPrerequisites): SizeScaleThreadPoolConfig = {
    import akka.util.Helpers.ConfigOps
    SizeScaleThreadPoolConfig(
      allowCorePoolTimeout = config getBoolean "allow-core-timeout",
      corePoolSize = ThreadPoolConfig.scaledPoolSize(config getInt "core-pool-size-min", config getDouble "core-pool-size-factor", config getInt "core-pool-size-max"),
      maxPoolSize = ThreadPoolConfig.scaledPoolSize(config getInt "max-pool-size-min", config getDouble "max-pool-size-factor", config getInt "max-pool-size-max"),
      sizeThreshold = config getInt "size-threshold",
      threadTimeout = config.getMillisDuration("keep-alive-time"),
      queueFactory = (Some(config getInt "task-queue-size") flatMap {
        case size if size > 0 ?
          Some(config getString "task-queue-type") map {
            case "array" ? ThreadPoolConfig.arrayBlockingQueue(size, fair = false) //TODO config fairness?
            case "" | "linked" ? ThreadPoolConfig.linkedBlockingQueue(size)
            case x ? throw new IllegalArgumentException("[%s] is not a valid task-queue-type [array|linked]!" format x)
          }
        case _ ? None
      }).getOrElse(ThreadPoolConfig.linkedBlockingQueue()),
      rejectionPolicy = ThreadPoolConfig.defaultRejectionPolicy
    )
  }

  def createExecutorServiceFactory(id: String, threadFactory: ThreadFactory): ExecutorServiceFactory =
    sizeScaleThreadPoolConfig.createExecutorServiceFactory(id, threadFactory)
} 
开发者ID:huanwuji,项目名称:teleporter,代码行数:43,代码来源:TeleporterDispatcher.scala

示例12: newThread

//设置package包名称以及导入依赖的类
package alexsmirnov
import java.util.concurrent.atomic.AtomicInteger
import java.util.concurrent.ThreadFactory
import org.reactivestreams._

package object stream {
  
  val streamsThreadFactory = new ThreadFactory {
        val count = new AtomicInteger
        def newThread(r: Runnable) = {
          val t = new Thread(r)
          t.setName("Stream-"+count.incrementAndGet())
          t.setDaemon(true)
          t
        }
  }
  
} 
开发者ID:alexsmirnov,项目名称:printrbot-g2-console,代码行数:19,代码来源:package.scala

示例13: DaemonThreadFactory

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

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

class DaemonThreadFactory extends ThreadFactory {
  val del = Executors.defaultThreadFactory()
  override def newThread(r: Runnable) = {
    val t = del.newThread(r)
    t.setDaemon(true)
    t
  }
}

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


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