java.lang.Thread.UncaughtExceptionHandler Scala Examples

The following examples show how to use java.lang.Thread.UncaughtExceptionHandler. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.
Example 1
Source File: ThreadFactoryBuilder.scala    From gfc-concurrent   with Apache License 2.0 5 votes vote down vote up
package com.gilt.gfc.concurrent

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

import com.gilt.gfc.logging.Loggable


object ThreadFactoryBuilder {
  def apply(): ThreadFactoryBuilder = ThreadFactoryBuilder(None, None, None, None, true)

  def apply(groupName: String, threadName: String): ThreadFactoryBuilder = {
    val group = ThreadGroupBuilder().withName(groupName).build()
    ThreadFactoryBuilder().withNameFormat(threadName + "-%s").withThreadGroup(group)
  }

  val LogUncaughtExceptionHandler = new Thread.UncaughtExceptionHandler with Loggable {
    override def uncaughtException(t: Thread, e: Throwable): Unit = {
      error("Failed to catch exception in thread " + t.getName(), e)
    }
  }
}

case class ThreadFactoryBuilder private (private val nameFormat: Option[String],
                                         private val priority: Option[Int],
                                         private val exceptionHandler: Option[UncaughtExceptionHandler],
                                         private val threadGroup: Option[ThreadGroup],
                                         private val daemon: Boolean) {
  def withNameFormat(nameFormat: String): ThreadFactoryBuilder = copy(nameFormat = Some(nameFormat))

  def withPriority(priority: Int): ThreadFactoryBuilder = copy(priority = Some(priority))

  def withUncaughtExceptionHandler(exceptionHandler: UncaughtExceptionHandler): ThreadFactoryBuilder = copy(exceptionHandler = Some(exceptionHandler))

  def withThreadGroup(threadGroup: ThreadGroup): ThreadFactoryBuilder = copy(threadGroup = Some(threadGroup))

  def withDaemonFlag(isDaemon: Boolean): ThreadFactoryBuilder = copy(daemon = isDaemon)

  def build(): ThreadFactory = {
    val nameF: Option[() => String] = nameFormat.map { nf =>
      val count = new AtomicLong(0)
      () => nf.format(count.getAndIncrement)
    }

    new ThreadFactory {
      override def newThread(runnable: Runnable): Thread = {
        val group = threadGroup.getOrElse(ThreadGroupBuilder.currentThreadGroup())
        val thread = new Thread(group, runnable)
        nameF.foreach(f => thread.setName(f()))
        priority.foreach(thread.setPriority)
        exceptionHandler.foreach(thread.setUncaughtExceptionHandler)
        thread.setDaemon(daemon)
        thread
      }
    }
  }
} 
Example 2
Source File: ThreadFactoryBuilderTest.scala    From gfc-concurrent   with Apache License 2.0 5 votes vote down vote up
package com.gilt.gfc.concurrent

import java.lang.Thread.UncaughtExceptionHandler
import org.scalatest.mockito.MockitoSugar
import org.scalatest.{Matchers, FunSuite}

class ThreadFactoryBuilderTest extends FunSuite with Matchers with MockitoSugar {
  test("name and groupname") {
    val f = ThreadFactoryBuilder("groupname", "name").withDaemonFlag(false).build()

    val t = f.newThread(new Runnable {
      override def run(): Unit = {}
    })
    t.getName should fullyMatch regex "name\\-\\d+"
    t.getThreadGroup.getName shouldBe "groupname"
  }

  test("All defaults") {
    val f = ThreadFactoryBuilder().build()

    val t = f.newThread(new Runnable {
      override def run(): Unit = {}
    })
    t.getName should fullyMatch regex "Thread\\-\\d+"
    t.isDaemon shouldBe true
    t.getPriority shouldBe Thread.NORM_PRIORITY
    t.getThreadGroup should be theSameInstanceAs Thread.currentThread.getThreadGroup
    t.getUncaughtExceptionHandler shouldBe Thread.currentThread.getThreadGroup
  }

  test("with...") {
    val group = new ThreadGroup("foo")
    val exh = mock[UncaughtExceptionHandler]
    val f = ThreadFactoryBuilder().
      withNameFormat("bar-%d").
      withDaemonFlag(false).
      withPriority(Thread.MIN_PRIORITY).
      withThreadGroup(group).
      withUncaughtExceptionHandler(exh).
      build

    val t = f.newThread(new Runnable {
      override def run(): Unit = {}
    })
    t.getName shouldBe "bar-0"
    t.isDaemon shouldBe false
    t.getPriority shouldBe Thread.MIN_PRIORITY
    t.getThreadGroup should be theSameInstanceAs group
    t.getUncaughtExceptionHandler shouldBe exh
  }
} 
Example 3
Source File: ThreadUtil.scala    From iotchain   with MIT License 5 votes vote down vote up
package jbok.common.thread

import java.lang.Thread.UncaughtExceptionHandler
import java.nio.channels.AsynchronousChannelGroup
import java.nio.channels.spi.AsynchronousChannelProvider
import java.util.concurrent.atomic.AtomicInteger
import java.util.concurrent.{Executors, ThreadFactory}

import cats.effect.{Resource, Sync}

import scala.concurrent.ExecutionContext
import scala.util.control.NonFatal

object ThreadUtil {
  def named(threadPrefix: String, daemon: Boolean, exitJvmOnFatalError: Boolean = true): ThreadFactory =
    new ThreadFactory {
      val defaultThreadFactory = Executors.defaultThreadFactory()
      val idx                  = new AtomicInteger(0)
      def newThread(r: Runnable) = {
        val t = defaultThreadFactory.newThread(r)
        t.setDaemon(daemon)
        t.setName(s"$threadPrefix-${idx.incrementAndGet()}")
        t.setUncaughtExceptionHandler(new UncaughtExceptionHandler {
          def uncaughtException(t: Thread, e: Throwable): Unit = {
            ExecutionContext.defaultReporter(e)
            if (exitJvmOnFatalError) {
              e match {
                case NonFatal(_) => ()
                case _           => System.exit(-1)
              }
            }
          }
        })
        t
      }
    }

  def blockingThreadPool[F[_]](name: String)(implicit F: Sync[F]): Resource[F, ExecutionContext] =
    Resource(F.delay {
      val factory  = named(name, daemon = true)
      val executor = Executors.newCachedThreadPool(factory)
      val ec       = ExecutionContext.fromExecutor(executor)
      (ec, F.delay(executor.shutdown()))
    })

  def acg[F[_]](implicit F: Sync[F]): Resource[F, AsynchronousChannelGroup] =
    Resource(F.delay {
      val acg = acgUnsafe
      (acg, F.delay(acg.shutdownNow()))
    })

  def acgUnsafe: AsynchronousChannelGroup =
    AsynchronousChannelProvider
      .provider()
      .openAsynchronousChannelGroup(8, named("jbok-ag-tcp", daemon = true))

  lazy val acgGlobal: AsynchronousChannelGroup = acgUnsafe
} 
Example 4
Source File: NamedThreadFactory.scala    From mango   with Apache License 2.0 5 votes vote down vote up
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()
  }
} 
Example 5
Source File: TestExecutorImpl.scala    From scalaprops   with MIT License 5 votes vote down vote up
package scalaprops

import scala.concurrent.{Await, ExecutionContext, Future}
import scala.concurrent.duration.Duration
import java.lang.Thread.UncaughtExceptionHandler
import sbt.testing.Logger
import java.util.concurrent.ForkJoinPool

object TestExecutorImpl {
  private[this] def newInstance(log: Logger): TestExecutor =
    new TestExecutor {
      private[this] val executionContext = {
        lazy val executorService: ForkJoinPool = new ForkJoinPool(
          sys.runtime.availableProcessors(),
          ForkJoinPool.defaultForkJoinWorkerThreadFactory,
          new UncaughtExceptionHandler {
            def uncaughtException(t: Thread, e: Throwable): Unit = {
              log.error("uncaughtException Thread = " + t)
              log.trace(e)
              e.printStackTrace()
              executorService.shutdown()
            }
          },
          false
        )
        ExecutionContext.fromExecutorService(executorService)
      }

      override def execute[A](timeout: Duration)(f: => A): A =
        Await.result(Future(f)(executionContext), timeout)

      override def shutdown(): Unit =
        executionContext.shutdown()
    }
  def withExecutor[A](logger: Logger)(f: TestExecutor => A): A = {
    val executor = newInstance(logger)
    try f(executor)
    finally executor.shutdown()
  }
} 
Example 6
Source File: ThreadUtil.scala    From almond   with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
package almond.util

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

import scala.concurrent.{ExecutionContext, ExecutionContextExecutorService}
import scala.util.control.NonFatal

object ThreadUtil {

  // From https://github.com/functional-streams-for-scala/fs2/blob/d47f903bc6bbcdd5d8bc6d573bc7cfd956f0cbb6/core/jvm/src/main/scala/fs2/Strategy.scala#L19-L41
  
  def daemonThreadFactory(threadName: String, exitJvmOnFatalError: Boolean = true): ThreadFactory = new ThreadFactory {
    val defaultThreadFactory = Executors.defaultThreadFactory()
    val idx = new AtomicInteger(0)
    def newThread(r: Runnable) = {
      val t = defaultThreadFactory.newThread(r)
      t.setDaemon(true)
      t.setName(s"$threadName-${idx.incrementAndGet()}")
      t.setUncaughtExceptionHandler(new UncaughtExceptionHandler {
        def uncaughtException(t: Thread, e: Throwable): Unit = {
          System.err.println(s"------------ UNHANDLED EXCEPTION ---------- (${t.getName})")
          e.printStackTrace(System.err)
          if (exitJvmOnFatalError) {
            e match {
              case NonFatal(_) => ()
              case fatal => System.exit(-1)
            }
          }
        }
      })
      t
    }
  }

  def sequentialExecutionContext(): ExecutionContext =
    new SequentialExecutionContext

  def singleThreadedExecutionContext(threadName: String): ExecutionContext =
    ExecutionContext.fromExecutorService(
      Executors.newSingleThreadExecutor(daemonThreadFactory(threadName))
    )

  def attemptShutdownExecutionContext(ec: ExecutionContext): Boolean =
    ec match {
      case _: SequentialExecutionContext =>
        true
      case es: ExecutionContextExecutorService =>
        es.shutdown()
        true
      case _ =>
        false
    }

} 
Example 7
Source File: CancellableFuturePool.scala    From almond   with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
package almond.interpreter.util

import java.lang.Thread.UncaughtExceptionHandler
import java.util.concurrent.{Executors, ThreadFactory}

import almond.logger.LoggerContext

import scala.concurrent.{Future, Promise}
import scala.util.control.NonFatal
import scala.util.{Failure, Success}

final class CancellableFuturePool(
  logCtx: LoggerContext
) {

  private val log = logCtx(getClass)

  private val pool = Executors.newCachedThreadPool(
    // from scalaz.concurrent.Strategy.DefaultDaemonThreadFactory
    new ThreadFactory {
      val defaultThreadFactory = Executors.defaultThreadFactory()
      def newThread(r: Runnable) = {
        val t = defaultThreadFactory.newThread(r)
        t.setDaemon(true)
        t.setUncaughtExceptionHandler(
          new UncaughtExceptionHandler {
            def uncaughtException(t: Thread, e: Throwable) =
              log.warn(s"Uncaught exception in thread $t", e)
          }
        )
        t
      }
    }
  )

  def future[T](result: => T): Future[T] = {

    val p = Promise[T]()

    pool.submit(
      new Runnable {
        def run() =
          p.complete {
            try Success(result)
            catch {
              case NonFatal(e) =>
                Failure(e)
            }
          }
      }
    )

    p.future
  }

  def cancellableFuture[T](result: T): CancellableFuture[T] = {

    @volatile var completionThreadOpt = Option.empty[Thread]

    def result0(): T = {
      completionThreadOpt = Some(Thread.currentThread())
      try result
      finally {
        completionThreadOpt = None
      }
    }

    def cancel(): Unit =
      for (t <- completionThreadOpt)
        t.stop()

    CancellableFuture(future(result0()), () => cancel())
  }

  def shutdown(): Unit =
    pool.shutdown()

}