How to clean up ThreadLocals

前端 未结 7 1691
遇见更好的自我
遇见更好的自我 2020-11-28 23:01

Does any one have an example how to do this? Are they handled by the garbage collector? I\'m using Tomcat 6.

7条回答
  •  迷失自我
    2020-11-28 23:36

    The JVM would automatically clean-up all the reference-less objects that are within the ThreadLocal object.

    Another way to clean up those objects (say for example, these objects could be all the thread unsafe objects that exist around) is to put them inside some Object Holder class, which basically holds it and you can override the finalize method to clean the object that reside within it. Again it depends on the Garbage Collector and its policies, when it would invoke the finalize method.

    Here is a code sample:

    public class MyObjectHolder {
    
        private MyObject myObject;
    
        public MyObjectHolder(MyObject myObj) {
            myObject = myObj;
        }
    
        public MyObject getMyObject() {
            return myObject;
        }
    
        protected void finalize() throws Throwable {
            myObject.cleanItUp();
        }
    }
    
    public class SomeOtherClass {
        static ThreadLocal threadLocal = new ThreadLocal();
        .
        .
        .
    }
    

提交回复
热议问题