Domanda

Server running on GlassFish 3.0

@Stateless(mappedName="messengerservice")
public class MessengerService implements MsnService{

    int count;


    @Override
    public int getCount() {
        // TODO Auto-generated method stub
        count = count+1;
        return count;
    }
}

Client

  for(int i=0;i<5;i++){
      MsnService br = (MsnService) ctx.lookup("java:global/EJbTutorial/MessengerService");
      System.out.println(br.getCount());
  }

Output

1
2
3
4
5

EJB spec says that server maintains a pool of session beans , i increment the value in one instance , re look up hopefully get a new instance and it seems the instance variable value is maintained

How is it possible ? unless server keeps returning me the same instance every time, or is it.

I even tried it executing it in a loop and same result. Can any shed some light

È stato utile?

Soluzione 2

To test , if Stateless Beans indeed pooled , as Tom Anderson suggested , i tried executing it parallel threads

Client

ExecutorService service =  Executors.newFixedThreadPool(10);           

for(int i=0; i<5;i++){
  Future future=  service.submit(new MessengerClient("Thread "+i+" :"));
  }        

service.shutdown();

Output

Thread 0 :1
Thread 1 :1
Thread 3 :1
Thread 4 :1
Thread 2 :1
Thread 1 :2
Thread 2 :3
Thread 3 :4
Thread 4 :5
Thread 0 :6
Thread 1 :7
Thread 2 :8
Thread 3 :9
Thread 4 :10
Thread 0 :11
Thread 1 :2
Thread 2 :12
Thread 3 :13
Thread 4 :14
Thread 2 :15
Thread 1 :16
Thread 3 :17
Thread 4 :18
Thread 0 :19
Thread 0 :20

Well this proves that indeed new instances are used by the threads

Altri suggerimenti

It gives the correct output, referred from this link, it says

With stateless beans, the clients may call any available instance of an instantiated bean for as long as the EJB container has the ability to pool stateless beans. This enables the number of instantiations of a bean to be reduced, thereby reducing required resources.

Bean pooling Any stateless session bean method instance that is not currently invoked is equally available to be called by an EJB
container or application server to service the request of a client. This allows the EJB container to pool stateless bean instances and
increase performance.

Scalability Because stateless session beans are able to service multiple clients, they tend to be more scalable when applications have a large number of clients. When compared to stateful session beans, stateless session beans usually require less instantiation.

Performance An EJB container will never move a stateless session bean from RAM out to a secondary storage, which it may do with a stateful session bean; therefore, stateless session beans may offer greater performance than stateful session beans.

read more about the difference between stateless and stateful session beans...

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top