My question is about how to use the block synchronized, my class FileAdapter has a method write that receives the InputStream of the result of an HTTP connection I’m using to download a file, for every kilobyte downloaded and written to disk, it calls the downloaded method of the DownloadReport class instance that it received, for pass on what has already been downloaded.
In another Thread, which is printing the output to the user, it calls the updateProgress method, also of the DownloadReport class, this method is responsible for updating a progress bar that is displayed to the user on the terminal.
The problem will be if the FileAdapter class tries to update the amount of bytes downloaded just when the output Thread tries to update the progress bar, as both methods edit the value of the variable intermediateDownloaded, which works only as an auxiliary variable, to hold the amount of bytes downloaded since the last update, to calculate the download speed.
If I use the "synchronized (this)" block, within the downloaded and updateProgress methods, it will block the entire class DownloadReport, and the output Thread will only be able to update the progress bar after the FileAdapter class updates the number of downloaded bytes?
FileAdapter:
public void write(InputStream content, DownloadReport downloadReport) throws IOException {
FileOutputStream output = new FileOutputStream(file);
byte[] buffer = new byte[1024];
int read;
while ((read = content.read(buffer)) != -1) {
output.write(buffer, 0, read);
downloadReport.downloaded(read);
}
}
DownloadReport:
public void downloaded(int bytes) {
intermediateDownloaded += bytes;
downloaded += bytes;
}
public void updateProgress() {
long now = System.currentTimeMillis();
double delta = UnitHelper.sizeRound(((now - lastTimeUpdate) / 1000.0), 2);
if (delta >= 1) {
unitAdapter.convertSpeed(intermediateDownloaded, delta);
intermediateDownloaded = 0;
lastTimeUpdate = now;
}
progressBar.updateProgress(unitAdapter.finalSize,
unitAdapter.recalculate(downloaded), unitAdapter.unity);
}