<rt id="bn8ez"></rt>
<label id="bn8ez"></label>

  • <span id="bn8ez"></span>

    <label id="bn8ez"><meter id="bn8ez"></meter></label>

    Chan Chen Coding...

    Understand TheadLocal

    Core concept of ThreadLocal is, “every thread that accesses a ThreadLocal variable via its get or set method has its own, independently initialized copy of the variable”. In this tutorial we will learn about ThreadLocal.
    ThreadLocal Introduction
    We want to have separate instances(private copy) of a class so that there will not be any conflict among multiple threads. Each instance will be unique for each thread. This is nothing but a way of implementing threadsafety.
    An important point about ThreadLocal variable is the global access. It can be accessed from anywhere inside the thread. Also note that, it is declared static and final.
    What is threadsafe?
    A thread is a single line of process. When we refer multi-threaded applications, we mean that there mulitple (sequential flow of control) line of process that runs through the same lines of code. In such situation, there is a possibility of one sequence(thread) accessing/modifying data of other sequence(thread). When data cannot be shared like this, then we make it threadsafe. Following are the some of the different ways of implementing threadsafe operation:
    1. Re-entrancy
    2. Mutual exclusion (synchronization)
    3. Thread-local
    4. Atomic operation
    So, in the above list Thread-local is one option. Hope now we get how ThreadLocal fits in the cube.
    Uses of ThreadLocal
    1. Genuine per-thread context, such as user id or transaction id. Works great. Easy to clean up when the thread exits the scope. No leaks.
    2. Per-thread instances for performance.
    3. “Sleazing” values through callbacks that you don’t control: sometimes you must call a library method that calls back into your package. At this point, you need some context that you were unable to pass to yourself, due to deficiencies in the library. In this rare situation, thread locals can be a lifesaver.
    Above points, in my own terms: We have an object that is not threadsafe and we want to use it safely. We go for synchronization by enclosing that object in synchronized block. Other way around is using ThreadSafe, what it does is holds separate instance for each thread and makes it safe.
     
    import java.text.SimpleDateFormat;
    import java.util.Date;
     
    public class ThreadLocalExample {
      private static final ThreadLocal formatter = new ThreadLocal() {
     
        protected SimpleDateFormat initialValue() {
          return new SimpleDateFormat("yyyyMMdd HHmm");
        }
      };
     
      public String formatIt(Date date) {
        return formatter.get().format(date);
      }
    }
    In the above sample code, get() method is key to understanding. It returns the value in the current thread’s copy of this thread-local variable. If the variable has no value for the current thread, it is first initialized to the value returned by an invocation of the initialValue method.
    Example from javadoc
    The class below generates unique identifiers local to each thread. A thread’s id is assigned the first time it invokes ThreadId.get() and remains unchanged on subsequent calls.
    import java.util.concurrent.atomic.AtomicInteger;
     
    public class ThreadId {
        // Atomic integer containing the next thread ID to be assigned
        private static final AtomicInteger nextId = new AtomicInteger(0);
     
        // Thread local variable containing each thread's ID
        private static final ThreadLocal threadId =
            new ThreadLocal() {
                @Override protected Integer initialValue() {
                    return nextId.getAndIncrement();
            }
        };
     
        // Returns the current thread's unique ID, assigning it if necessary
        public static int get() {
            return threadId.get();
        }
    }

    Use of ThreadLocal in Java API
    In JDK 1.7 we have got a new class namely ThreadLocalRandom. It can be used to generate random numbers specific to parallel threads. Seed for random number will be unique for each thread. This is a real cool utility.
    Following is the code that implements ThreadLocal in the above class:
    private static final ThreadLocal localRandom =
        new ThreadLocal() {
            protected ThreadLocalRandom initialValue() {
                return new ThreadLocalRandom();
            }
    };
    Example using ThreadLocalRandom
     
    import java.util.concurrent.ThreadLocalRandom;
     
    public class ThreadLocalRandomExample {
     
      public static void main(String args[]) throws InterruptedException {
     
        //tossing 3 coins
        for (int i = 0; i < 3; i++) {
          final Thread thread = new Thread() {
     
            public void run() {
              System.out.print(Thread.currentThread().getName() + ":");
     
              // generating 3 random numbers - random for every thread
              for (int j = 0; j < 3; j++) {
                final int random = ThreadLocalRandom.current().nextInt(
                    1, 3);
                System.out.print(random + ",");
              }
              System.out.println();
            }
          };
          thread.start();
          thread.join();
        }
      }
    }


    -----------------------------------------------------
    Silence, the way to avoid many problems;
    Smile, the way to solve many problems;

    posted on 2012-11-23 11:24 Chan Chen 閱讀(615) 評(píng)論(0)  編輯  收藏 所屬分類: Scala / Java

    主站蜘蛛池模板: 久久久久亚洲av成人无码电影 | 中文字幕无码视频手机免费看| 国产亚洲精品免费视频播放| 国产大片免费天天看| 亚洲人成影院在线无码观看| 免费国产va视频永久在线观看| 亚洲成年人啊啊aa在线观看| 欧洲美女大片免费播放器视频| 亚洲AⅤ永久无码精品AA| 一级毛片在线免费播放| 亚洲中文字幕久久精品无码喷水 | 亚洲午夜未满十八勿入| 91精品免费观看| 亚洲国产成a人v在线观看| 成人免费a级毛片| 精品国产亚洲AV麻豆| 亚洲欧洲自拍拍偷精品 美利坚| 国产一级婬片A视频免费观看| 亚洲av永久无码精品漫画| 5g影院5g天天爽永久免费影院| 亚洲无砖砖区免费| 免费看的黄色大片| 一级**爱片免费视频| 亚洲伦另类中文字幕| 毛片a级毛片免费观看品善网| 久久亚洲精品无码网站| 久久久久亚洲AV成人网人人网站 | 国产91在线|亚洲| 久久久精品国产亚洲成人满18免费网站| 成在线人视频免费视频| 亚洲午夜精品在线| 国产乱子伦精品免费女| 国产免费AV片在线观看| 亚洲人成色在线观看| 亚洲日韩中文字幕在线播放| 日韩在线播放全免费| 无码AV动漫精品一区二区免费| 亚洲精品国产成人99久久| 国产无遮挡吃胸膜奶免费看视频| 精品一区二区三区高清免费观看| 亚洲第一二三四区|