ThreadLocal for ScheduledExecutorService

Can someone tell me why threadlocal.get () gives me null when I start the thread using ScheduledExecutorService?

 public class ThreadTest extends ParentClassThread
  {
    private static ScheduledFuture<?> periodicFuture;
    private static ScheduledExecutorService ex;

    public ThreadTest(){
        ex = Executors.newSingleThreadScheduledExecutor();
        periodicFuture = ex.schedule(this, 1, TimeUnit.SECONDS);
    }

    @Override
    public void run() {
       try {
            System.out.println("Thread started");
            for (int i = 0; i <= 100000; i++) {
                System.out.println(i);
            }
            ThreadLocal local = new ThreadLocal();
            System.out.println(local.get());
        }catch(Exception e){

        }finally {
            ex.shutdown();
        }

      }
   }
+4
source share
3 answers
ThreadLocal<String> local = new ThreadLocal<String>();
local.set("String");
System.out.println(local.get());

You need to set something in ThreadLocalVariable and then extract it. ThreadLocal is initially empty.

+2
source

Because the specified ThreadLocal variable is empty. You need to either set the value or specify the initial value.

ThreadLocal<String> threadLocal = ThreadLocal.withInitial(() -> "initial value");

or

ThreadLocal<String> threadLocal = new ThreadLocal<>(); // now holding null
threadLocal.set("value"); //now holding "value"

If you have not set a value, ThreadLocal defaults to null.

+1
source

. , .set() .get() . .

+1

All Articles