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));
}
}
Le fichier word2vectors.wordsNearest() est une méthode issue d'une bibliothèque publique. J'ai l'intention de laisser 4 threads exécuter simultanément la méthode pour accélérer le processus. Ce fil est-il sûr?Est-ce que ce morceau de code est sûr?
Dépend de la méthode 'wordsNearest'. – Oleg
Si je ne peux pas contrôler les mots, comment puis-je sécuriser ce code? – user697911
Sans rien connaître d'autre, le seul moyen sûr est d'utiliser un thread ou de synchroniser sur 'word2vectors' quand vous appelez' wordsNearest'. – Oleg