I must say I am a bit confused about exactly what the ejb spec states
regarding transactions.   Consider a very simple scenario.  I have an
inventory database and I want to keep it updated.  For each item I keep
track of how many items are in stock.  Let's say I do this with an
Inventory Bean that corresponds to one row in the Inventory table.  For
simplicity assume the table just has an item number field and an
quantity amount field.

Let's say now that the bean has a method updateQuantity (This is
actually taken from the Pet Store Demo referred to in the Sun Blueprints
guideline).  It is implemented as follows:

public void updateQuantity( int qty) {
 this.qty -= qty;
    }

Clearly this method should be properly synchronized and that is what I
would like to understand.  Suppose that this method is called under two
separate transactions each of which is decrementing the quantity by 1.
The spec describes two ways that a container can choose to implement
this.  Now I assume that one should code in a way that works for any
implementation so I will discuss the case where the container delegates
the method calls to  two separate bean instances.

I am concerned that the following can happen.  When updateQuantity is
called ejbLoad gets called to update the value of qty.  This will happen
for each of the two bean instances and since the calls are not
necessarily synchronized they can both see the same thing before the
transaction is complete. Say that qty is 2.  So both transactions see a
qty of 2.  Now when the first transaction is complete it will call
ejbStore changing the quantity to 1.  The second transaction will also
decrement and also change qty to 1 and store it.   Now of course we have
a problem because it should be 0.

Obviously if only one instance of the bean is used and the calls to
updateQuantity are synchronized by the container then this will work
properly.

So how should one code for this properly?   If the transaction isolation
level is Serializable then an exception will be generated in the store
method for the second transaction.  This is not what we want to happen.

Here are my questions.

1) Is my analysis correct?
2) What is the correct way to code for this so that it works in any
container?

Dan

===========================================================================
To unsubscribe, send email to [EMAIL PROTECTED] and include in the body
of the message "signoff EJB-INTEREST".  For general help, send email to
[EMAIL PROTECTED] and include in the body of the message "help".

Reply via email to