LearnFrenzy
Sign in Take a free test

Static and Final Keywords · Static and Final Programs · Question 5

Singleton logger using an enum in Java Solution, output & explanation

  • Program
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 5 Back to Exercise

Implement a Logger singleton as a single-element enum (the safest singleton in Java) that keeps a count of messages by level, and use it from two different methods.

Solution
Main.java
import java.util.EnumMap;
import java.util.Map;

enum Level { INFO, WARN, ERROR }

enum Logger {
    INSTANCE;                                    // the one and only instance

    private final Map<Level, Integer> counts = new EnumMap<>(Level.class);

    void log(Level level, String msg) {
        counts.merge(level, 1, Integer::sum);
        System.out.println("[" + level + "] " + msg);
    }

    String summary() { return counts.toString(); }
}

public class Main {
    static void checkout() {
        Logger.INSTANCE.log(Level.INFO, "checkout started");
        Logger.INSTANCE.log(Level.WARN, "coupon expired");
    }

    static void payment() {
        Logger log = Logger.INSTANCE;            // the same object
        log.log(Level.INFO, "payment ok");
        log.log(Level.ERROR, "email failed");
    }

    public static void main(String[] args) {
        checkout();
        payment();
        System.out.println(Logger.INSTANCE.summary());
    }
}

Output Verified by compiling and running

[INFO] checkout started
[WARN] coupon expired
[INFO] payment ok
[ERROR] email failed
{INFO=2, WARN=1, ERROR=1}

The JVM guarantees an enum constant is created exactly once, even with serialization or reflection – so an enum is the recommended singleton.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links