`

Thread Local usage

阅读更多

ThreadLocal usage – from Javadoc

This class provides thread-local variables. These variables differ from their normal counterparts in that each thread that accesses one (via its get or set method) has its own, independently initialized copy of the variable. ThreadLocal instances are typically private static fields in classes that wish to associate state with a thread (e.g., a user ID or Transaction ID).

For example, in the class below, the private static ThreadLocal instance (serialNum) maintains a "serial number" for each thread that invokes the class's static SerialNum.get() method, which returns the current thread's serial number. (A thread's serial number is assigned the first time it invokes SerialNum.get(), and remains unchanged on subsequent calls.)

 

 

 public class SerialNum {
     // The next serial number to be assigned
     private static int nextSerialNum = 0;
 
     private static ThreadLocal serialNum = new ThreadLocal() {
// Tom’s comments: This initialValue must be override, 
//telling ThreadLocal object, what value to return when he’s called get()
              protected synchronized Object initialValue() {
             return new Integer(nextSerialNum++);
         }
     };
 
     public static int get() {
         return ((Integer) (serialNum.get())).intValue();
     }
 }

 

 

 

Each thread holds an implicit reference to its copy of a thread-local variable as long as the thread is alive and the ThreadLocal instance is accessible; after a thread goes away, all of its copies of thread-local instances are subject to garbage collection (unless other references to these copies exist).

 

ThreadLocal usage – from Thinking In Java

 

ThreadLocal objects are usually stored as static fields. When you create a ThreadLocal object, you are only able to access the contents of the object using the get() and set() methods.

 

get() method returns a copy of the object that is associated with that thread.

 

set() inserts its argument into the object stored for that thread, returning the old object that was in storage.

 

This example is better than the example above. ThreadLocal is really declared as generic.

 

 private static ThreadLocal<Integer> value = new ThreadLocal<Integer>

  {

     private Random rand = new Random(47);

     protected synchronized Integer initialValue()

     {

         return rand.nextInt(10000);

     }

  };

分享到:
评论

相关推荐

    Java.Threads.and.the.Concurrency.Utilities.1484216997

    How to apply thread usage in Swing, JavaFX, and Java 8 Streams API contexts Who this book is for The primary audience is Java beginners and the secondary audience is more advanced Java developers who ...

    ModernGadgets_1.6.3.rmskin

    - Line graph displays CPU temperature**, per-thread CPU usage, RAM usage, and Page file usage - Optional average CPU usage graph display - Opens task manager on double-click - Able to be scaled to ...

    alien_8.79.tar.gz

    Writing /usr/local/lib/perl5/site_perl/5.10.0/i386-linux-thread-multi/auto/Alien/.packlist install -d /usr/local/share/alien/patches \ /var/lib/alien Appending installation info to /usr/lib/perl5/...

    海洋环流数值模式POP的GPU并行优化.pdf

    4. **减少局部内存使用(Reducing Local Memory Usage)**:通过优化数据结构和算法,降低对局部内存的依赖,使得更多数据可以驻留在速度快的寄存器中,提高数据重用度。 5. **增加GPU端代码执行(Increasing Code ...

    CUDA_C_Programming_Guide

    CUDA supports multiple levels of memory, each with different characteristics and usage scenarios: - **Global Memory**: Located on the GPU and accessible by all threads. It has the largest capacity ...

    JProfiler Helper

    It provides developers with a detailed analysis of their Java programs' performance, enabling them to identify bottlenecks, optimize memory usage, and enhance overall application efficiency....

    C#实现的windows 服务,还实现了服务的安装,卸载

    processInstaller.Account = ServiceAccount.LocalSystem; serviceInstaller.StartType = ServiceStartMode.Automatic; serviceInstaller.ServiceName = "SystemMonitor"; this.Installers.Add...

    微软内部资料-SQL性能优化2

    The Windows 2000 cache manager provides data caching for both local and network file system drivers. By caching virtual blocks, the cache manager can reduce disk I/O and provide intelligent read ahead...

    apktool documentation

    -advance / --advanced will launch advance parameters and information on the usage output -m / --match-original is a new feature for apk analysis. This retains the apk is nearly original format, but ...

    AkkaScala.pdf

    - **Cluster Usage:** Akka Cluster usage involves configuring cluster nodes, managing member discovery, and coordinating cluster-wide operations. - **Cluster Singleton:** Akka Cluster Singleton ensures...

    Development.apk(Android Dev Tools)

    5.9 show cpu usage(显示CPU的进程) 5.10 show sleep state on LED(再LED上显示睡眠时间) 5.11 window animation scale 1x(窗口动画规模1X) 5.12 transition animation scale 1x(转换动画模式1X) 5.13 Light Hinting...

    EurekaLog_7.5.0.0_Enterprise

    7)....Added: Streaming unpacked debug info into temporal files instead of memory - this greatly reduces run-time application memory usage at cost of slightly slower exception processing. This also ...

    UNIX Network Programming Volume 1, Third Edition (Unix网络编程卷1第3版英文版)

    Protocol Usage by Common Internet Applications Section 2.14. Summary Exercises Part 2: Elementary Sockets Chapter 3. Sockets Introduction Section 3.1. Introduction Section 3.2. Socket...

    acpi控制笔记本风扇转速

    Ported the -g option (get local ACPI tables) to the new ACPICA Table Manager to restore original behavior. ---------------------------------------- 27 September 2006. Summary of changes for version ...

    python3.6.5参考手册 chm

    PEP 495: Local Time Disambiguation PEP 529: Change Windows filesystem encoding to UTF-8 PEP 528: Change Windows console encoding to UTF-8 PEP 520: Preserving Class Attribute Definition Order PEP ...

    8192CU LINUX驱动

    * if not set we'll use function local variable (stack memory) */ //#define CONFIG_USB_VENDOR_REQ_BUFFER_DYNAMIC_ALLOCATE #define CONFIG_USB_VENDOR_REQ_BUFFER_PREALLOC #define CONFIG_USB_VENDOR_REQ_...

    Sakemail

    1997 - 2003 Sergio A....and fixed it. Some minor bugs that I don‘t remember fixed.- Added MIME-compliant base64 support (not for use by now). Added examples.0.9.2.1b- Fixed a bug when send a mail and ...

    SimIt-ARM-3.0 ARM指令模拟器

    usage : ema [-h] [-d] [-v] [-m num] [-s config] [&lt;file name&gt; ] -h : print this message and quit -d : debuging mode -v : verbose mode -m num : maximum number of instructions to simulate, in million...

    vxworks_kernel_programmers_guide_6.9

    PART I: CORE TECHNOLOGIES 1 Overview ...................................................................................................... 3 1.1 Introduction ............................................

Global site tag (gtag.js) - Google Analytics