ThreadLocal Java thread local variable __java

Source: Internet
Author: User
threadlocal<t> java thread Local variables

In languages such as IBM Xml,fortran, thread-local variables are provided at the syntactic level, but Java provides no such support at the syntactic level, but provides java.lang.ThreadLocal at the beginning of JDK 1.2 (and supports generics at JDK1.5 start) threadloca<t>) is used to support thread-local variables, and the Threadlocal tool class makes it simple to write multithreaded programs without having to write a large number of thread synchronization blocks like traditional methods;

Instead of a thread, Theadlocal saves the container of the thread localization object, and when an object running in a multithreaded environment uses ThreadLocal to maintain the variable, ThreadLocal assigns a copy of the variable to each thread that uses the white energy. Each thread can change its own copy independently, without affecting the copy of other threads;

interface method provided by ThreadLocal

ThreadLocal includes the following 4 interfaces, which can be implemented as part of the following interface methods when implementing a thread local variable class:

void set (Object value)

Sets the value of the local variable for the current thread

Public Object Get ()

Returns the value of the local variable for the current thread

public void Remove ()

The method to execute when the current local variable is deleted, in order to reduce memory footprint;

Public Object InitialValue ()

Returns the initial value of the local variable for the current thread;



a ThreadLocal instance

The following example uses Thradlocal to implement local variables:

public class SequenceNumber {//thread local variable, anonymous implementation InitValue () method privatestatic threadlocal<integer> seqnum = new

       Threadlocal<integer> () {public Integer InitialValue () {return 0;

    }

    };

       Publicint Getnextnum () {Seqnum.set (Seqnum.get () + 1);

    return Seqnum.get ();

       } publicstatic void Main (string[] args) {sequencenumber sn = new SequenceNumber ();

       testclient T1 = new TestClient (SN);

       TestClient t2 = new TestClient (SN);

       testclient t3 = new TestClient (SN);

       T1.start ();

       T2.start ();

    T3.start ();

       } publicstatic class TestClient extends thread{private sequencenumber SN;

       Public testclient (SequenceNumber sn) {this.sn = SN; public void Run () {for (int i=0;i<3;i++) System.out.println ("[thread-" +thread.curr

       Entthread (). GetName () + "]sn [" + sn.getnextnum () + "]"); }

    }

}


The results of the execution are as follows: Each thread produces a serial number that shares the same SequenceNumber instance, but they do not interfere with each other, but each produces separate ordinal numbers;

[thread-thread-0] SN [1] [

thread-thread-0] sn [2]

[thread-thread-0] sn [3]

[thread-thread-2] sn [1]

[ THREAD-THREAD-2] SN [2]

[thread-thread-2] sn [3]

[thread-thread-1] sn [1]

[thread-thread-1] sn [2]


comparison of synchronization mechanism between ThreadLocal and thread

For multithreading resource synchronization problem, the traditional Thread synchronization mechanism and threadlocal strategy are different;

The thread synchronization mechanism adopts the mode of "time changing Space", implements access serialization, objects sharing, multiple threads share an object, and competes for object resource in the way of thread competition;

ThreadLocal adopts the way of "space Change Time", implements access Parallelization, object exclusive, provides a copy of variable for each thread, and can access without influence.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.