Thread Continue - 3

zhaozj2021-02-16  72

Listing 4. Manage each-threaded registration log public class debuglogger {private static class threadlocallist extends threadlocal {public object initialValue () {return new arraylist ();

Public List getList () {return (list) super.get ();}}

Private threadlocallist list = new threadlocallist (); private static string [] stringArray = new string [0];

Public void clear () {list.getlist (). clear ();

Public void put (string text) {list.getlist (). Add (text);

Public string [] get () {return list.getlist (). Toarray (StringArray);}}

In your code, you can call DEBUGLGGER.PUT () to save what you are doing, and if necessary (for example, an error happens), you can easily retrieve with a specific thread Related debugging information. With you dump all information to a log file, then try to find out which thread comes from which thread comes from (also worried about the log record object), this technology is much easier and more effective.

ThreadLocal is also useful in any multi-threaded application server based on servlet-based applications or work units because a single thread will be used during the entire process of processing requests. You can store all-request context messages through the threadlocal variables described earlier.

Threadlocal's thread security is a little brother, inheritablethreadlocalthreadlocal class has a relative, inheritablethreadlocal, working in a similar manner, but applies to applications that are completely different. If you save a thread, if you save the value of all InheritableThreadLocal objects, then these values ​​will also be passed to the sub-thread. If a sub-thread calls incheritablethreadLocal's get (), it will see the same object with its parent thread. To protect thread safety, you should only use InheritableThreadLocal only for non-variable objects (once created, it will never be changed) because the object is shared by multiple threads. InheritableThreadLocal is suitable for transmitting data from the parent threads to sub-threads, such as user IDs, or transaction IDs, but cannot be status objects, such as JDBC Connection.

转载请注明原文地址:https://www.9cbs.com/read-16412.html

New Post(0)