diff --git a/configuration/spotbugs-filters.xml b/configuration/spotbugs-filters.xml index 9f36b9481..2d238c0e6 100644 --- a/configuration/spotbugs-filters.xml +++ b/configuration/spotbugs-filters.xml @@ -87,4 +87,10 @@ + + + + + + diff --git a/tinylog-impl/src/main/java/org/tinylog/core/WritingThread.java b/tinylog-impl/src/main/java/org/tinylog/core/WritingThread.java index 6e82ba5de..c6a4e7d08 100644 --- a/tinylog-impl/src/main/java/org/tinylog/core/WritingThread.java +++ b/tinylog-impl/src/main/java/org/tinylog/core/WritingThread.java @@ -28,9 +28,8 @@ public final class WritingThread extends Thread { private static final String THREAD_NAME = "tinylog-WritingThread"; - private static final long MILLISECONDS_TO_SLEEP = 10L; - private final Object mutex; + private final Object threadMutex; private final Collection writers; private List tasks; @@ -40,6 +39,7 @@ public final class WritingThread extends Thread { */ WritingThread(final Collection writers) { this.mutex = new Object(); + this.threadMutex = new Object(); this.writers = writers; this.tasks = new ArrayList(); @@ -56,23 +56,30 @@ public void run() { Collection writers = new ArrayList(1); while (true) { + synchronized (threadMutex) { + try { + // Only wake up when there's something to write + threadMutex.wait(); + } catch (InterruptedException ex) { + // Ignore and continue + } + } + boolean flushOnShutdown = false; for (Task task : receiveTasks()) { if (task == Task.POISON) { + if (flushOnShutdown) { + flush(writers); + } close(); return; } else { + flushOnShutdown = true; write(writers, task); } } flush(writers); writers.clear(); - - try { - sleep(MILLISECONDS_TO_SLEEP); - } catch (InterruptedException ex) { - // Ignore and continue - } } } @@ -89,6 +96,9 @@ public void add(final Writer writer, final LogEntry logEntry) { synchronized (mutex) { tasks.add(task); } + synchronized (threadMutex) { + threadMutex.notifyAll(); + } } /** @@ -102,6 +112,10 @@ public void add(final Writer writer, final LogEntry logEntry) { public void shutdown() { synchronized (mutex) { tasks.add(Task.POISON); + mutex.notify(); + } + synchronized (threadMutex) { + threadMutex.notifyAll(); } interrupt();