Advertisement
codeuniv

ThreadLocal

Jan 1st, 2019
159
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.21 KB | None | 0 0
  1. import java.util.concurrent.ExecutorService;
  2. import java.util.concurrent.Executors;
  3.  
  4. class MyRunnable implements Runnable {
  5.  
  6.     private static final ThreadLocal<Integer> thrLoc1 = new ThreadLocal<Integer>() {
  7.         @Override
  8.         protected Integer initialValue() {
  9.             return new Integer(777);
  10.         }
  11.     };
  12.  
  13.     // same as lambda arg: Supplier<T>, T get()
  14.     private static final ThreadLocal<Integer> thrLoc2 = ThreadLocal.withInitial(() -> 777);
  15.  
  16.     @Override
  17.     public void run() {
  18.         thrLoc1.set(thrLoc1.get() + 1); // increment Integer (ThreadLocal var)
  19.         System.out.println(thrLoc1.get());
  20.         System.out.println(thrLoc2.get());
  21.         thrLoc2.set(111);
  22.         System.out.println(thrLoc2.get());
  23.         thrLoc1.remove();
  24.         thrLoc2.remove();   // prevents memory leak
  25.     }
  26. }
  27.  
  28. public class Driver {
  29.  
  30.     public static void main(String[] args) {
  31.  
  32.         // USING EXECUTOR FRAMEWORK LIKE BELOW NOT RECOMMENDED!
  33.         // USE Thread t = new Thread(Runnable), t.start
  34.         ExecutorService es1 = Executors.newSingleThreadExecutor();
  35.         ExecutorService es2 = Executors.newSingleThreadExecutor();
  36.         Runnable r = new MyRunnable();
  37.  
  38.         es1.submit(new MyRunnable());
  39.         es2.submit(new MyRunnable());
  40.     }
  41. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement