Skip to content

Commit

Permalink
Performance optimizations
Browse files Browse the repository at this point in the history
  • Loading branch information
darkfrog26 committed Dec 6, 2024
1 parent 115b372 commit 850272b
Show file tree
Hide file tree
Showing 3 changed files with 13 additions and 21 deletions.
4 changes: 2 additions & 2 deletions benchmark/src/main/scala/benchmark/ManyTasksBenchmark.scala
Original file line number Diff line number Diff line change
Expand Up @@ -37,9 +37,9 @@ class ManyTasksBenchmark {
@Benchmark
def zioBenchmark(): Unit = {
val completed = new AtomicInteger(0)
val runtime = Runtime.default
(1 to tasks).foreach { _ =>
val zio = ZIO.succeed(simpleComputation).map(_ => completed.incrementAndGet())
val runtime = Runtime.default
val zio = ZIO.succeedBlocking(simpleComputation).map(_ => completed.incrementAndGet())
Unsafe.unsafe(implicit u => runtime.unsafe.fork(zio))
}
waitForComplete(completed)
Expand Down
27 changes: 9 additions & 18 deletions core/src/main/scala/rapid/Fiber.scala
Original file line number Diff line number Diff line change
Expand Up @@ -2,40 +2,31 @@ package rapid

import java.util.concurrent.atomic.AtomicLong
import scala.concurrent.duration._
import scala.util.{Failure, Success, Try}

class Fiber[Return](val task: Task[Return]) extends Task[Return] {
private var result: Either[Throwable, Return] = _
private val thread = Thread
.ofVirtual()
.name(s"rapid-${Fiber.counter.incrementAndGet()}")
.start(() => try {
result = Right(task.sync())
} catch {
case t: Throwable => result = Left(t)
})
private var result: Try[Return] = _

private val thread = Thread.startVirtualThread(() => {
result = Try(task.sync())
})

override protected def invoke(): Return = await()

override def start(): Fiber[Return] = this

override def await(): Return = {
thread.join()
result match {
case Left(t) => throw t
case Right(r) => r
}
result.get
}

override def attempt(): Either[Throwable, Return] = {
override def attempt(): Try[Return] = {
thread.join()
result
}

def await(duration: Duration): Option[Return] = if (thread.join(java.time.Duration.ofMillis(duration.toMillis))) {
result match {
case Left(t) => throw t
case Right(r) => Some(r)
}
Some(result.get)
} else {
None
}
Expand Down
3 changes: 2 additions & 1 deletion core/src/main/scala/rapid/Task.scala
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package rapid

import scala.concurrent.duration.FiniteDuration
import scala.util.Try

/**
* Represents a task that can be executed to produce a result of type `Return`.
Expand Down Expand Up @@ -43,7 +44,7 @@ trait Task[Return] extends Any {
*
* @return either the result of the task or an exception
*/
def attempt(): Either[Throwable, Return] = start().attempt()
def attempt(): Try[Return] = start().attempt()

/**
* Transforms the result of the task using the given function.
Expand Down

0 comments on commit 850272b

Please sign in to comment.