πŸ• Reading time: 2 minutes

A few days ago I came across the boundedElastic() method. I explored it a bit and a little pill came out of it – it had been a while since I'd written one!

πŸ“Œ The experiment

The code below sets out to check the thread behaviour in two distinct cases:

  1. the "default" execution of a Mono (without specifying a scheduler)
  2. the execution of a Mono with explicit use of the Schedulers.boundedElastic() scheduler
@Slf4j
@SuppressWarnings("squid:S3577")
class SampleTest013 {

    private static final Consumer<String> logThreadName = threadName -> log.info("threadName: {}", threadName);

    @Test
    void test_defaultMonoExecutionRunsOnMainThread() {
        final String threadName = Mono.fromCallable(() -> Thread.currentThread().getName())
                .doOnNext(logThreadName)
                .block();
        assertEquals("main", threadName);
    }

    @Test
    void test_monoExecutionRunsOnBoundedElasticThread_whenUsingSubscribeOn() {
        final String threadName = Mono.fromCallable(() -> Thread.currentThread().getName())
                .doOnNext(logThreadName)
                .subscribeOn(Schedulers.boundedElastic())
                .block();
        assertNotNull(threadName);
        assertTrue(threadName.startsWith("boundedElastic-"));
    }
}

πŸ“‘ Analysis of the 1st test – defaultMonoExecutionRunsOnMainThread()

A Mono is created that returns the name of the current thread. Since no scheduler is specified, the code runs on the calling thread, which in a JUnit test is the main thread. This shows that, by default, a Mono runs on the same thread that subscribes to it, if you don't specify a scheduler.

πŸ“‘ Analysis of the 2nd test – monoExecutionRunsOnBoundedElasticThread()

The Mono is identical, but .subscribeOn(Schedulers.boundedElastic()) is added. This changes the behaviour: execution is moved onto one of the boundedElastic pool's threads, thanks to subscribeOn(...). It's a scheduler suited to blocking or slow operations, such as file or database access. Using subscribeOn(...) changes the thread the Mono runs on, letting you decouple the logic from the current thread!

See you at the next pill! β˜•