建議推廣ThreadLocal在Java中的應用

來源:互聯網
上載者:User
工作要求用Java了,有很多東西要學習.不得不暫時告別一下.net

在看Spring的時候突然想到.net裡面的ThreadStaticAttribute(允許static變數在不同線程不同).
在很多情況下每個執行線程裡面的內容是固定的,比如web環境下servlet的CurrentUser/HttpContext/Session.很多情況下這些變數被想方設法的傳遞到後層類中,造成設計的複雜.

.net中很好的設計方法就是Static: Thread.CurrentPrincipal / HttpContext.Current ....

那麼Java中是否也有類似機制呢?答案是ThreadLocal.
API doc: http://java.sun.com/j2se/1.4.2/docs/api/index.html
DW上Brian Goetz 的文章:http://www-900.ibm.com/developerWorks/cn/java/j-threads/index3.shtml
Brian Goetz 在文章中指出,在jdk1.4中ThreadLocal的效能已經可以不用擔心.

在用法上比.net要複雜,API中的例子比較怪異,這裡是我自己寫的例子:public class Hello implements Runnable{
    static class Counter{
        int c = 0;
        public void Count(){
            System.out.println(Thread.currentThread().hashCode() + ": "+ c++);
        }
    }
    private static ThreadLocal counter = new ThreadLocal(){
        protected Object initialValue() {return new Counter();}
    };
    public static Counter Counter(){return (Counter)counter.get();} 
    
    public static void main(String[] args)throws Exception {
        Hello h = new Hello();
        h.run();
        new Thread(new Hello()).start();
        Thread.sleep(1000L);
        h.run();
        Counter().Count();
    }

    public void run() {
        Counter().Count();
        Counter().Count();
        Counter().Count();
    }
}

結果:25358555: 0
25358555: 1
25358555: 2
26399554: 0
26399554: 1
26399554: 2
25358555: 3
25358555: 4
25358555: 5
25358555: 6

看樣ThreadLocal工作的很好.請注意ThreadLocal類似一個訪問媒介,get()返回的值是儲存在當前線程中的.

值得注意的是InheritableThreadLocal類,可以使ThreadLocal資料傳遞到子線程中.

另外servlet線程可能會被重新利用,要注意在每個servlet開始時重新初始化.

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.