Thread Confinement

后端 未结 8 641
生来不讨喜
生来不讨喜 2020-12-02 14:43

I am reading Java Concurrency in Practice and kind of confused with the thread confinement concept. The book says that

When an object is confined to a

8条回答
  •  [愿得一人]
    2020-12-02 15:00

    One way is "stack confinement" in which the object is a local variable confined to the thread's stack, so no other thread can access it. In the method below, the list is a local variable and doesn't escape from the method. The list doesn't have to be threadsafe because it is confined to the executing thread's stack. No other thread can modify it.

    public String foo(Item i, Item j){
        List list = new ArrayList();
        list.add(i);
        list.add(j);
        return list.toString();
    }
    

    Another way of confining an object to a thread is through the use of a ThreadLocal variable which allows each thread to have its own copy. In the example below, each thread will have its own DateFormat object and so you don't need to worry about the fact that DateFormat is not thread-safe because it won't be accessed by multiple threads.

    private static final ThreadLocal df
                     = new ThreadLocal(){
        @Override
        protected DateFormat initialValue() {
            return new SimpleDateFormat("yyyyMMdd");
        }
      };
    

    Further Reading

提交回复
热议问题