View Javadoc

1   package com.github.triceo.splitlog;
2   
3   import java.util.concurrent.ScheduledExecutorService;
4   
5   import org.slf4j.Logger;
6   import org.slf4j.LoggerFactory;
7   
8   import com.github.triceo.splitlog.api.Follower;
9   
10  /**
11   * As followers are terminated via {@link #stopFollowing(Follower)} and then
12   * discarded by GC, some messages will become unreachable. (No followers point
13   * to them any longer.)
14   *
15   * The point of this class is to review the situation and discard whatever
16   * messages are no longer reachable. Otherwise they'd be uselessly occupying
17   * memory.
18   *
19   * This class is intended to be run periodically by
20   * {@link ScheduledExecutorService}.
21   */
22  final class LogWatchStorageSweeper implements Runnable {
23  
24      private static final Logger LOGGER = LoggerFactory.getLogger(LogWatchStorageSweeper.class);
25      private final LogWatchStorageManager toSweep;
26  
27      public LogWatchStorageSweeper(final LogWatchStorageManager watch) {
28          this.toSweep = watch;
29      }
30  
31      @Override
32      public void run() {
33          final MessageStore messages = this.toSweep.getMessageStore();
34          final int minId = this.toSweep.getFirstReachableMessageId();
35          LogWatchStorageSweeper.LOGGER.debug(
36                  "Starting message sweep from {}. First reachable message ID reportedly {}.",
37                  this.toSweep.getLogWatch(), minId);
38          if (minId < 0) {
39              LogWatchStorageSweeper.LOGGER.info("Sweeping all messages from {} as none are reachable.",
40                      this.toSweep.getLogWatch());
41              messages.discardBefore(messages.getNextPosition());
42              return;
43          } else if (messages.isEmpty()) {
44              LogWatchStorageSweeper.LOGGER.info("No messages in {}.", this.toSweep.getLogWatch());
45              return;
46          }
47          final int num = messages.discardBefore(minId);
48          LogWatchStorageSweeper.LOGGER.info("Swept {} messages from {}.", num, this.toSweep.getLogWatch());
49      }
50  
51  }