I want calculate current percentage in my muli-thread download programme.But there is a strange problem . The lastDownloadSize during the second download must be the sum of write and lastDownloadSize of lastDown. example
There is my code
private long getDownloadSize() {
synchronized (this) {
final AtomicLong totalWriteCount = new AtomicLong(0);
final AtomicLong lastDownloadSize = new AtomicLong(0);
for (DownloadTask task : downloadTasks) {
final long writeCount = task.getWriteCount();
totalWriteCount.addAndGet(writeCount);
final long downloadSize = task.getPosition().getDownloadSize();
lastDownloadSize.addAndGet(downloadSize);
}
System.out.println("===== writeCount : " + totalWriteCount + "lastDownloadSize : " + lastDownloadSize);
return totalWriteCount.addAndGet(lastDownloadSize.get());
}
}
Your
totalWriteCountandlastDownloadSizevariables are local variables of thegetDownloadSize()method. In that case, it does not make sense to useAtomicLong, because only a single thread can access them.What you probably meant, is to make
totalWriteCountandlastDownloadSizemembers of your class:However, also in that case, if they are only accessed from within
synchronized(this)blocks, you do not need to useAtomicLongs, because the synchronized block already makes sure that they are only accessed by a single thread at the same time.