How can I implement a proper counter bean with EJB 3.0?
Posted
by Aaron Digulla
on Stack Overflow
See other posts from Stack Overflow
or by Aaron Digulla
Published on 2010-03-31T07:27:03Z
Indexed on
2010/03/31
7:53 UTC
Read the original article
Hit count: 412
I have this entity bean:
import javax.persistence.*;
@Entity
public class CounterTest {
private int id;
private int counter;
@Id
public int getId() { return id; }
public void setId(int id) { this.id = id; }
public int getCounter() { return counter; }
public void setCounter(int counter) { this.counter = counter; }
}
and this stateful bean to increment a counter:
import java.rmi.RemoteException;
import javax.ejb.*;
import javax.persistence.*;
@Stateful
public class CounterTestBean implements CounterTestRemote {
@PersistenceContext(unitName = "JavaEE")
EntityManager manager;
public void initDB() {
CounterTest ct = new CounterTest();
ct.setNr(1);
ct.setWert(1);
manager.persist(ct);
}
public boolean testCounterWithLock() {
try {
CounterTest ct = manager.find(CounterTest.class, 1);
manager.lock(ct, LockModeType.WRITE);
int wert = ct.getWert();
ct.setWert(wert + 1);
manager.flush();
return true;
} catch (Throwable t) {
return false;
}
}
}
When I call testCounterWithLock()
from three threads 500 times each, the counter gets incremented between 13 and 1279 times. How do I fix this code so that it is incremented 1500 times?
© Stack Overflow or respective owner