I'm still not too thrilled about using ThreadLocals, but they are working for me. If your ApplicationContexts are shared between threads, then you don't need a ThreadLocal, a static Map would work better: if they're not, then a Map in a ThreadLocal does the trick.
Now that my main project has finished its migration to Spring, I'd say that the best way to do this (imo) would be to have instances of the user type be retrieved from Spring, so that it can work its dependency-inject magic on them. I haven't changed the original custom date class that prompted this thread, but some newer user types that I've written have used Spring to create (empty) instances of the appropriate entity class, and Spring knows about the objects that would otherwise be stored in ThreadLocals. It's working well, and I get to hide all the global/threadlocal variables inside Spring configurations.
If you're not using Spring, then any equivalent implementation of the factory pattern works just as well. You configure your factory in (e.g.) a web filter, or at thread startup-time, and have your user type's nullSafeGet method request new instance from the facory in a thread-agnostic way.
_________________ Code tags are your friend. Know them and use them.
|