Search code examples
javasingletonimmutabilitymutabledata-collection

What is the appropriate way/pattern to collect information from classes?


To keep things simplified lets say I have an interface RandomProvider interface

public interface RandomProvider
{
    double nextRandom();
}

And say I have 3 different implementations of this interface, ARandom, BRandom, CRandom. I want to collect some statistics about the implementations:

  • how many times nextRandom() is called
  • sum of the generated random numbers (it may sound silly but this is just an example).

In the end these statistics will be recorded to DB. These are heavily used classes from multiple threads so it is not feasible to write the values every time a request comes.

The first idea that comes to my mind is, I make a singleton that holds these data, implementations call the singleton and increase necessary statistics. Another class reads from the singleton and writes the results to DB and decrements the statistics. But I have read so many articles about how evil globally mutable data and singletons are so I am afraid to go this way.

Any other ideas?


Solution

  • Yes the singleton can be an evil idea, however it depends on their use. If you use a singleton just to make your code work (allowing it to touch other classes like a global central object) then it is bad.

    But ultimately you are simply looking for some way to log information ( a logger ) and in this case it is not a bad decision to use a singleton to log this data or even to log it to some text / log files.