I need to restrict access to a method in a session bean so that just one user at a time can execute that section of code.
In normal java applications , i do it in the following manner
public static Object mylock = new Object();
critical section code
Will this mechanism work in Session beans also? . As multiple instances of session beans are running in the Application server- how will the synchronization occur.
Correct me f I'm wrong, but aren't Session Beans single threaded (one client per Session bean) ?
You're right! Session Beans are single threaded, so your methodds will never be accessed by more than one client at a time, but you will probably have more than one bean of the same type present in your application server, each alling the same method, but in their separate contexts.
If I'm right (I'm a beginner at this) the problem with EJBs first arises when using cached entity beans. You will have to use either long transactions, locking the database while updating the data, or use some kind of dirty flag or optimistic locking strategy.
The choice depend on your need for performance (long transactions cost!).
...coming to think about it, you're need for syncronization probably follows from some other design decision you've made. See if you can't redesign so you don't need to sync the call. Solve the right problems ;-)
What is the problem you are trying to solve?
I have a function which has a sql query that reads a row from a table and after some calculation updates it back in the table.
The problem is that if multiple clients simultaneously read the old row and update based on that, only the last update would be visible and it would be incorrect.
Thus i want to restrict access to this function to just 1 client at a time.
But since there are multiple instances of session beans in a pool, i am not sure whwther there is a way to synchronize a function across multiple instances.
My select qry is in the session bean and the update qry is in an entity bean. if i put both the operations in a single function and declare its transaction attribute as required - will it work ?
Use TX_SERIALIZABLE transaction isolation - it is transactional equvalent of 'synchronized'.