I’m using JBoss AS 7 and a Schedule method on a EJB Stateless. My problem is that even the EJB is a Stateless one, its keeping its state, and this brings me trouble. Here is the example:
The timer:
@Stateless
public class TestTimer {
@Inject HelloWorldService helloWorld;
@SuppressWarnings("unused")
@Schedule(second="*/10", minute="*", hour="*", info="MyTimer")
private void execute() {
System.out.println(helloWorld.sayHello());
System.out.println(this.toString() + " "+ helloWorld.toString());
}
}
The Injected HelloWorldService:
public class HelloWorldService {
public String sayHello() {
return "Hello World!";
}
}
I was expecting that the line System.out.println(this.toString() + " "+ helloWorld.toString()); would print one different time every time the timer runs, since it would be a new TestTimer instance every time, but I was wrong:
16:43:50,003 INFO [stdout] (EJB default - 3) foo.service.TestTimer@4a56936f foo.service.HelloWorldService@79e98289
16:44:40,022 INFO [stdout] (EJB default - 1) foo.service.TestTimer@4a56936f foo.service.HelloWorldService@79e98289
Am I doing something wrong, this is the expected behavior, or what?
What matters is that each timer there is a lookup, you may get a different instance of the bean
,
but “may” means you may still get the same instance, as it is obtained from a pool of beans
That the container manages for you.
There is nothing wrong with using the same timer object,
as long as it provides the proper functionality.
This means that as a developer you cannot make any assumption on the state of the bean, and whether or not it is will be restored upon a new lookup of the bean.