1 Reply Latest reply on Nov 17, 2002 3:50 PM by Adrian Brock

    static initializer problem

    Steve Conover Newbie

      Hi,

      I have the following code:

      protected static ThreadLocal tl_ctx = new ThreadLocal();
      static
      {
      tl_ctx = new ThreadLocal();
      }

      at the beginning of my class. This class is used by one of my beans. In one of the methods in this class, I call

      tl_ctx.set(object);

      this of course relies on the fact that tl_ctx has been initialized. For some reason I get a nullpointerexception - it seems that the static initializer isn't running before this method gets called. Very strange behavior. Incidentally, I replaced the static initializer with the following code, which I put in the constructor:

      public MyClass()
      {
      synchronized (this)
      {
      if (tl_ctx==null)
      {
      tl_ctx = new ThreadLocal();
      }
      }
      }

      which makes it work.

      Anyone know why my static initializer isn't running? I have plenty of code similar to this which I run in a local vm, and everything initializes fine.

      Regards,
      Steve

        • 1. Re: static initializer problem
          Adrian Brock Master

          Read the ejb spec.
          Only "static final" can be used in an ejb.

          Also, you are not allowed to do anything with
          threads. This includes, threadlocal, sleep, wait,
          synchronized, new Thread(), yield, etc.

          The reason it doesn't work is because your bean is
          pooled and so are the threads. There is no guarantee
          that the same object or thread will be used in
          different method invocations.

          Regards,
          Adrian