[FIX] Possible multithreading issue

This commit is contained in:
Gravita 2023-03-22 21:46:40 +07:00
parent dc664c7ee2
commit fb2883d215

View file

@ -19,6 +19,7 @@
import java.util.Queue; import java.util.Queue;
import java.util.concurrent.*; import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Consumer; import java.util.function.Consumer;
public class Downloader { public class Downloader {
@ -28,7 +29,7 @@ public class Downloader {
private static boolean isNoHttp2; private static boolean isNoHttp2;
protected final HttpClient client; protected final HttpClient client;
protected final ExecutorService executor; protected final ExecutorService executor;
protected final LinkedList<DownloadTask> tasks = new LinkedList<>(); protected final Queue<DownloadTask> tasks = new ConcurrentLinkedDeque<>();
protected CompletableFuture<Void> future; protected CompletableFuture<Void> future;
protected Downloader(HttpClient client, ExecutorService executor) { protected Downloader(HttpClient client, ExecutorService executor) {
this.client = client; this.client = client;
@ -128,15 +129,13 @@ protected DownloadTask sendAsync(AsyncDownloader.SizedFile file, URI baseUri, Pa
IOHelper.createParentDirs(targetDir.resolve(file.filePath)); IOHelper.createParentDirs(targetDir.resolve(file.filePath));
ProgressTrackingBodyHandler<Path> bodyHandler = makeBodyHandler(targetDir.resolve(file.filePath), callback); ProgressTrackingBodyHandler<Path> bodyHandler = makeBodyHandler(targetDir.resolve(file.filePath), callback);
CompletableFuture<HttpResponse<Path>> future = client.sendAsync(makeHttpRequest(baseUri, file.urlPath), bodyHandler); CompletableFuture<HttpResponse<Path>> future = client.sendAsync(makeHttpRequest(baseUri, file.urlPath), bodyHandler);
var ref = new Object() { AtomicReference<DownloadTask> task = new AtomicReference<>(null);
DownloadTask task = null; task.set(new DownloadTask(bodyHandler, future.thenApply((e) -> {
}; tasks.remove(task.get());
ref.task = new DownloadTask(bodyHandler, future.thenApply((e) -> {
tasks.remove(ref.task);
return e; return e;
})); })));
tasks.add(ref.task); tasks.add(task.get());
return ref.task; return task.get();
} }
protected HttpRequest makeHttpRequest(URI baseUri, String filePath) throws URISyntaxException { protected HttpRequest makeHttpRequest(URI baseUri, String filePath) throws URISyntaxException {