Skip to content

Commit

Permalink
Wait for IO completion
Browse files Browse the repository at this point in the history
  • Loading branch information
dmssargent committed Jul 24, 2018
1 parent 873c995 commit 6ae70c2
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 12 deletions.
2 changes: 1 addition & 1 deletion build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,9 @@ version '0.1.4'
apply plugin: 'java'
apply plugin: 'application'


sourceCompatibility = 1.8
mainClassName = "me.davidsargent.stubjars.Main"

repositories {
mavenCentral()
}
Expand Down
8 changes: 8 additions & 0 deletions src/main/java/me/davidsargent/stubjars/StubJars.java
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,15 @@ public void createSourceFiles() {
sourceFiles.append(file.getAbsolutePath()).append(System.lineSeparator());
writer.write();
}

writerThread.done();
try {
writerThread.waitForCompletion();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return;
}

Writer sourcesList = new Writer(SOURCES_LIST_FILE);
try {
sourcesList.write(sourceFiles.toString());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,14 @@
package me.davidsargent.stubjars.components.writer;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Semaphore;

/**
* @see Writer
*/
public class WriterThread extends Thread implements Runnable {
private final ArrayBlockingQueue<Writer> writersToProcess;
private Thread runningThread = null;
private volatile boolean stop = false;

public WriterThread() {
Expand All @@ -31,6 +33,10 @@ public void done() {
stop = true;
}

public void kill() {
runningThread.interrupt();
}

void addWriter(Writer writer) {
try {
writersToProcess.put(writer);
Expand All @@ -39,21 +45,28 @@ void addWriter(Writer writer) {
}
}

@Override
public void run() {
public void waitForCompletion() throws InterruptedException {
if (runningThread == null) return;
runningThread.join();
}

private void internalRun() {
while (!Thread.currentThread().isInterrupted() && !(writersToProcess.isEmpty() && stop)) {
Writer writer = writersToProcess.poll();
if (writer == null) {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}

continue;
Writer writer;
try {
writer = writersToProcess.take();
} catch (InterruptedException e) {
return;
}

writer._threadWrite();
}
}

@Override
public void run() {
runningThread = Thread.currentThread();
internalRun();
runningThread = null;
}
}

0 comments on commit 6ae70c2

Please # to comment.