Reputation: 7449
What I want to achieve is to take advantage of EJB feautures and use some kind of automatic pooling.
I thought a SLSB may be suitable, when retaining a local stateless variable (don't know if it is an appropriate definition) - at least from the client/caller POV.
@Stateless
public class CommunicationService implements Serializable
{
private Process process;
@PostConstruct
//@PostActivate maybe?
public void startProcess()
{
try
{
process = new ProcessBuilder("running a temporary daemon").start();
}
catch(IOException e)
{
throw new RuntimeException(e.getMessage(), e);
}
}
@PreDestroy
//@PrePassivate maybe?
public void endProcess()
{
if(process.isAlive())
{
process.destroy();
boolean terminated = false;
try
{
terminated = process.waitFor(5, TimeUnit.SECONDS);
}
catch(InterruptedException e)
{
// ignore
}
if(!terminated)
{
process.destroyForcibly();
}
}
}
public int send(String message)
{
// do something with the process - may take a long time
// this is just an example
PrintStream printStream = new PrintStream(process.getOutputStream());
printStream.println(message);
try
{
return process.getInputStream().read();
}
catch(IOException e)
{
return -1;
}
}
}
Note that I want a pool of processes, so @Singleton
s are not suitable.
@Stateless
EJB instance variable?@MessageDriven
more appropriate?Thanks
Upvotes: 0
Views: 1044
Reputation: 19445
Contrary to popular belief, it's quite OK to maintain state in SLSBs. It just cannot be client state. §4.7 of the EJB 3.2 Spec says:
The term “stateless” signifies that an instance has no state for a specific client. However, the instance variables of the instance can contain the state across client-invoked method calls. Examples of such state include an open database connection and an object reference to an enterprise bean object.
Therefore, this might be a workable strategy with some caveats:
The spec says that "stateless session bean instances are typically pooled". You would need to check that your chosen JavaEE server implementation does actually pool them, because (at least for a while there) some of them would just create a new instance every time;
Controlling the number of beans in the pool may be tricky. An implementation may continue to create bean instances even when the pool is full, it just never returns them to the pool;
If any type of RuntimeException is thrown from a business method then the bean instance will be discarded without calling the @PreDestroy callback (see §9.3.1 of EJB 3.2 Spec). This will result in process leaks in your system;
Therefore you will need to be intimate with the way in which your server manages SLSB pools.
Upvotes: 2
Reputation: 2175
For me, you need to implement a Factory method pattern ;
Read this for me information EJB Factory Class
Upvotes: -1