1. import java.util.ArrayList;
  2. import java.util.List;
  3. import java.util.concurrent.atomic.AtomicInteger;
  4. class LogStream {
  5. private List<String> logs; // Store log messages
  6. private int maxLogs; // Maximum number of logs to store
  7. private AtomicInteger logCounter = new AtomicInteger(0); // Atomic counter for unique log IDs
  8. public LogStream(int maxLogs) {
  9. this.logs = new ArrayList<>();
  10. this.maxLogs = maxLogs;
  11. }
  12. public synchronized void log(String message) { // Synchronized for thread safety
  13. logCounter.incrementAndGet();
  14. String logId = "log-" + logCounter.get(); // Generate a unique ID
  15. logs.add(logId + ": " + message); // Add log message with ID
  16. if (logs.size() > maxLogs) {
  17. logs.remove(0); // Remove the oldest log message if limit is reached
  18. }
  19. }
  20. public List<String> getLogs() {
  21. return new ArrayList<>(logs); // Return a copy to prevent external modification
  22. }
  23. public static void main(String[] args) {
  24. // Example usage
  25. LogStream logStream = new LogStream(5); // Limit to 5 logs
  26. logStream.log("This is log message 1.");
  27. logStream.log("This is log message 2.");
  28. logStream.log("This is log message 3.");
  29. logStream.log("This is log message 4.");
  30. logStream.log("This is log message 5.");
  31. logStream.log("This is log message 6."); // Will replace the oldest log
  32. System.out.println(logStream.getLogs());
  33. }
  34. }

Add your comment