reactor / reactor-core

Non-Blocking Reactive Foundation for the JVM

Home Page:http://projectreactor.io

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

context lost when using Mono.create with threads

weditor opened this issue · comments

Steps to Reproduce

val CTX = ThreadLocal.withInitial { "init" }

fun printCtx(tag: String) {
    println("context=${CTX.get()} at $tag")
}

fun main() {
    ContextRegistry.getInstance().registerThreadLocalAccessor("myctx", CTX)
    Hooks.enableAutomaticContextPropagation()

    CTX.set("hello")
    // here, the sink.success executed in an other thread
    val mono1 = Mono.create { sink -> thread { sink.success(1) } }
        .doOnSubscribe { printCtx("subscribe1") }
        .doOnNext { printCtx("next1") }
        .doOnSuccess { printCtx("success1") }
    val mono2 = Mono.just(2)
        .doOnSubscribe { printCtx("subscribe2") }
        .doOnNext { printCtx("next2") }
        .doOnSuccess { printCtx("success2") }
    val result = Flux.concat(mono1, mono2).collectList().contextCapture().block()
    println("finish, result=$result")
}

Expected Behavior

CTX.get() always hello in doOnSubscribe doOnNext doOnSuccess:

context=hello at subscribe1
context=hello at next1
context=hello at success1
context=hello at subscribe2
context=hello at next2
context=hello at success2
finish, result=[1, 2]

Actual Behavior

it output:

context=hello at subscribe1
context=init at next1
context=init at success1
context=init at subscribe2
context=init at next2
context=init at success2
finish, result=[1, 2]

Possible Solution

Your Environment

  • Reactor version(s) used: io.projectreactor:reactor-core:3.5.14
  • Other relevant libraries versions (eg. netty, ...): io.micrometer:context-propagation:1.0.5
  • JVM version (java -version): jdk11
  • OS and version (eg uname -a): windows10

I tested on reactor-core:3.6.4, It seems the bug has fixed in the newest version.

I noticed that version 5. x is currently under maintenance, so I'm not sure if this bug should also be fixed in version 5.3.14

Hey, @weditor!

This behaviour change in 3.6.x is a significant enhancement that was introduced as part of last year's GA release. We also posted a brief blog post entry that explains it: https://spring.io/blog/2023/10/31/what-new-is-coming-in-reactor-core-3-6-0#better-automatic-context-propagation

It will not be back-ported to 3.5.x as it is not considered a bug but an enhancement to a feature that was progressively being enhanced over the 3.5.x line starting from 3.5.3.