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);
}
}
내 질문의 ThreadLocal로 나는 readNWrite()
방법에 lineCnt
을해야합니까입니까?