0

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?

Hakanai
  • 12,010
  • 10
  • 62
  • 132

1 Answers1

2

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;

Santosh
  • 17,667
  • 4
  • 54
  • 79
  • Just a bit of a post-mortem for this - this indeed fixed the issue for the person who had it and also fixed every test we had written, at least in the short term. In the longer term, 1 in 10,000 times the test is run, PicoContainer still creates multiple instances of the component. So I would assert that it's still not thread-safe even when using the Locking behaviour, it's just somewhat better than not using it. – Hakanai Apr 01 '13 at 23:23
  • True. I guess [Double Check locking](http://www.cs.umd.edu/~pugh/java/memoryModel/DoubleCheckedLocking.html) can further reduce the chances of multiple instances. In particular JDK5 with improved [memory model](http://www.cs.umd.edu/~pugh/java/memoryModel/jsr-133-faq.html). – Santosh Apr 02 '13 at 07:42
  • I was thinking I might just dig into how PicoContainer works and then try to use some of Guava's concurrency stuff to make a truly thread-safe component adapter. – Hakanai Apr 05 '13 at 04:03