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.
- Is this the correct use of
@Stateless
EJB instance variable? - Is a
@MessageDriven
more appropriate? - Is there a more EE way to achive it?
Thanks