Since EJB Server is a multithreaded environment, component instances that share resources and volatile data must be coded or configured to avoid problems with inconsistent state. For example, if all instances of a component write to the same file, you must take steps to ensure that the file is “locked” before each instance writes to it and “unlocked” when the write completes. If writes to the file are allowed to occur simultaneously, then output from two component instances may be mixed together within the file.
Whenever possible, avoid the use of static class variables. Also, avoid sharing stateful (being able to maintain information about the state of a resource) resources such as database connections or file descriptors. In cases where data and resources are shared, there are two ways to ensure thread safety in a component:
Configure the component for single-threaded execution.
Each component defined in EJB Server has a Concurrency property. By default, components are multithreaded and instances are allowed to execute concurrently on different threads. You can also request single-threading; in a single-threaded component, each method invocation blocks other method invocations on instances of the same component.
For components in general, single-threading is the least desirable alternative because it increases the likelihood that clients will block each other’s execution and increase the apparent response time of client applications. Single-threading makes sense for some specific problems; for example, to share an output file among component instances, you can create a single-threaded component with methods that write to the file (another alternative is to use explicit threading primitives when implementing code that writes to the file, such as the Java synchronized keyword).
Store shared data on the database.
You can use connection caching and store the data on the database, letting the database server handle concurrency issues. (The component’s transactional semantics may affect the interaction with the database.)