Skip to content

Commit

Permalink
POC thread-local iolocals
Browse files Browse the repository at this point in the history
  • Loading branch information
armanbilge committed May 16, 2023
1 parent 6ffcb8e commit 0b88c01
Show file tree
Hide file tree
Showing 4 changed files with 36 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -43,4 +43,6 @@ private object IOFiberConstants {
final val CedeR = 6
final val AutoCedeR = 7
final val DoneR = 8

final val dumpLocals = false
}
2 changes: 2 additions & 0 deletions core/jvm/src/main/java/cats/effect/IOFiberConstants.java
Original file line number Diff line number Diff line change
Expand Up @@ -43,4 +43,6 @@ final class IOFiberConstants {
static final byte CedeR = 6;
static final byte AutoCedeR = 7;
static final byte DoneR = 8;

static final boolean dumpLocals = Boolean.getBoolean("cats.effect.tracing.dumpLocals");
}
11 changes: 11 additions & 0 deletions core/shared/src/main/scala/cats/effect/IOFiber.scala
Original file line number Diff line number Diff line change
Expand Up @@ -250,6 +250,12 @@ private final class IOFiber[A](
pushTracingEvent(cur.event)
}

var locals: IOLocals = null
if (dumpLocals) {
locals = new IOLocals(localState)
IOLocals.threadLocal.set(locals)
}

var error: Throwable = null
val r =
try cur.thunk()
Expand All @@ -260,6 +266,11 @@ private final class IOFiber[A](
onFatalFailure(t)
}

if (dumpLocals) {
localState = locals.getState()
IOLocals.threadLocal.set(null)
}

val next =
if (error == null) succeeded(r, 0)
else failed(error, 0)
Expand Down
21 changes: 21 additions & 0 deletions core/shared/src/main/scala/cats/effect/unsafe/IOLocals.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
package cats.effect
package unsafe

// TODO handle defaults and lenses. all do-able, just needs refactoring ...
final class IOLocals private[effect] (private[this] var state: IOLocalState) {

private[effect] def getState(): IOLocalState = state

def get[A](iol: IOLocal[A]): A = state(iol).asInstanceOf[A]

def set[A](iol: IOLocal[A], value: A): Unit = state += (iol -> value)

def reset[A](iol: IOLocal[A]): Unit = state -= iol

// TODO other ops from IOLocal

}

object IOLocals {
val threadLocal = ThreadLocal.withInitial[IOLocals](() => null)
}

0 comments on commit 0b88c01

Please sign in to comment.