I’ve read the the restrictions for EJBs and several answers here on stackoverflow but I’m not quite sure about a snippet of code, which I found at work.
There’s a service which provides detailed information about Foos depending on their identifier.
public FooResponse getFoo(FooRequest request){...};
Somewhere under the surface is a self written pool which holds recently provided response objects. For every request, the pool is asked, if there’s an entry available. If yes, then it’s used as the response and if not, then the database will be asked. When a response was fetched from the database, then it’s stored in the pool.
The pool uses two strategies to take care of its size.
First, it uses java.lang.ref.SoftReference<T> inside a Map to avoid OutOfMemoryErrors.
The second thing it uses is a java.util.TimerTask which is created for every entry in the Map and scheduled by a java.util.Timer, which deletes the entry after a configurable amount of time.
This is, in my opinion, violating the restriction, that an EJB is not allowed to create threads (which the java.util.Timer does). Am I right or am I missing something somewhere?
Until today, this has not caused any obvious problems. Do you recommend, to get rid of this self coded pool?
Another thing is, that the service is a stateless SessionBean. A container will create not just only one of them. Therefore they’re not sharing the same pool and it would be luck, if one bean would be asked about a Foo twice. Am I also right with this?
The main problem with creating your own threads is that it means that they are outside the control of your application server, which could lead to scenarios where a rogue EJB “breaks the server” by creating too many threads.
However, having background threads is a desirable thing, so usually app servers provide “Work Managers” in order to schedule tasks (with a timer or a parallel threads).
Here’s an article on CommonJ with Websphere which provides background on how to use threads without breaking the server: Work Managers
Here’s how Weblogic’s CommonJ docs: The Timer and Work Manager API
Though possibly off-topic, here’s how spring integrates with work managers: Task Execution and Scheduling
To solve your problem, I would integrate with a cache (e.g. EHCache) and let it work out when to evict items from the cache.
(Again, possibly off topic, using Spring, the can make using the cache a matter of adding some annotations to your code: ehcache-spring-annotations)