Downloader: keep track of download queue.

crossfading
Nekojimi 3 years ago
parent 579fb01a20
commit b7f0794bc4
  1. 23
      src/main/java/moe/nekojimi/chords/Downloader.java

@ -8,6 +8,9 @@ package moe.nekojimi.chords;
import java.io.File; import java.io.File;
import java.io.InputStream; import java.io.InputStream;
import java.nio.charset.Charset; import java.nio.charset.Charset;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.concurrent.LinkedBlockingDeque; import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
@ -24,9 +27,9 @@ import java.util.regex.Pattern;
*/ */
public class Downloader implements Consumer<Song> public class Downloader implements Consumer<Song>
{ {
// private final Queue<Song> downloadQueue = new LinkedBlockingDeque<>(); private final List<Song> downloadQueue = new LinkedList<>();
private final LinkedBlockingDeque<Runnable> workQueue = new LinkedBlockingDeque<>(); private final LinkedBlockingDeque<Runnable> workQueue = new LinkedBlockingDeque<>();
private final ThreadPoolExecutor exec = new ThreadPoolExecutor(1, 4, 30, TimeUnit.SECONDS, workQueue); private final ThreadPoolExecutor exec = new ThreadPoolExecutor(2, 4, 30, TimeUnit.SECONDS, workQueue);
private Consumer<Song> next; private Consumer<Song> next;
private BiConsumer<Song, Exception> messageHandler; private BiConsumer<Song, Exception> messageHandler;
@ -38,9 +41,14 @@ public class Downloader implements Consumer<Song>
@Override @Override
public void accept(Song song) public void accept(Song song)
{ {
exec.submit(() -> downloadQueue.add(song);
exec.submit(new Runnable()
{ {
download(song); @Override
public void run()
{
download(song);
}
}); });
} }
@ -76,12 +84,14 @@ public class Downloader implements Consumer<Song>
if (next != null) if (next != null)
next.accept(song); next.accept(song);
downloadQueue.remove(song);
messageHandler.accept(song, null); messageHandler.accept(song, null);
} catch (Exception ex) } catch (Exception ex)
{ {
Logger.getLogger(Downloader.class.getName()).log(Level.SEVERE, null, ex); Logger.getLogger(Downloader.class.getName()).log(Level.SEVERE, null, ex);
if (messageHandler != null) if (messageHandler != null)
messageHandler.accept(song, ex); messageHandler.accept(song, ex);
downloadQueue.remove(song);
} }
} }
@ -95,4 +105,9 @@ public class Downloader implements Consumer<Song>
this.messageHandler = messageHandler; this.messageHandler = messageHandler;
} }
public List<Song> getDownloadQueue()
{
return downloadQueue;
}
} }

Loading…
Cancel
Save