0

How to implement the getDataStore method as singleton method(threadsafe) in a Scala object or Scala's object will implement this method automatically as a singleton method?

object MorphiaHelper {
  var morphia = new Morphia()
  var datastore = null
  def getDataStore() = {morphia.createDatastore(new Mongo(mongoip, mongoport), "test")
  }
}
nullox
  • 295
  • 2
  • 7
  • 18

1 Answers1

4

I'm not completely sure what you mean by singleton method(threadsafe), so here come some variants/facts you might care about:

  1. MorphiaHelper is a singleton since you made it an object. Nothing to do here

  2. the method getDataStore() is not thread safe. To make it thread safe see this Question: How to make a code thread safe in scala?

  3. if you want to make sure that there is only one instance of datastore, initialized using the return value of getDataStore, you can rewrite the object like this:

    object MorphiaHelper {
      lazy val datastore = (new Morphia()).createDatastore(
          new Mongo(mongoip, mongoport), "test")
    }
    

    This will create only one data store when it is requested and it will be thread safe.

Community
  • 1
  • 1
Jens Schauder
  • 77,657
  • 34
  • 181
  • 348