Skip to content

Commit

Permalink
Synchronize writing thread with existing writers
Browse files Browse the repository at this point in the history
  • Loading branch information
manisiu committed Dec 22, 2023
1 parent d216a20 commit 5f42c07
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 8 deletions.
6 changes: 6 additions & 0 deletions configuration/spotbugs-filters.xml
Original file line number Diff line number Diff line change
Expand Up @@ -87,4 +87,10 @@
<!-- Allow writing to static field org.tinylog.policies.DynamicPolicy.reset from instance method org.tinylog.policies.DynamicPolicy.reset -->
<Bug pattern="ST_WRITE_TO_STATIC_FROM_INSTANCE_METHOD" />
</Match>
<Match>
<!-- Writing Thread -->
<Class name="org.tinylog.core.WritingThread" />
<!-- Allow unconditional waits - a rare spurious thread is a no-op other than synchronizing on the task mutex-->
<Bug pattern="UW_UNCOND_WAIT" />
</Match>
</FindBugsFilter>
30 changes: 22 additions & 8 deletions tinylog-impl/src/main/java/org/tinylog/core/WritingThread.java
Original file line number Diff line number Diff line change
Expand Up @@ -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<Writer> writers;
private List<Task> tasks;

Expand All @@ -40,6 +39,7 @@ public final class WritingThread extends Thread {
*/
WritingThread(final Collection<Writer> writers) {
this.mutex = new Object();
this.threadMutex = new Object();
this.writers = writers;
this.tasks = new ArrayList<Task>();

Expand All @@ -56,23 +56,30 @@ public void run() {
Collection<Writer> writers = new ArrayList<Writer>(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
}
}
}

Expand All @@ -89,6 +96,9 @@ public void add(final Writer writer, final LogEntry logEntry) {
synchronized (mutex) {
tasks.add(task);
}
synchronized (threadMutex) {
threadMutex.notifyAll();
}
}

/**
Expand All @@ -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();
Expand Down

0 comments on commit 5f42c07

Please sign in to comment.