Loading...
Loading...
1 <= operations.length <= 1000 operations[i] is one of: "getInstance", "log", "getLogs", "reset" arguments[i].length <= 200 All concurrent thread simulations use up to 100 threads
You are building a distributed logging system for a high-traffic web application. The system requires a single, shared Logger instance that is safely created and accessed across multiple concurrent threads. Your task is to implement a thread-safe Singleton pattern in Java that:
Logger is ever created, even under heavy concurrent access.Implement a Logger class with the following behavior:
Logger.getInstance() — Returns the single shared instance of Logger. Must be thread-safe.void log(String message) — Appends the message (with a newline) to an internal log.String getLogs() — Returns all logged messages as a single concatenated string.void reset() — For testing only. Clears all logs and resets the instance (simulates a fresh start).You will be given a sequence of operations as two arrays:
operations: a list of method names to call ("getInstance", "log", "getLogs", "reset")arguments: a list of arguments for each operation (empty string "" if no argument is needed)Return a list of results for each operation:
"getInstance" → returns "Logger@singleton" (confirms same instance)"log" → returns "null""getLogs" → returns the full log string"reset" → returns "null"Input: operations = ["getInstance", "log", "log", "getLogs"], arguments = ["", "Server started", "Request received", ""]
Output: ["Logger@singleton", "null", "null", "Server started\nRequest received\n"]
Explanation: getInstance returns the singleton. Two messages are logged. getLogs returns them in order.
Input: operations = ["getInstance", "getInstance"], arguments = ["", ""]
Output: ["Logger@singleton", "Logger@singleton"]
Explanation: Both calls return the exact same singleton instance, confirming only one object is ever created.
Input: operations = ["log", "getLogs", "reset", "getLogs"], arguments = ["Error 500", "", "", ""]
Output: ["null", "Error 500\n", "null", ""]
Explanation: After reset, the log is cleared and getLogs returns an empty string.
volatile field for lazy initialization.synchronized getInstance() which locks on every call — this is inefficient.volatile guarantees in the Java Memory Model and why it matters here.