5 Replies Latest reply: May 15, 2007 5:53 AM by 807606 RSS

    Yet another ThreadLocal....

    807606
      Hi people,

      first of all sorry for asking this question again, that has been answered so many times.

      But something I dont undestand is that if one wants to keep a different object value per thread, why not just use private objects instead??

      Wouldn't that be simpler??? I know I would have as many private objects as the number of running threads, but apart from that, I can't seem to find any benefits of using it??

      Can you guys guide me here ;)

      Many thanks,

      MeTitus
        • 1. Re: Yet another ThreadLocal....
          807606
          Suppose your application has a stateless Singleton, for example a DateFormat, that you use for parsing and formatting. Then you decide to make your application multithreaded and your read in the API for the DateFormat class, "Date formats are not synchronized. It is recommended to create separate format instances for each thread. " The usual thing here is to use ThreadLocal. Yes, you could define:
          class MyThread extends Thread {
              private DateFormat format;
          
              ...
          }
          //or 
          class MyRunnable implements Runnable {
              private DateFormat format;
          
              ...
          }
          But in some frameworks, you don't define the Thread classes/Runnables in client code -- think of servlets, for example.
          • 2. Re: Yet another ThreadLocal....
            807606
            It is recommended to create separate format instances for each thread
            This exacly what I would do, or I could synchronize the methods that would access the DataFormat class as well.
            I just don't see how could ThreadLocal help in this case, if anything it does is keep a copy of the object value to each thread.

            MeTitus
            • 3. Re: Yet another ThreadLocal....
              807606
              Well I could something like this:
                   private static ThreadLocal<DataFormat> instance = new ThreadLocal<Database>();
              I guess so,

              Thanks Hippolyte

              MeTitus
              • 4. Re: Yet another ThreadLocal....
                807606
                I could synchronize the methods that would access the DataFormat class aswell.
                Synchronizing on a single instance creates a bottleneck. If you're willing to
                do this, why have threads at all?
                • 5. Re: Yet another ThreadLocal....
                  807606
                  Yes its a good point ;)

                  MeTitus