我想知道我们什么时候需要使用threadlocal变量?我有一个运行多个线程的代码,每个代码都读取S3上的一些文件,我希望跟踪这些文件完全读出多少行,这里是我的代码:是否需要在这里使用ThreadLocal?
final AtomicInteger logLineCounter = new AtomicInteger(0);
for(File f : files) {
calls.add(_exec.submit(new Callable<Void>() {
@Override
public Void call() throws Exception {
readNWrite(f, logLineCounter);
return null;
}
}));
}
for (Future<Void> f : calls) {
try {
f.get();
} catch (Exception e) {
//
}
}
LOGGER.info("Total number of lines: " + logLineCounter);
...
private void readNWrite(File f, AtomicInteger counter) {
Iterator<Activity> it = _dataReader.read(file);
int lineCnt = 0;
if (it != null && it.hasNext()) {
while(it.hasNext()) {
lineCnt++;
// write to temp file here
}
counter.getAndAdd(lineCnt);
}
}
我的问题是,我需要做的lineCnt
在readNWrite()
方法是ThreadLocal的?