Threading in EJB


EJB design: Threading in EJB

  1. Threading in EJB (1 messages)

    According to the J2EE specification ver 1.3 section 6.2.1 regarding the use of threads in an EJB:

    "If enterprise bean were allowed to manage threads, the J2EE platform could not manage the lifecycle of the enterprise bean and it could not properly manage transactions."

    And in J2EE specs version 2.0,

    "An enterprise Bean must not use thread synchronization primitives to synchronize execution of multiple instances."
    "Synchronization would not work if the EJB Container distrbuted enterprise bean's instances across multiple JVMs."

    I wonder whether a harmless invocation Thread.sleep(1000) to simulate a delay could affect the lifecycle of an EJB component.

    I would think that the above statements means explicit synchronisation of the access of object/resource would not work in a cluster multi-machine environment.

    Does that mean Thread.sleep() is ok since it does not entails synchronization to a resource.

    Benedict Chng

    Threaded Messages (1)

  2. Threading in EJB[ Go to top ]

    IMO, you have to consider these kinds of rules in the appropriate context. For instance, take the thread synchronization primitives rule. When you use Java libraries (even standard ones like system IO streams) you are probably using hundreds of synchronization primitives. And some of them (e.g, lazy initialization of Singletons) may cause different bean instances to synchronize against each other. If such use had been restricted, you could hardly use any libs at all.
    So what the rule actually means IMO, is that you should not count on the synchronization primitives to synchronize seperate bean instances. Not that you can't use them in beans.
    The same argument holds for thread management. I doubt you'll find a single IO stream that doesn't sleep/wait/notify. You can use these methods, just don't make any assumptions about how such methods in one bean instance affect the other - they may not affect it at all.

    Note: creating threads is a bit more risky becuase it may screw up the containers synchronization system or the transation manager, so you should try to avoid it. IMO.