2017-08-09 189 views
0

我有这样的方法:的ThreadPoolExecutor返回null

public class NFeRoboServiceImpl implements NFeRoboService { 

private static volatile ThreadPoolExecutor executor; 

    private ThreadPoolExecutor getExecutor() { 
     if (executor == null) { 
      synchronized (NFeRoboServiceImpl.class) { 
       if (executor == null) { 
        executor = new ThreadPoolExecutor(2, 10, 10, TimeUnit.SECONDS, 
          new ArrayBlockingQueue<Runnable>(100, true), new RetryRejectedExecutionHandler()); 
        Monitor monitor = new Monitor(nFePersistenceService, executor, 3); 
        Thread monitorThread = new Thread(monitor); 
        monitorThread.start(); 
       } 
      } 
     } 
     return executor; 
    } 
} 

这个问题很奇怪,当我把光标移到新的ThreadPoolExecutor后的“执行者”,它说的是,对象为空,当我选择执行者和ctrl + 转变 + i,它显示我创建的对象。

我具有线程执行空:

getExecutor().execute(worker); 
+1

'executor'是一个静态字段吗?这听起来像这是至少有点特定于IDE。你在用什么IDE? – Michael

+0

Im使用eclipse – AgamenonD2

+0

你是**绝对**不使用“双重检查锁定”的有效**版本。有关选项,请参阅https://www.securecoding.cert.org/confluence/display/java/LCK10-J.+Use+a+correct+form+of+the+double-checked+locking+idiom。 – GhostCat

回答

0

我认为,执行是静态的。在这种情况下,你应该把它定义为volatile。 请参阅“双重检查”的Should I synchronize a static volatile variable?

答案,请参阅:

http://www.cs.umd.edu/~pugh/java/memoryModel/DoubleCheckedLocking.html

大概Eclipse使用getExecutor,当它试图确定执行的值,因为豆公约。如果将隐式初始化函数重命名为与字段名称不相关的内容,会发生什么情况?

+0

没有用我的代码.... – AgamenonD2

+0

好吧,对不起,应该是一个评论,因为你似乎有调试器的问题。尽管如此,多线程初始化和双重检查必须使用volatile进行。我延长了我的回答,请看最后一句。 – aschoerk

+0

Tks的答案,即时通讯使用私有静态易失性ThreadPoolExecutor执行器;是的,即时调试时遇到问题。 – AgamenonD2