4 Replies Latest reply on Aug 9, 2013 3:02 AM by olpf

    Deadlock in unit test initializing static member

    olpf

      Hi,

       

      I am quite new with CDI. In my junit test with CDI-unit I added a cache as static member in a dao like this:

       

      private static Map<CacheKey, Map<String, String>> CACHE = new HashMap<>();

       

      This leads to a deadlock when I execute the test.

       

      If I init the cache like this:

       

      @PostConstruct

                public void afterInjection()

                {

                               CACHE = new HashMap<>();

        }

       

      There is no deadlock. I am using weld 2.0.2.Final in the test.

      Does anyone know the reason?

       

      Cheers

      Oliver

        • 1. Re: Deadlock in unit test initializing static member
          mkouba

          Hi Oliver,

           

          could you describe your test and dead lock symptoms more thoroughly? E.g. what is the scope of the bean with the static member? BTW I don't think it's a good idea to place a static member on a bean class. Also it's not synchronized so that it's not thread-safe...

          • 2. Re: Deadlock in unit test initializing static member
            olpf

            Hi Martin,

             

            Symptoms are that the junit test run hangs and newer exits. Unfortunately the information in the debugger when I suspend the thread are not useful for me. The class which is injected has no specific scope assigned. So probably it is the default scope? If I climb up the object tree a parent has @ApplicationScoped and that parent @EJB.

             

            I thought about to do it with @Singleton instead of the static members. But I synchronized the access/change of the cache with synchronized blocks...so I think it is thread safe. But the initialization of the static member takes place on class loading, I do not know but I am wondering if this seems to be a problem with weld.

             

            The cache is located inside a DAO, the DAO is accessed by a service and the service is injected in a junt 4 test.

            • 3. Re: Deadlock in unit test initializing static member
              mkouba

              Hm, that's weird. I'll try to dig deeper. Anyway @javax.ejb.EJB and @javax.ejb.Singleton are not CDI scopes. @javax.ejb.EJB is used to inject EJBs. @javax.ejb.Singleton denotes a singleton session bean.

              • 4. Re: Deadlock in unit test initializing static member
                olpf

                Ok. Thank you. I realized the cache now as @Singleton annotated class instead of a static member. I know that annotation mention are no scopes. But I think the annotation singleton is more sexy than static members