Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
3 changed files
with
43 additions
and
0 deletions.
There are no files selected for viewing
30 changes: 30 additions & 0 deletions
30
core/src/main/scala-3/com/github/skozlov/commons/scala/concurrent/lock/Condition.scala
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,30 @@ | ||
package com.github.skozlov.commons.scala.concurrent.lock | ||
|
||
import com.github.skozlov.commons.scala.time.Deadline | ||
|
||
import java.util.concurrent.TimeoutException | ||
import java.util.concurrent.locks.Condition | ||
import scala.annotation.tailrec | ||
|
||
extension (condition: Condition) { | ||
def awaitUninterruptibly(exitCondition: () => Boolean): Unit = { | ||
while (!exitCondition()) { | ||
condition.awaitUninterruptibly() | ||
} | ||
} | ||
|
||
@throws[InterruptedException] | ||
@throws[TimeoutException] | ||
@tailrec | ||
def await(exitCondition: () => Boolean)(implicit deadline: Deadline): Unit = { | ||
if (!exitCondition()) { | ||
if deadline.isOver then throw new TimeoutException(s"Condition was never true before $deadline") | ||
if (deadline == Deadline.Inf) { | ||
condition.await() | ||
} else { | ||
condition.awaitNanos(deadline.toTimeout.toNanos) | ||
} | ||
await(exitCondition)(deadline) | ||
} | ||
} | ||
} |
11 changes: 11 additions & 0 deletions
11
core/src/main/scala-3/com/github/skozlov/commons/scala/concurrent/lock/SafeCondition.scala
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,11 @@ | ||
package com.github.skozlov.commons.scala.concurrent.lock | ||
|
||
import com.github.skozlov.commons.scala.time.Deadline | ||
|
||
import java.util.concurrent.locks.Condition | ||
|
||
case class SafeCondition(unsafe: Condition) { | ||
def await(exitCondition: () => Boolean)(implicit deadline: Deadline): Unit = unsafe.await(exitCondition)(deadline) | ||
|
||
def signalAll(): Unit = unsafe.signalAll() | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters