javajakarta-eeejbejb-3.1stateless-session-bean

Stateless EJB local (instance) variable


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 @Singletons are not suitable.

  1. Is this the correct use of @Stateless EJB instance variable?
  2. Is a @MessageDriven more appropriate?
  3. Is there a more EE way to achive it?

Thanks


Solution

  • 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:

    Therefore you will need to be intimate with the way in which your server manages SLSB pools.