Skip to content

Commit

Permalink
Synchronize writing thread with existing writers (tinylog-org#634)
Browse files Browse the repository at this point in the history
  • Loading branch information
manisiu committed Dec 27, 2023
1 parent d216a20 commit 411b9ae
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 16 deletions.
12 changes: 12 additions & 0 deletions configuration/spotbugs-filters.xml
Original file line number Diff line number Diff line change
Expand Up @@ -87,4 +87,16 @@
<!-- 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>
<Match>
<!-- Writing Thread -->
<Class name="org.tinylog.core.WritingThread" />
<!-- There is only one writing thread instance to wake up -->
<Bug pattern="NO_NOTIFY_NOT_NOTIFYALL" />
</Match>
</FindBugsFilter>
27 changes: 11 additions & 16 deletions tinylog-impl/src/main/java/org/tinylog/core/WritingThread.java
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,6 @@
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 Collection<Writer> writers;
private List<Task> tasks;
Expand Down Expand Up @@ -67,12 +65,6 @@ public void run() {

flush(writers);
writers.clear();

try {
sleep(MILLISECONDS_TO_SLEEP);
} catch (InterruptedException ex) {
// Ignore and continue
}
}
}

Expand All @@ -88,6 +80,7 @@ public void add(final Writer writer, final LogEntry logEntry) {
Task task = new Task(writer, logEntry);
synchronized (mutex) {
tasks.add(task);
mutex.notify();
}
}

Expand All @@ -102,9 +95,8 @@ public void add(final Writer writer, final LogEntry logEntry) {
public void shutdown() {
synchronized (mutex) {
tasks.add(Task.POISON);
mutex.notify();
}

interrupt();
}

/**
Expand All @@ -114,13 +106,16 @@ public void shutdown() {
*/
private List<Task> receiveTasks() {
synchronized (mutex) {
if (tasks.isEmpty()) {
return Collections.emptyList();
} else {
List<Task> currentTasks = tasks;
tasks = new ArrayList<Task>();
return currentTasks;
while (tasks.isEmpty()) {
try {
mutex.wait();
} catch (InterruptedException ex) {
return Collections.emptyList();
}
}
List<Task> currentTasks = tasks;
tasks = new ArrayList<Task>();
return currentTasks;
}
}

Expand Down

0 comments on commit 411b9ae

Please sign in to comment.