
Originally Posted by
wuj98
Could explain why "it's simply not needed because SLSB instances have no state (instance variables) or have the state that's threadsafe so you simply do not need multiple instances, simple singleton will do the job"? Thanks
Consider a class:
Code:
public class FooStatelessService {
public doIt(int i) {
return i*i;
}
}
You can have any number of threads running the method doIt with no problems. The class has no state (instance variables) so it's threadsafe. (local variables and parameters are on the stack and each thread uses it's own stack so they are always threadsafe)
Case 2:
Code:
public class FooStatefulService {
private int i;
public setI(int i) {
this.i = i;
}
public doIt() {
return i*i;
}
}
This class is stateful. You need to call the method setI to set the state and calls to doIt are not threadsafe anymore as different threads can change the state between the calls.
Does it mean that only classes with no instance variables are threadsafe? Well, no. The class is threadsafe if it has no state or the state is constant and threadsafe itself.
Case 3:
Code:
public class FooThreadsafeService {
private Datasource ds;
public setDs(Datasource ds) {
this.ds = ds;
}
public void doIt() {
/* do some db magic here*/
}
}
In this case datasource is set once, when the instance is created, he datasource class itself is threadsafe so - this class is threadsafe too.
Case 4:
Code:
public class FooNonThreadsafeService {
private SimpleDateFormat sdf;
public setSdf(SimpleDateFormat sdf) {
this.sdf = sdf;
}
public void doIt() {
/* do some date formatting here*/
}
}
SimpleDateFormat is set once, at the creation time, but it's not threadsafe (see it's javadocs) so this class is also not threadsafe. So, how do we make it threadsafe? Easiest solution is to make the offending instance local:
Code:
public class FooThreadsafeAgainService {
private String sf;
public setSf(String sf) {
this.sf = sf;
}
public void doIt() {
SimpleDateFormat sdf = new SimpleDateFormat(sf);
/* do some date formatting here*/
}
}
So we made the SimpleDateFormat local and instead of it we have a constant string as a state. Strings are threadsafe so it's all in green again.
Now, how does all this relate to SLSB and WS? SLSB are Stateless Session Beans. WS calls are stateless. They per definition do not have the state that needs to be saved in instance variables between the calls (case 2). They most likely look something like case 3 or 4.