从Thread调用会话bean时出现NullPointerException

时间:2013-11-23 19:06:11

标签: java multithreading nullpointerexception ejb stateless-session-bean

我的简单锻炼计划有些问题。我想从线程调用会话bean但它变成NullPointer异常!但如果我从主线程调用它,它可以正常运行

这是警告和例外

Warning: C:\Documents andSettings\User\MyDocuments\NetBeansProjects\ThreadCounter\dist\gfdeploy\ThreadCounter does not exist.
Exception in thread "Thread-2" java.lang.NullPointerException
at threadcounter.Main.run(Main.java:14)
at java.lang.Thread.run(Thread.java:744)

这是一个调用远程会话bean的runnable类

package threadcounter;

import javax.ejb.EJB;
import mysessionbean.CounterSessionBeanRemote;

public class Main implements Runnable {
@EJB
private static CounterSessionBeanRemote counterSessionBean;

@Override
public void run() {
 System.out.println("counter : "+counterSessionBean.getCounter());  //NullPointer
  } 
}

这是我的主要功能

package threadcounter;

public  class Ya {

public static void main(String[] args){
Main t1 = new Main();
new Thread(t1).start();
  }

}

这是会话bean

package mysessionbean;

import java.util.Random;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.Stateless;

@Stateless
public class CounterSessionBean implements CounterSessionBeanRemote {
private int counter = 0;

@Override
public int getCounter() {
    int temp = counter;
    temp++;
    Random r = new Random();
    try {
    Thread.sleep(r.nextInt(20));
    } catch (InterruptedException ex) {
    Logger.getLogger(CounterSessionBean.class.getName()).log(Level.SEVERE, null, ex);
    }
    counter = temp;
    return counter;
}


}

2 个答案:

答案 0 :(得分:1)

我已经明白了!我必须在main函数中注入会话bean,并将会话bean交给带有这样的构造函数的线程

package threadcounter;

import javax.ejb.EJB;
import mysessionbean.CounterSessionBeanRemote;

public class Main implements Runnable {
    @EJB
    private static CounterSessionBeanRemote counterSessionBean;
    Main(CounterSessionBeanRemote x){
        counterSessionBean = x;
    }
   @Override
   public void run() {
   System.out.println("counter : "+counterSessionBean.getCounter());   
   }
}

这是包含主要功能的类

package threadcounter;

import javax.ejb.EJB;
import mysessionbean.CounterSessionBeanRemote;
public  class Ya {
 @EJB
private static CounterSessionBeanRemote counterSessionBean;

  public static void main(String[] args){
  Main t1 = new Main(counterSessionBean);
  new Thread(t1).start();
  Main t2 = new Main(counterSessionBean);
  new Thread(t2).start();
  Main t3 = new Main(counterSessionBean);
  new Thread(t3).start();
  Main t4 = new Main(counterSessionBean);
  new Thread(t4).start();
  }

}

答案 1 :(得分:1)

你不能在一个非容器管理的类中注入带有@EJB的EJB,比如这个

@EJB
private static CounterSessionBeanRemote counterSessionBean;

您的课程应该是一个能够使其运作的容器。否则你可以使用jndi查找

Context jndiContext = new InitialContext();
CounterSessionBeanRemote bean = (CounterSessionBeanRemote ) jndiContext.lookup("....");

另一件事是:为什么要使用@EJB注释,然后在构造函数中稍后赋值?这样做没有意义。

您可能希望至少仔细阅读http://docs.oracle.com/javaee/6/tutorial/doc/gipjf.html#girfl来完成简单的练习。