Skip to content

Commit

Permalink
Added the 'join()' method on the Job class and added more tests
Browse files Browse the repository at this point in the history
  • Loading branch information
rcardin committed May 24, 2024
1 parent ec87580 commit 545682a
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 2 deletions.
8 changes: 8 additions & 0 deletions core/src/main/scala/in/rcard/sus4s/sus4s.scala
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,14 @@ object sus4s {
private val executingThread: CompletableFuture[Thread]
) {
def value: A = cf.get()
def join(): Unit =
cf.handle((_, throwable) => {
throwable match {
case null => ()
case _: InterruptedException => ()
case _ => throw throwable
}
})
def cancel(): Unit = {
executingThread.get().interrupt()
cf.completeExceptionally(new InterruptedException("Job cancelled"))
Expand Down
49 changes: 47 additions & 2 deletions core/src/test/scala/StructuredSpec.scala
Original file line number Diff line number Diff line change
Expand Up @@ -120,13 +120,12 @@ class StructuredSpec extends AnyFlatSpec with Matchers {
results.toArray should contain theSameElementsInOrderAs List("3", "2", "1")
}

it should "cancel at the first suspending point" in {
"cancellation" should "cancel at the first suspending point" in {
val queue = new ConcurrentLinkedQueue[String]()
val result = structured {
val cancellable = fork {
while (true) {
Thread.sleep(2000)
println("cancellable job")
queue.add("cancellable")
}
}
Expand All @@ -138,8 +137,54 @@ class StructuredSpec extends AnyFlatSpec with Matchers {
}
job.value
}
}

it should "not throw an exception if joined" in {
val queue = new ConcurrentLinkedQueue[String]()
val result = structured {
val cancellable = fork {
while (true) {
Thread.sleep(2000)
queue.add("cancellable")
}
}
val job = fork {
Thread.sleep(500)
cancellable.cancel()
queue.add("job2")
43
}
cancellable.join()
job.value
}
queue.toArray should contain theSameElementsInOrderAs List("job2")
result shouldBe 43
}

it should "not cancel parent job" in {
val queue = new ConcurrentLinkedQueue[String]()
val result = structured {
val job1 = fork {
val innerCancellableJob = fork {
while (true) {
Thread.sleep(2000)
queue.add("cancellable")
}
}
Thread.sleep(1000)
innerCancellableJob.cancel()
queue.add("job1")
}
val job = fork {
Thread.sleep(500)
queue.add("job2")
43
}
job.value
}
queue.toArray should contain theSameElementsInOrderAs List("job2", "job1")
result shouldBe 43
}


}

0 comments on commit 545682a

Please sign in to comment.