when to be thread safe?

Discussions

EJB programming & troubleshooting: when to be thread safe?

  1. when to be thread safe? (4 messages)

    This is a basic question:

    suppose i have (assume the code will compile, etc.):

    class MyStatelessSessionBean implements SessionBean
    {
     MyFooClass myFoo;
     public void ejbCreate()
     {
      myFoo = new MyFooClass();
     }

     public String x() // - exposed thru remote
     {
      myFoo.xyz();

      MyBarClass myBar = new MyBarClass();
      myBar.abc();
     }

     public void ejbActivate(), etc......
    }

    Does MyFooClass.xyz() need to be thread safe?
    How about MyBarClass.abc()?

    Threaded Messages (4)

  2. when to be thread safe?[ Go to top ]

    Method calls to Session beans are serialized, so in uor case u dont have to worry about MyFooClass.

    MyBarClass anyway is not an instance variable. its part of method x stack. so u shud be ok.

    kapil
  3. Follow-up question[ Go to top ]

    How does the container do this? Is there a separate copy of code for each existing stateless sesseion bean?
  4. Follow-up question[ Go to top ]

    First of all DON'T use instance variables in statless session beans if you're not absolutly sure about what you are doing!

    This is becaus you'll never know to wich statless sessionbean instance your call goes to. Two method calls after eachother to the same sessionbean can actually go to two separate instances. This is why it's called stateless.

    Second, calls to session beans are not really serialized. But you can be sure that your thread is alone in that perticular sessionbean instance.

    The only time you have to make sure that your methods is 100% threadsafe if you use a singelton from your EJB:s.
  5. Follow-up question[ Go to top ]

    The only instance variables you can safely use in a SLSB are things which are not related to the client calling them, and which the client calling them does not rely on being the same (which is almost, but not quite, the same.)

    As others have said, the EJB server (and this is a point of contention for some) will effectively single thread access to each instance of the bean, so you are fine, provided you are not accessing any other shared objects inside the VM (which is more than just Singleton)

    The reason I say it's a point of contention is that it slows things down a bit. When you compare to the Servlet model, which forces you to write thread safe code (or cheat and use the marker interface, but lets skip that for now).

    Servlets run incredibly quickly as they let the app server manage concurrency with acceptor work threads, rather than using instances of the actual object.

    However, that's a bit off track, you are safe in the code you submitted provided your instance variable is not client specific, and that the client doesn't need to make two calls to the "same" bean.

    Chz

    Tony