ThreadLocal and object reuse
Everyone knows that Java's memory management mechanism is done by the garbage collector, which is mainly to travel to each thread reference. This method is more in a language compared to Perl, etc. Complex, more computational volume. Due to this mechanism, it has also caused the memory waste (not leak) in Java-in-style style (not leak). For example, a large number of local Object variables creation, when is it to be used, a new one. This is certainly uncomfortable, but high efficiency, uninterrupted, requires reducing the number of garbage collection is very meaningful for some specific real-time systems. Object reuse is a good solution.
Here we do not introduce the relative complex object reuse mechanism of the object pool, such as Jakarta Object Pool. Instead, a very simple reuse method is introduced. The idea of this method is only one thing, that is, every thread has an example for each of the objects that need to be reused. The benefits are: 1, less object, the number of objects of each class is the same as the number of threads. 2, no synchronization, no efficiency problem. The means of achieving is very simple, that is, using the Threadlocal class. The Threadlocal class guarantees that each thread has a different instance, and the same thread must be the same instance. This is a simple reuse object factory that I wrote. For StringBuffer, List and other commonly used temporary variable types, you can directly use the getObject method to get the instance in this lever, and then call clear () or other methods to initialize it. . However, it must be noted that this Object must be temporary, and its survival does not exceed its definitions, and must not be placed in a global data structure or container.