我使用SwingWorker刷新当前目录中充满文件的JList。为了防止用户多次运行刷新命令,我在运行时使用AtomicBoolean锁定命令但是在使用HashTable的put()时,我仍然有时会遇到NullPointerException的奇怪问题,有时它会& #39;带有Matcher()的IllegalStateException。 AtomicBoolean不足以阻止并发问题吗?
有问题的行是syntaxHash.put(file.getAbsolutePath(), m.group(1));
函数
doInBackground()
public boolean fillWithFiles(final String EXEC_DIR) {
if (started.compareAndSet(false, true)) { //Lock the function
FillWithFilesWorker worker = new FillWithFilesWorker();
worker.execute(); //Run the worker
return true;
} else {
return false; //There is a thread in the function still
}
}
private class FillWithFilesWorker extends SwingWorker<Void, Boolean> {
@Override
public Void doInBackground() {
try {
publish(true); //disable JList and activate wait cursor
if (syntaxHash != null) syntaxHash.clear();
File currentFolder = new File(HelperWindow.EXEC_DIR);
File[] currentRexScripts = currentFolder.listFiles(new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.toLowerCase().endsWith(".txt");
}
});
listModel = new DefaultListModel<String>();
for (File file : currentRexScripts) {
listModel.addElement(file.getAbsolutePath());
}
final File[] tempCurrentRexScripts = currentRexScripts;
for (File file : tempCurrentRexScripts) {
try {
try (Scanner fileScanner = new Scanner(file)) {
while (fileScanner.hasNext()) {
String s = fileScanner.nextLine();
m = syntax.matcher(s);
if (m.find()) {
syntaxHash.put(file.getAbsolutePath(), m.group(1));
break;
}
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@Override
protected void done() {
JListHelper.this.setModel(listModel);
HelperWindow.scrollPane.setCursor(Cursor.getDefaultCursor());
JListHelper.this.setEnabled(true);
started.set(false);
}
@Override
protected void process(List<Boolean> chunks) {
for (Boolean chunk : chunks) {
if (chunk) {
HelperWindow.scrollPane.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
JListHelper.this.setEnabled(false);
}
}
}
}