diff --git a/src/main/java/com/hextremelabs/cloudwatchappender/CloudWatchAppender.java b/src/main/java/com/hextremelabs/cloudwatchappender/CloudWatchAppender.java index 77cc827..786b649 100644 --- a/src/main/java/com/hextremelabs/cloudwatchappender/CloudWatchAppender.java +++ b/src/main/java/com/hextremelabs/cloudwatchappender/CloudWatchAppender.java @@ -1,26 +1,31 @@ package com.hextremelabs.cloudwatchappender; +import com.amazonaws.annotation.ThreadSafe; import org.apache.log4j.AppenderSkeleton; import org.apache.log4j.spi.LoggingEvent; import java.util.Collection; -import java.util.LinkedList; -import java.util.List; import java.util.Queue; -import java.util.concurrent.ConcurrentLinkedQueue; +import java.util.concurrent.PriorityBlockingQueue; +import java.util.concurrent.atomic.AtomicReference; import static java.util.Comparator.comparing; /** * @author oladeji */ +@ThreadSafe public class CloudWatchAppender extends AppenderSkeleton { - - private static final Queue LOGS = new ConcurrentLinkedQueue<>(); + private static final int INITIAL_CAPACITY = 11; // copied from PBQ implementation + private static final AtomicReference> LOGS = new AtomicReference<>( + new PriorityBlockingQueue<>(INITIAL_CAPACITY, comparing(LoggingEvent::getTimeStamp))); @Override protected void append(LoggingEvent loggingEvent) { - LOGS.add(loggingEvent); + LOGS.updateAndGet(queue -> { + queue.add(loggingEvent); + return queue; + }); } @Override @@ -32,10 +37,8 @@ public boolean requiresLayout() { return true; } - public static Collection retrieveLogsAndClear() { - final List events = new LinkedList<>(); - LOGS.removeIf(e -> events.add(e)); - events.sort(comparing(LoggingEvent::getTimeStamp)); - return events; + static Collection retrieveLogsAndClear() { + Queue queue = new PriorityBlockingQueue<>(INITIAL_CAPACITY, comparing(LoggingEvent::getTimeStamp)); + return LOGS.getAndSet(queue); } }