Skip to content

Instantly share code, notes, and snippets.

@gorshkov-leonid
Last active August 19, 2025 11:28
Show Gist options
  • Select an option

  • Save gorshkov-leonid/43780f8ad2963ddc267753608e82ea59 to your computer and use it in GitHub Desktop.

Select an option

Save gorshkov-leonid/43780f8ad2963ddc267753608e82ea59 to your computer and use it in GitHub Desktop.
package com.netcracker.dstud.servicepackage.service.specification;

import java.util.concurrent.*;
import java.util.function.*;

public class M
{
    public static void main(String[] args)
    {
        ThreadLocal<Object> tl = new ThreadLocal<>();
        tl.set(1);
        CompletableFuture.supplyAsync(contextualize1(tl, tl.get())).thenApplyAsync(contextualize2(tl, tl.get()));
    }

    private static Supplier<Integer> contextualize1(ThreadLocal<Object> tl, Object precTlValue)
    {
        return () -> {
            Object o = tl.get();
            tl.set(precTlValue);
            try{
                int i = 2;
                return i;
            }
            finally
            {
                tl.set(o);;
            }
        };
    }

    private static Function<Integer, Integer> contextualize2(ThreadLocal<Object> tl, Object precTlValue)
    {
        return integer -> {
            Object o = tl.get();
            tl.set(precTlValue);
            try{
                int i = 3;
                return i;
            }
            finally
            {
                tl.set(o);;
            }
        };
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment