I can't understand how the EJB container manage thread-safety for @Stateless beans with instance variables. So I will give a simple example before explaining my concerns:
@Stateless
public class BeanTest{
@Inject
private String var;
private Connection connection;
@Resource(name = "jdbc/TestDB")
private DataSource dataSource;
public void modify() {
var = "TestName";
}
@PostConstruct
public void initialize() {
try {
connection = dataSource.getConnection();
} catch (SQLException sqle) {
sqle.printStackTrace();
}
}
@PreDestroy
public void cleanup() {
try {
connection.close();
connection = null;
} catch (SQLException sqle) {
sqle.printStackTrace();
}
}
}
Here is my questions, assuming that our container supports pooling:
1. Pooling vs Thread-safe:
User 1 used an instance of BeanTest and modified the var using the modify method, then he finished and the container put the instance of BeanTest in the managed pool. When User 2 tries to use the same bean for a request, he might get the same instance of BeanTest intially modified by User 1 (I understand that might get another instance too). So which state of the instance variable var he will find (default value which is null or "TestName")? if its the new modified one, do that mean that even @Stateless beans are not 100% thread-safe? So finnaly there is no container added -value regarding thread safety, as not using instance variable makes a bean thread safe even if it's not a @Stateless bean
2. Pooling vs @PreDestroy
If the bean is returned to the managed pool and not destroyed, do that mean that the @Predestroy method will not be called and in that case the connection will stay opened ? So, if we have 30 inctance of that bean in the pool, we may have 30 open connection that is not used, isn't that a performance issue? or this not how @Predestroy is working conbined with pooling? (using Connection is just an example, we may have other kind of ressource that we need to close in @Predestroy)
NB: This is not a real life example, so I'am not looking for an alternative solution, my concern is to understand the whole concept and how things are managed in the Application Server, what is happening under the hood