Java threadlocal self-written

Source: Internet
Author: User

Import java. util. collections;
Import java. util. hashmap;
Import java. util. Map;

Public class mythreadlocal2 <t> {

Private Map <thread, T> map = collections. synchronizedmap (New hashmap <thread, T> ());

T initvalue ()
{
Return NULL;
}

Public t getvalue ()
{
Thread thread = thread. currentthread ();
T = map. Get (thread );
If (t = NULL &&! Map. containskey (thread ))
{
T = initvalue ();
Map. Put (thread, t );
}
Return T;
}

Public void setvalue (T)
{
Map. Put (thread. currentthread (), t );
}

}


Import java. Io. ioexception;
Import java. util. Logging. filehandler;
Import java. util. Logging. level;
Import java. util. Logging. Logger;

Public class simplethreadloger {

Private Static mythreadlocal2 <logger> local2 = new mythreadlocal2 <logger> (){
Logger initvalue (){
Logger logger = logger. getlogger (thread. currentthread (). getname ());
Try {
Logger. addhandler (New filehandler (thread. currentthread ()
. Getname () + ". log "));
} Catch (securityexception e ){
// Todo auto-generated Catch Block
E. printstacktrace ();
} Catch (ioexception e ){
// Todo auto-generated Catch Block
E. printstacktrace ();
}
Return logger;
};
};

Private Static logger getlogger (){
Return local2.getvalue ();
}

Public static void setlogger (logger ){
Local2.setvalue (logger );
}

Public static void log (string name ){
Getlogger (). Log (level. info, name );
}
}


Public class testlogger {

Public static void main (string [] ARGs ){
For (INT I = 0; I <1000000; I ++ ){
Thread thread = new loggerthread ();
Thread. Start ();
}
}

Static class loggerthread extends thread {
Int number = 100;

@ Override
Public void run (){
// Todo auto-generated method stub

Super. Run ();

Simplethreadloger. Log (getname () + "message ");
Simplethreadloger. setlogger (null );

}
}
}

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.