可能重复:
Singleton 中的线程安全
嗨,
我正在使用wordnet词典查找单词的同义词。由于我有很多文档,我使用了多个线程来进行文档预处理,包括词干、分词和同义词替换。
我使用以下代码访问字典并获取每个文档的单词集。
IndexWordSet set = Dictionary.getInstance().lookupAllIndexWords(newWord);
这在单线程环境中运行良好。但在多线程环境中,这并没有像预期的那样工作。程序过了一段时间就被卡住了。
这是因为Dictionary.getInstance()
是一个单例类,并且它不是线程安全的吗?如果是,我如何修改对字典的访问,使其线程安全?(我无法修改字典类,因为我使用了字典库(
为Dictionary实例编写一个包装器。在此包装中,同步访问以确保一次只有一个线程可以访问lookupAllIndexWords((。
public class DictionaryIndexer {
public static IndexWordSet lookupAllIndexWords(newWord) {
final Dictionary instance = Dictionary.getInstance();
synchronized (instance) {
return instance.lookupAllIndexWords(newWord);
}
}
}
如果您使用相同的锁将所有对Dictionary的调用封装在包装器中进行同步,那么您就可能拥有线程安全的解决方案。
来源:
这个库中到处都是迭代器和状态:
/**
* Main word lookup procedure. First try a normal lookup. If that doesn't work,
* try looking up the stemmed form of the lemma.
* @param pos the part-of-speech of the word to look up
* @param lemma the lemma to look up
* @return IndexWord the IndexWord found by the lookup procedure, or null
* if an IndexWord is not found
*/
public IndexWord lookupIndexWord(POS pos, String lemma) throws JWNLException {
lemma = prepareQueryString(lemma);
IndexWord word = getIndexWord(pos, lemma);
if (word == null && getMorphologicalProcessor() != null) {
word = getMorphologicalProcessor().lookupBaseForm(pos, lemma);
}
return word;
}
/**
* Return a set of <code>IndexWord</code>s, with each element in the set
* corresponding to a part-of-speech of <var>word</var>.
* @param lemma the word for which to lookup senses
* @return An array of IndexWords, each of which is a sense of <var>word</var>
*/
public IndexWordSet lookupAllIndexWords(String lemma) throws JWNLException {
lemma = prepareQueryString(lemma);
IndexWordSet set = new IndexWordSet(lemma);
for (Iterator itr = POS.getAllPOS().iterator(); itr.hasNext();) {
IndexWord current = lookupIndexWord((POS)itr.next(), lemma);
if (current != null) set.add(current);
}
return set;
}
在POS中我们可以找到
private static final List ALL_POS =
Collections.unmodifiableList( /* alphazero: this is good news .. */
Arrays.asList(new POS[] {NOUN, VERB, ADJECTIVE, ADVERB}));
public static List getAllPOS() {
return ALL_POS;
}
试试林奇的答案。它应该起作用。
您可以使用其中一个并发容器。。。
或者,您可以在singleton实例中使用同步(有人已经在注释中发布了线程安全singleton的链接(。