I've faced a problem of initializing singleton element in a thread safe way in Scala. Usually companion object is used. But this time I need to pass a config object to initializer. Calling some init function of companion object either not thread safe, or leads to locks, that looks kind of low level for Scala (may be I'm not right).
The thing I came up with is a cache. Calling cache with the same argument helps to initialize it exactly once. But the strange thing for me is that I have to use structure with much broader functionality that I need. Seems like knowing that cache will store only one element may result in better performance (at least we don't need to calculate hash of argument every time). So is there such a singleton in Scala that supports only one initialization and ignoring argument for further calls?
[thread 1]
a = A(config) // initialization is initiated
[thread 2, 3, ..]
a = A(config) // initialized object is used
// only one entity of class should exist
class A(config: Config) {
// should be done once
client = config.getString("client")
}
Or may be some other approach solving the problem?