Skip to content

Instantly share code, notes, and snippets.

@russwyte
Created May 27, 2022 16:44
Show Gist options
  • Save russwyte/c3054bac7bad4c136cef2ed13cda1267 to your computer and use it in GitHub Desktop.
Save russwyte/c3054bac7bad4c136cef2ed13cda1267 to your computer and use it in GitHub Desktop.
Trying to use a custom blocking executor
import zio.*
import zio.Executor
import java.util.concurrent.atomic.AtomicInteger
import java.util.concurrent._
object CustomizedRuntimeZIOApp extends ZIOAppDefault {
class NamedThreadFactory(name: String, daemon: Boolean)
extends ThreadFactory {
private val parentGroup = Thread.currentThread.getThreadGroup
private val threadGroup = new ThreadGroup(parentGroup, name)
private val threadCount = new AtomicInteger(1)
override def newThread(r: Runnable): Thread = {
val newThreadNumber = threadCount.getAndIncrement()
val thread = new Thread(threadGroup, r)
thread.setName(s"$name-$newThreadNumber")
thread.setDaemon(daemon)
thread
}
}
val myAppLogic =
for n <- ZIO.foreach(1 to 1000) { n =>
io(n)
}
yield n
def io(n: Int) =
ZIO
.succeed(zio.internal.OneShot.make[Unit])
.flatMap { oneShot =>
val x = 10 * n
ZIO
.foreachPar((1 to x).toList) { i =>
val res =
if (i == x)
ZIO
.succeed {
oneShot.set(())
oneShot.get()
}
else {
ZIO.succeed(oneShot.get())
}
res
.debug(Thread.currentThread().getName)
}
}
.head
.debug(Thread.currentThread().getName)
val bigBlockingExecutor = Runtime.setBlockingExecutor(
Executor.fromThreadPoolExecutor(_ => Int.MaxValue)(
ThreadPoolExecutor(
5000,
Int.MaxValue,
30,
TimeUnit.SECONDS,
new LinkedBlockingQueue[Runnable](),
new NamedThreadFactory("big-blocking-executor", false)
)
)
)
def run = myAppLogic.provideLayer(bigBlockingExecutor)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment