2017-10-07 132 views
-2
private static final Word2Vec word2vectors = getWordVector(); 

    private static Word2Vec getWordVector() { 
     String PATH; 
     try { 
      PATH = new ClassPathResource("models/word2vec_model").getFile().getAbsolutePath(); 
     } catch (Exception e) { 
      e.printStackTrace(); 
      return null; 
     } 
     log.warn("Loading model..."); 
     return WordVectorSerializer.readWord2VecModel(new File(PATH)); 
    } 

     ExecutorService pools = Executors.newFixedThreadPool(4); 
     long startTime = System.currentTimeMillis(); 
     List<Future<?>> runnables = new ArrayList<>(); 
     if (word2vectors != null) { 
      for (int i = 0; i < 3000; i++) { 
       MyRunnable runnable = new MyRunnable("beautiful", i); 
       runnables.add(pools.submit(runnable)); 
      } 
     } 
     for(Future<?> task: runnables){ 
      try { 
       task.get(); 
      }catch(InterruptedException ie){ 
       ie.printStackTrace(); 
      }catch(ExecutionException ee){ 
       ee.printStackTrace(); 
      } 
     } 
     pools.shutdown(); 

static class MyRunnable implements Runnable{ 
     private String word; 
     private int count; 
     public MyRunnable(String word, int i){ 
      this.word = word; 
      this.count = i; 
     } 

     @Override 
     public void run() { 
       Collection<String> words = word2vectors.wordsNearest(word, 5); 
       log.info("Top 5 cloest words: " + words); 
       log.info(String.valueOf(count)); 
     } 
    } 

的word2vectors.wordsNearest()是从公共图书馆的方法。我打算让4个线程同时执行这个方法来加速这个过程。这个线程安全吗?这段代码是否线程安全?

+2

还要看'wordsNearest'方法。 – Oleg

+0

如果我无法控制wordsNearest,我该如何让这段代码安全? – user697911

+1

不知道别的,唯一安全的方法是在调用'wordsNearest'时使用一个线程或在'word2vectors'上同步。 – Oleg

回答

2

您的代码段将是线程安全的,如果满足以下条件:

  1. word2vectors.wordsNearest(...)调用是线程安全的
  2. word2vectors数据结构创建和当前线程初始化。
  3. 没有改变pools.execute通话和计算整理的数据结构。

如果wordsNearest不看其他数据结构,如果不改变word2vectors数据结构,那么它是一个合理的假设它是线程安全的。但是,唯一可以肯定的是分析它

但是,这也是值得注意的是,你只能提交一个任务执行人。由于每个任务都是由单个线程运行的,因此您的代码只能有效使用一个线程。要利用多线程,您需要将您的单个大任务分解为多个小而独立的任务;例如把10000次的重复循环的执行调用的外部...

+0

你可以把这个作为一个例子,将它分成多个小任务? – user697911

+0

我已经告诉过你一种方法。再次阅读我的答案。 –

+0

我用您的建议更新了我的代码。看起来工作不安全。假设我无法控制word2vectors.wordsNearest,我怎样才能使这个方法线程安全? – user697911