开发者

get and initialValues method of ThreadLocal synchronized

开发者 https://www.devze.com 2023-04-08 06:15 出处:网络
I came across a code where the get() and initialValue() methods of Th开发者_如何学GoreadLocal is synchronized.

I came across a code where the get() and initialValue() methods of Th开发者_如何学GoreadLocal is synchronized.

I couldn't find any use of having these methods synchronized. Correct me if I am wrong.

-Krishna.


I was investigating the same usage of synchronized on ThreadLocal initialValue(). Fakrudeen's answer includes a link to a Java 1.5 defect in which the synchronized keyword was the work around for multiple objects being created. It was fixed in Java 1.6

If you run this test (taken from the Fakrudeen's link) in Java 1.5 and compare your results to a later version, you will see that in versions 1.6 and later that synchronized is not necessary.

---------- BEGIN SOURCE ---------- import java.util.ArrayList;

public class ThreadLocalBug { static int COUNT = 8;

static ThreadLocal tl = new ThreadLocal() {
    protected Object initialValue() {
        System.err.println("initialValue called");
        ArrayList list = new ArrayList(COUNT);
        for (int i = 0; i < COUNT; i++) {
            MyThreadLocal mtl = new MyThreadLocal();
            mtl.get();
            list.add(mtl);
        }
        return list;
    }
};

public static void main(String[] args) throws Throwable {
    Object first = tl.get();
    Object second = tl.get();
    Object third = tl.get();
    System.err.println("first=" + first);
    System.err.println("second=" + second);
    System.err.println("second=" + third);
}

static class MyThreadLocal extends ThreadLocal {
    protected Object initialValue() {
        return Boolean.TRUE;
    }
}

}

---------- END SOURCE ----------

(I would have added this as a comment to Fakrudeen's answer, but I don't have enough points :-) )


It may be useful due to this bug:

https://bugs.openjdk.java.net/browse/JDK-6550283?page=com.atlassian.streams.streams-jira-plugin:activity-stream-issue-tab


No, that's completely pointless, and was likely written by someone who didn't know what they were doing.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号