Skip to content

Commit

Permalink
unsafeToThreadLocal() throws if propagation disabled
Browse files Browse the repository at this point in the history
  • Loading branch information
armanbilge committed Jun 4, 2024
1 parent d63a6ff commit d4549fb
Showing 1 changed file with 23 additions and 17 deletions.
40 changes: 23 additions & 17 deletions core/shared/src/main/scala/cats/effect/IOLocal.scala
Original file line number Diff line number Diff line change
Expand Up @@ -240,27 +240,33 @@ sealed trait IOLocal[A] { self =>
*/
def lens[B](get: A => B)(set: A => B => A): IOLocal[B]

def unsafeToThreadLocal(): ThreadLocal[A] = new ThreadLocal[A] {
override def get(): A = if (ioLocalPropagation) {
val fiber = IOFiber.currentIOFiber()
val state = if (fiber ne null) fiber.getLocalState() else IOLocalState.empty
self.getOrDefault(state)
} else self.getOrDefault(IOLocalState.empty)

override def set(value: A): Unit = if (ioLocalPropagation) {
val fiber = IOFiber.currentIOFiber()
if (fiber ne null) {
fiber.setLocalState(self.set(fiber.getLocalState(), value))
def unsafeToThreadLocal(): ThreadLocal[A] = if (ioLocalPropagation)
new ThreadLocal[A] {
override def get(): A = {
val fiber = IOFiber.currentIOFiber()
val state = if (fiber ne null) fiber.getLocalState() else IOLocalState.empty
self.getOrDefault(state)
}

override def set(value: A): Unit = {
val fiber = IOFiber.currentIOFiber()
if (fiber ne null) {
fiber.setLocalState(self.set(fiber.getLocalState(), value))
}
}
}

override def remove(): Unit = if (ioLocalPropagation) {
val fiber = IOFiber.currentIOFiber()
if (fiber ne null) {
fiber.setLocalState(self.reset(fiber.getLocalState()))
override def remove(): Unit = {
val fiber = IOFiber.currentIOFiber()
if (fiber ne null) {
fiber.setLocalState(self.reset(fiber.getLocalState()))
}
}
}
}
else
throw new UnsupportedOperationException(
"IOLocal-ThreadLocal propagation is disabled.\n" +
"Enable by setting cats.effect.ioLocalPropagation=true."
)

}

Expand Down

0 comments on commit d4549fb

Please sign in to comment.