javasingletonpicocontainer

Can PicoContainer caching be thread-safe?


Lost a bunch of time just trying to figure out what was going on here, but I think I'm finally onto something.

We have some fairly normal PicoContainer code which simply turns on caching, which I thought was supposed to result in singleton behaviour:

container.as(Characteristics.CACHE).addComponent(Service.class, ServiceImpl.class);

However as we found today, we have a component which is apparently being constructed not once, but four times. It's not something I can reproduce on my own computer, just on some other developer machines.

We investigated further, and it turns out that multiple threads were hitting PicoContainer to look up the same component at the same time, and instead of instantiating one copy and making the other three threads wait, it appears that it just instantiates four copies (and then only remembers to keep around one of them.)

Is there some relatively simple way to get true singular behaviour in PicoContainer?


Solution

  • Seems pico-container needs explicit synchronization mechanism for the case you are dealing with. Here is a link which documents this behavior and suggests the solutions for the same.

    To quote this link

    When components are created by two threads concurrently, with the intention of the instance being cached, it is possible in a small percentage of cases for the first instance into the cache to be replaced with a second instance.

    The other link worth visiting is regarding caching;