Best java thread safe object pool
I'm not familiar with Java's concurrency library, so I usually only write my own mutex management code for the following problems, but I'm worried that with the increase of servlet traffic, mutex will slow down the system
The first need is to use a limited set of string keys. I need to find it first, otherwise I create and publish an expensive object This means that there is a global mutex on a naive implementation Is there anything better?
The second requirement is that each expensive object has a soft pool of equivalent workers, any of which is sufficient for execution These workers are cheaper to create than factory factories, but they are still expensive and need to be pooled A simple implementation will install a mutex for each factory, check out a worker from the soft cache, or create it if it is not available However, since many servlet calls use the same factory (possibly), this mutex will also become a focus of debate
Of course, for two mutexes, I can definitely minimize the time spent in synchronous statements, but I'm looking for something better in both cases Maybe both have a non blocking solution?
Andy
Solution
For the first part: instead of putting expensive objects directly into the HashMap, create a simple wrapper that is cheap to create Then, you basically create expensive objects on demand in the wrapper getexpensiveobject () method - although you can obviously trigger creation immediately if this is preferred In either case, you have to synchronize get methods, but this can be done cheaply by double checking locking - usually we just replace normal reads with volatile reads and have expensive synchronization only when creating objects
This assumes that you are using various types of concurrenthashmap because we need putifabsent or some equivalent method to work (we don't want to replace existing expensive objects with empty wrappers)
There's no time to think about the second question now, maybe later