Synchronization organisation

This commit is contained in:
Emmanuel Bigeon 2018-10-11 12:09:24 -04:00
parent 98d22782c1
commit 761d640f0b
2 changed files with 17 additions and 15 deletions

View File

@ -265,6 +265,7 @@ public final class ReadingRunnable implements Runnable {
message);
final Thread th = new Thread(waitRunn);
// Wait for the thread to actually start before unlocking the message queue.
synchronized (start) {
th.start();
while (!waitRunn.isStarted()) {

View File

@ -88,18 +88,18 @@ import java.util.logging.Logger;
public final class WritingRunnable implements Runnable {
/** Wait timeout. */
private static final long TIMEOUT = 1000;
private static final long TIMEOUT = 1000;
/** Class logger. */
private static final Logger LOGGER = Logger
private static final Logger LOGGER = Logger
.getLogger(WritingRunnable.class.getName());
/** Messages to write. */
private final Deque<String> messages = new ArrayDeque<>();
/** Stream to write to. */
private final OutputStream outPrint;
private final OutputStream outPrint;
/** The charset. */
private final Charset charset;
private final Charset charset;
/** Runnable state. */
private boolean running = true;
private boolean running = true;
/** Synchro object. */
private final Object lock = new Object();
@ -143,15 +143,14 @@ public final class WritingRunnable implements Runnable {
public void run() {
while (running) {
synchronized (lock) {
while (messages.isEmpty()) {
waitNextMessage();
if (!running) {
return;
}
waitNextMessage();
if (!running) {
return;
}
writeMessage();
}
}
}
/** Set the running status.
@ -166,11 +165,14 @@ public final class WritingRunnable implements Runnable {
/** Wait for next message. */
private void waitNextMessage() {
try {
lock.wait(TIMEOUT);
synchronized (lock) {
while (running && messages.isEmpty()) {
lock.wait(TIMEOUT);
}
}
} catch (final InterruptedException e) {
if (running) {
LOGGER.log(Level.SEVERE,
"Thread interruption exception.", e); //$NON-NLS-1$
LOGGER.log(Level.SEVERE, "Thread interruption exception.", e); //$NON-NLS-1$
}
Thread.currentThread().interrupt();
}
@ -179,8 +181,7 @@ public final class WritingRunnable implements Runnable {
/** Write next message to output. */
private void writeMessage() {
final String message = messages.poll();
final ByteBuffer buff = charset
.encode(message + System.lineSeparator());
final ByteBuffer buff = charset.encode(message + System.lineSeparator());
if (buff.hasArray()) {
try {
outPrint.write(buff.array());