Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A Singleton with multiple instances?

Background

I have a situation in which I'm developing a program that runs like a thread. Basically, there is a "master" program that runs instances of sub-programs simultaneously.

Due to the nature of this system, the "sub-programs" all run under a single Java Virtual Machine. The most serious implication here is that they share memory spaces.

In my sub-program, I want to create a Logger class so that all the classes within my sub-program can log to a single location. Since this project can include many classes, I want to avoid Dependency Injection and use a Singleton.

But if I use a Singleton, the instance will be stored statically. So if the JVM has 2 instances of my program running, the Logger class will give them the same instance (because they share that memory).

I want each sub-program to have their own logger, without dependency injection.

There exists a unique identifier that I can call for each program to differentiate between them.


My Current Solution

Assume "uniqueID" is an API call that the Master Program receives and then returns what Sub-Program called it. Assume this call produces extremely little computational overhead.

public class Logger {
    private static HashMap<string,Logger> instances = new Hashmap<>();

    public static Logger instance() {
        if(instances.containsKey(uniqueId)) {
            return instances.get(uniqueId);
        } else {
            Logger newLogger = new Logger();
            instances.put(uniqueId, newLogger);
            return newLogger;
        }
    }

    private Logger(){}
}

This solution allows each sub-program to treat the Logger class like a Singleton, but it's not quite a Singleton. It acts as an Instance Manager, that creates and returns instances based on which sub-program is interacting with the method.


My Question(s)

This solution is not technically a Singleton, but each project using it treats it like a singleton. What design pattern is it?

Also, is this the correct approach to my problem? How can I improve it?

like image 557
Clay07g Avatar asked Jan 19 '26 19:01

Clay07g


1 Answers

If I read correctly, you want a thread-based multiton. Java provides the ThreadLocal class to support that pattern. With a little thought, you can implement a static logMessage() method that uses the ThreadLocal under the covers to retrieve the correct logger instance.

Care should be taken in JEE application server environments to avoid memory leaks when the application context is restarted, but I don't think that applies to your situation.

like image 72
Steve11235 Avatar answered Jan 21 '26 09:01

Steve11235



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!