Skip to content

Instantly share code, notes, and snippets.

@ffissore
Created October 29, 2018 16:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ffissore/694f7e1772f1ff9b6ce189f7723db016 to your computer and use it in GitHub Desktop.
Save ffissore/694f7e1772f1ff9b6ce189f7723db016 to your computer and use it in GitHub Desktop.
ThreadLocal and CompletableFuture
package com.example;
import org.junit.Test;
import java.util.concurrent.CompletableFuture;
public class ThreadLocalTest {
@Test
public void name() {
ThreadLocal<Integer> threadLocal = new ThreadLocal<>();
threadLocal.set(10);
System.out.println(10);
System.out.println(Thread.currentThread());
CompletableFuture.supplyAsync(threadLocal::get)
.thenApplyAsync((i) -> {
System.out.println(Thread.currentThread());
System.out.println(i);
int value = i + 10;
threadLocal.set(value);
return value;
})
.thenAccept((i) -> {
System.out.println(i);
})
.join();
}
}
@TheKSoni
Copy link

This fails on L#20. NullPointerException as threadLocal::get returns null.
Did you share this test case just to prove failure OR it works for you?

@ffissore
Copy link
Author

Hi @TheKSoni sorry but this gist was posted 1.5 years ago, I don't even remember where. Can you remind me?

@TheKSoni
Copy link

I couldn't find it in your public repositories. I can only see it here in your gist.

@ffissore
Copy link
Author

ffissore commented Feb 17, 2020

Yeah but how come you stumbled on this gist? Is it linked in some bug report, or have you just googled?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment