Friday, August 8, 2008

Calling RMI from EJB Stateless Session Bean

I have to analyze one of our J2EE application(s), that call RMI from a Stateless Session Bean. I originally think that it could be a problem, because our Session Bean use remote object as singleton and the rule said that Session Bean shall be programed in thread safe manner because its methods run concurrently within container's threads. To confirm that I decided to do some experiments.
I create a sample RMI server
/* SampleServer.java */
import java.rmi.*;

public interface SampleServer extends Remote
{
  public int sum(int a,int b) throws RemoteException;
}

import java.rmi.*;
import java.rmi.server.*;
import java.rmi.registry.*;

/* SampleServerImpl.java */
public class SampleServerImpl extends UnicastRemoteObject
                             implements SampleServer
{
  SampleServerImpl() throws RemoteException
  {
     super();
  }

  public int sum(int a,int b) throws RemoteException
  {
     try {
       Thread.sleep(5000);
     } catch (InterruptedException e){
       e.printStackTrace();
     }

     return a + b;
  }

  public static void main(String args[])
  {
    try
      {
        SampleServerImpl sampleServer = new SampleServerImpl();

        Registry registry = LocateRegistry.createRegistry(8989);
        registry.rebind("Sample", sampleServer);

        System.out.println("Server waiting.....");
      }
    catch (RemoteException e)
      {
         e.printStackTrace();
      }
  }
}
I compile these classes compile and run using JDK1.5 with jmx enabled according jconsole article
$ javac SampleServer.java SampleServerImpl.java
$ rmic SampleServerImpl
$ java -Dcom.sun.management.jmxremote SampleServerImpl
I decide to use JRUBY to create and run a 20 thread(s), each issue a call RMI server
$jirb
> import java.rmi.Naming  
> sample = Naming.lookup("//127.0.0.1:8989/Sample")
> (1..20).each { Thread.new { puts sample.sum(3,7)} }
>
Then I run jconsole supplied in JDK1.5 and watch thread pool of the RMI server
$jconsole
The result is everything is OK, for each incoming call request, RMI server create a separate thread to handle it and the thread is dropped after it completion.

No comments: