Advertisement
Guest User

Untitled

a guest
Aug 23rd, 2019
104
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.38 KB | None | 0 0
  1. import java.io.Closeable;
  2. import java.io.Flushable;
  3. import java.io.PrintWriter;
  4. import java.util.LinkedList;
  5. import java.util.Queue;
  6. import java.util.logging.Logger;
  7.  
  8. /**
  9. * Writes log files to a after a specified number of items are writen to the buffer
  10. */
  11. public class BufferingLogFileWriter implements Flushable, Closeable {
  12.  
  13. private static final Logger LOGGER = LoggerUtils.getLogger(BufferingLogFileWriter.class);
  14.  
  15. public static final int MAX_QUEUE_SIZE = 50;
  16. public final Queue<String> mQueue = new LinkedList<>();
  17. private String logFilePath;
  18. private PrintWriter printWriter;
  19.  
  20. public BufferingLogFileWriter(String logFilePath) {
  21. this.logFilePath = logFilePath;
  22. }
  23.  
  24. public synchronized void open() {
  25. this.printWriter = FileIO.openPrintWriter(this.logFilePath);
  26. }
  27.  
  28. public synchronized void queue(String line) {
  29. if (mQueue.size() > MAX_QUEUE_SIZE) {
  30. this.flush();
  31. }
  32.  
  33. mQueue.add(line);
  34. }
  35.  
  36. public synchronized void flush() {
  37. LOGGER.info("Flushing queue...");
  38. while (!mQueue.isEmpty()) {
  39. String line = mQueue.poll();
  40. this.printWriter.print(line);
  41. if (!line.endsWith("\n")) {
  42. this.printWriter.println();
  43. }
  44. }
  45. LOGGER.info("Flushed.");
  46. }
  47.  
  48. public synchronized void close() {
  49. this.printWriter.close();
  50. }
  51. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement