Skip to content

Commit

Permalink
refactor: reduce allocations
Browse files Browse the repository at this point in the history
  • Loading branch information
tusharmath committed Jan 26, 2022
1 parent 8a9a67a commit 94e6884
Showing 1 changed file with 8 additions and 5 deletions.
13 changes: 8 additions & 5 deletions zio-http/src/main/scala/zhttp/service/HttpRuntime.scala
Original file line number Diff line number Diff line change
Expand Up @@ -14,21 +14,21 @@ import scala.jdk.CollectionConverters._
* cancel the execution when the channel closes.
*/
final class HttpRuntime[+R](strategy: HttpRuntime.Strategy[R]) {

def unsafeRun(ctx: ChannelHandlerContext)(program: ZIO[R, Throwable, Any]): Unit = {

val rtm = strategy.getRuntime(ctx)

// Close the connection if the program fails
// When connection closes, interrupt the program
def closeListener(fiber: Fiber.Runtime[_, _]): GenericFutureListener[Future[_ >: Void]] =
(_: Future[_ >: Void]) => rtm.unsafeRunAsync_(fiber.interrupt): Unit

rtm
.unsafeRunAsync(for {
fiber <- program.fork
close <- UIO(closeListener(fiber))
_ <- UIO(ctx.channel().closeFuture.addListener(close))
close <- UIO {
val close = closeListener(rtm, fiber)
ctx.channel().closeFuture.addListener(close)
close
}
_ <- fiber.join
_ <- UIO(ctx.channel().closeFuture().removeListener(close))
} yield ()) {
Expand All @@ -41,6 +41,9 @@ final class HttpRuntime[+R](strategy: HttpRuntime.Strategy[R]) {
if (ctx.channel().isOpen) ctx.close()
}
}

private def closeListener(rtm: Runtime[Any], fiber: Fiber.Runtime[_, _]): GenericFutureListener[Future[_ >: Void]] =
(_: Future[_ >: Void]) => rtm.unsafeRunAsync_(fiber.interrupt): Unit
}

object HttpRuntime {
Expand Down

1 comment on commit 94e6884

@github-actions
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🚀 Performance Benchmark:

Concurrency: 256
Requests/sec: 261493.52

Please sign in to comment.