0

I'm working with jdk7 on weblogic 11g, as I would to use ThreadLocal variable to overcome issues with SimpleDateFormat and thread safety, I also thought about potential memory leak, in case I don't remove the current value. In order to do that, I'm wondering if it's ok to add to the constructor of the object in witch I'm using this ThreadLocal (static final) instance the following lines

Runtime runtime = Runtime.getRuntime();
        runtime.addShutdownHook(new Thread(){
            @Override
            public void run() {
                dateFormat.remove();
            }
        });

or if it would be better placed in a static block (or if there is any better solution)

Raffaele
  • 461
  • 1
  • 7
  • 20
  • What is the potential memory leak you speak of? – Joni Aug 05 '20 at 23:07
  • Well, working on weblogic there will be ThreadPool managed by the container. So those threads will eventually get() their ThreadLocal value and use it. When I shutdown the application, the thread will still be there, holding a reference to the ThreadLocal value (and it will hold reference to the containing class) so this will probably cause cascading dependencies and avoid the garbage collector to claim my app objects.... – Raffaele Aug 05 '20 at 23:10
  • That's why I think my solution won't work at all...since not all thread will invoke remove for sure...so I would probably need some way to remove it when the object is collected...but I don't see how....and I'm wondering if I would need to do a remove() after every get() basically...and of course I will loose advantage of having a copy of an expensive object already loaded – Raffaele Aug 05 '20 at 23:14
  • FYI, `SimpleDateFormat` was supplanted years ago by `DateTimeFormatter`. Never use the terrible legacy date-time classes. Use only *java.time* classes. The *java.time* classes use immutable objects, and are thread-safe by design. – Basil Bourque Aug 06 '20 at 02:06
  • As I said, I'm on jdk7, that's not a choice, java.time and the improved datetimeformatter are since 1.8 – Raffaele Aug 06 '20 at 02:29

0 Answers0