从InitialContext中获取Stateless Bean在不同的线程中

时间:2013-05-25 15:24:26

标签: java-ee ejb ejb-3.0 jboss7.x

我想从java桌面应用程序调用在JBoss 7中部署的无状态会话Bean 我创建了InitialContext实例,如果我在同一个线程中查找并调用bean方法(以下代码中的bean1),一切正常。 但是如果我在另一个线程中从InitialContext获取bean代理,那么当我从bean调用一个方法时,程序会引发一个Exception(以下代码中的bean2)。
我使用的部分源代码:

public class Tester1 implements Runnable
{
    InitialContext ctx;
    static String beanAddr = "MobileSubscribersService_war_exploded/SubscriberEJB!com.persianswitch.ussd.ISubscriberBeanRemote";

    public void doIt()  throws NamingException
    {
        Properties p = new Properties();
        p.put(Context.INITIAL_CONTEXT_FACTORY,"org.jboss.naming.remote.client.InitialContextFactory");
        p.put(Context.PROVIDER_URL, "remote://localhost:4447");
        p.put(Context.SECURITY_PRINCIPAL, "user");
        p.put(Context.SECURITY_CREDENTIALS, "pass");
        p.put("jboss.naming.client.ejb.context", true);
        ctx = new InitialContext(p);

        ISubscriberBeanRemote bean1 =  (ISubscriberBeanRemote)ctx.lookup(beanAddr);
        int res = bean1.getLanguageByMobileNo("12345"); // this line runs good

        Thread th = new Thread(this);
        th.start();
    }

    @Override
    public void run() {
        try {
            ISubscriberBeanRemote bean2 = (ISubscriberBeanRemote)ctx.lookup(beanAddr);
            int res = bean2.getLanguageByMobileNo("12345"); // Throws Exception Here
        } catch (NamingException e) {
        }
    }
}

例外内容:

Exception in thread "Thread-2" java.lang.IllegalStateException: No EJB receiver available for handling [appName:,modulename:MobileSubscribersService_war_exploded,distinctname:] combination for invocation context org.jboss.ejb.client.EJBClientInvocationContext@3337cdec
    at org.jboss.ejb.client.EJBClientContext.requireEJBReceiver(EJBClientContext.java:584)
    at org.jboss.ejb.client.ReceiverInterceptor.handleInvocation(ReceiverInterceptor.java:119)
    at org.jboss.ejb.client.EJBClientInvocationContext.sendRequest(EJBClientInvocationContext.java:181)
    at org.jboss.ejb.client.EJBInvocationHandler.doInvoke(EJBInvocationHandler.java:136)
    at org.jboss.ejb.client.EJBInvocationHandler.doInvoke(EJBInvocationHandler.java:121)
    at org.jboss.ejb.client.EJBInvocationHandler.invoke(EJBInvocationHandler.java:104)
    at com.sun.proxy.$Proxy0.getLanguageByMobileNo(Unknown Source)
    at com.persianswitch.Tester1.run(Tester1.java:52)
    at java.lang.Thread.run(Thread.java:722)

我想在多个线程中重用一个InitialContext来提高性能 我的代码中有错误吗?有什么规则我必须知道吗?

1 个答案:

答案 0 :(得分:1)

InitialContext不是线程安全的,因为它的JavaDoc声明:“一个InitialContext实例没有与多个线程的并发访问同步。每个操作不同的InitialContext实例的多个线程不需要同步。需要访问单个线程的线程InitialContext实例同时应该在它们之间同步并提供必要的锁定。“