singleton design pattern with thread safe - singleton

I read the reason for synchronize the new instance creation is two threads can access getInstance same time and find that _instance is null and create two instances of Singleton class. So in order to eliminate that we synchronized it. But again how come a double-checked locking method introduce again check whether the instance is null inside the Synchronized block. Does this necessary? Once a code block is synchronized it already thread safe know?
public class Singleton {
private static Singleton _instance = null;
private Singleton() { }
public static Singleton getInstance() {
if (_instance == null) {
synchronized (Singleton.class) {
_instance = new Singleton(); // why need to again check null
}
}
return _instance;
}
}

The synchronized block will be executed sequentially (i.e., one thread at a time), but that's not enough, because the second call to _instance = new Singleton() might override the first one.
It's a plausible scenario if one context-switch takes place immediately after the first thread evaluates the _instance == null expression, and no other context-switch takes place until another thread evaluates the _instance == null expression.
Therefore, once inside the synchronized block, the current thread has to make sure that _instance is still null before setting it to a new Singleton().

Related

Should all the static methods be synchronised?

I will explain the two use-cases here:
Static method which uses an object and perform some operations and returns the same object:
// Lets assume here SomeObject contains a function putInt which store a HashMap.
public static SomeObject createIntEvent(SomeObject objectName,
final String eventName,
final int value){
objectName.putInt(eventName, value);
return objectName;
}
Static method which creates an object and perform some operations and returns the created Object:
// Lets assume here SomeObject contains a function putInt which store a HashMap.
public static SomeObject createIntEvent(final String eventName,
final int value){
SomeObject objectName = new SomeObject();
objectName.putInt(eventName, value);
return objectName;
}
For the above two examples, For Case 2 we should have createIntEvent as a synchronized method because we are creating a new object and if it is not thread safe it could cause unwanted problems. But for the case 1, I wasn't certain if the same logic applies.
Can someone please explain why the first Case should or shouldn't be synchronized?
I tried creating a sample program to do the same thing, didn't face any issue. But was wondering if there is some Design pattern which advocates this.
Thank you for your time.

Execute a method when object is changed (OOP)

I'm learning OOP and trying to write a simple program that will execute some method every time when a specific varible will change.
I have two classes:
public class SomeClass {
private OtherClass object;
public OtherClass getObject() {
return this.object;
}
public void setObject(OtherClass object) {
objectChanged();
this.object = object;
}
private void objectChanged() {
System.out.println("Object has changed");
}
}
public class OtherClass {
private int value = 5;
public int getValue() {
return this.value;
}
public void setValue(int value) {
this.value = value;
}
}
The variable objectChanged should be called every time when variable "object" is changed. My first naive idea was to put the method call inside of set function. But what if you change the object after you set it? Like this:
SomeClass someObject = new SomeClass();
OtherClass otherObject = new OtherClass();
someObject.setObject(otherObject); //"Object has changed"
otherObject.setValue(10); //nothing happens yet
I need someObject to realize that object stored inside of it changed its value to 10, but how do i do it? Is it even possible in OOP?
It looks to be reasonable, but one should consider many things. This is why there is no automatic way to do it in general. It is not part of the OOP paradigm as such. If this would be some automatic behavior, it would cause huge overhead as it is not often needed to observe changes this way. But you can, of course, implement your way depending on your concrete requirements.
There are at least two approaches.
In MVVM (like WPF) there is an INotifyPropertyChanged interface (let's call it a pattern) you can use to trigger a notification yourself, mutch like you did with SomeClass. However when you are nesting objects, you need to wire up that mechanism.to cascade: you should do the same with OtherClass and also connect the actual instances to bubble up changes.
See: https://rehansaeed.com/tag/design-patterns/
An other option is the Observable pattern. Each time the object changes state, you emit an instance - the current instance. However, you should care to emit unmutable objects. At least by using an interface that makes it read-only. But you still need to wire up the object tree to react to the changes of nested objects.
If your platform supports reflection, and you create a proper toolset, you could make this wiring up quite simple. But again: this is not strictly related to the paradigm.

java - how to init a singletone with data only once?

It is probably elementary but I have problem solving it.
I have a singleton and in every method call i send an object . the same one.
so it looks like this :
mySingletone.getInstance.doSomethingXXX(MyObj)
mySingletone.getInstance.doSomethingYYY(MyObj)
Now, I want to stop sending it and put it inside the singletone.
I have a few optional solutions -
1. set it right after the first - getinstance call .
very bad - cause I am not sure when will be the frst time.
2. I can erase the singletone implementation and send them to a public ctor - but then I will not be sure that it will be created once only.
Is there a way to init a singletone only once?
Check out the Initialization On Demand Holder Idiom for the best way to implement a singleton pattern in Java.
http://en.wikipedia.org/wiki/Initialization-on-demand_holder_idiom
You can just set the value in your private constructor, which should be called only once.
If your Singleton class needs to doSomething with different MYObj then you should continue to do what you are doing.
If the Singleton should always use the same instance of MyObj (i think that's what you're asking for), you can create an instance of it in your Singleton (it would be better because it would be encapsulated/hidden from the client. (you can even encapsulate the MyObj class inside this class)
For example:
public class MySingleton {
private static MySingleton _instance = new MySingleton();
private MyObj _myObj = new MyObj();
private MySingleton() {
//set more stuff into _myObj if necessary
}
/*
//similarly you can replace the above 4 lines of code with this code:
private MyObj _myObj;
private MySingleton() {
_myObj = new MyObj();
//set more stuff into _myObj if necessary
}
*/
private static MySingleton getInstance() { return _instance; }
//other methods of the class use _myObj
// ...
//could even define MyObj class nested in this class
}

If not a singleton, then what?

So I'm working on a middleware layer.
I'm consuming a COM DLL that deals with the low level hardware interaction, and providing an interface for the UI to do IO with the hardware.
As part of the design of my layer, we put in a contextmanager that arranges the various pieces of hardware to produce contexts that our application can work with.
So I want to guarantee that a developer that is working with my code has a single context manager to work with and then inside that context manager I can guarantee that we only allocate 1 work queue per hardware device.
Just to complicate this there is some initialization that must be done before I can start adding in hardware devices. Something that would be simple if not for the fact that typically you only access a singleton via a readonly property.
I know the singleton pattern can make alot of things difficult because of it's global accessibility. I really do not want, nor need for this class to have the global availability of a singleton, I just want the guarantee that only one will be created inside the app.
For that would I be crazy to do something like this, to basically give my singleton a constructor:
public class MySingleton
{
private static MySingleton _MySingleton;
private static object singletonLock = new object();
private MySingleton(int foo1, string foo2)
{
//do init stuff
}
public static MySingleton StartSingleton(int foo1, string foo2)
{
try
{
Monitor.Enter(singletonLock);
if (_MySingleton == null)
{
_MySingleton = new MySingleton(foo1, foo2);
}
else
throw new Exception("Singleton already initialized");
}
finally
{
Monitor.Exit(singletonLock);
}
return _MySingleton;
}
public static MySingleton Instance
{
get
{
try
{
Monitor.Enter(singletonLock);
if (_MySingleton == null)
{
throw new Exception("Singleton must be Initialized");
}
}
finally
{
Monitor.Exit(singletonLock);
}
return _MySingleton;
}
}
}
It's not crazy code but it is a singleton anyway. If you remove Instance property then it won't be singleton anymore.
Global accessibility is not all that makes singletons nasty. What makes them nasty is that they are used all through the system directly without you being able to track all those usages. That's why it is such a nightmare in multi-threading code, that's why it is so hard to unit test anything with singletons inside.
So if it is your code I'd recommend creating just one object during application initialization and pass it around with dependency injection or as plain constructor argument. If it is a library, you can either check in constructor if it is first object being created or not and throw an exception or you can go with static constructor as you did but without Instance property, forcing developers to pass instance around.
As always, you can just create singleton, after all all it matters is that product works and customers enjoy using it, singletons or no singletons doesn't really matter.
You wouldn't be crazy. A singleton avoids the drawbacks of global variables by virtue of being namespaced. Even though it is globally accessible via a static function call, it is not a global variable. And further, it is accessed via a namespace, so noone is likely to put it in a global var called temp, then later assign something else to temp. They should always get a local reference to it by doing
MySingleton singletonRef = MySingleton.Instance();
when their scope closes, the reference dies, and so it's not a global variable.
So if I just need to garuntee that you can only create one version of my object then something like this would work:
public class MySingleton
{
private static int objectCount = 0;
private static object singletonLock = new object();
public MySingleton(int foo1, string foo2)
{
try{
Monitor.Enter(singletonLock);
if (objectCount != 0)
{
throw new Exception("MySingleton Already exsists");
}
else
{
objectCount++;
}
}
finally{
Monitor.Exit(singletonLock);
}
//do initialization stuff
}
}
obviously not a true singleton anymore.

Can a class return an object of itself

Can a class return an object of itself.
In my example I have a class called "Change" which represents a change to the system, and I am wondering if it is in anyway against design principles to return an object of type Change or an ArrayList which is populated with all the recent Change objects.
Yes, a class can have a method that returns an instance of itself. This is quite a common scenario.
In C#, an example might be:
public class Change
{
public int ChangeID { get; set; }
private Change(int changeId)
{
ChangeID = changeId;
LoadFromDatabase();
}
private void LoadFromDatabase()
{
// TODO Perform Database load here.
}
public static Change GetChange(int changeId)
{
return new Change(changeId);
}
}
Yes it can. In fact, that's exactly what a singleton class does. The first time you call its class-level getInstance() method, it constructs an instance of itself and returns that. Then subsequent calls to getInstance() return the already-constructed instance.
Your particular case could use a similar method but you need some way of deciding the list of recent changes. As such it will need to maintain its own list of such changes. You could do this with a static array or list of the changes. Just be certain that the underlying information in the list doesn't disappear - this could happen in C++ (for example) if you maintained pointers to the objects and those objects were freed by your clients.
Less of an issue in an automatic garbage collection environment like Java since the object wouldn't disappear whilst there was still a reference to it.
However, you don't have to use this method. My preference with what you describe would be to have two clases, changelist and change. When you create an instance of the change class, pass a changelist object (null if you don't want it associated with a changelist) with the constructor and add the change to that list before returning it.
Alternatively, have a changelist method which creates a change itself and returns it, remembering the change for its own purposes.
Then you can query the changelist to get recent changes (however you define recent). That would be more flexible since it allows multiple lists.
You could even go overboard and allow a change to be associated with multiple changelists if so desired.
Another reason to return this is so that you can do function chaining:
class foo
{
private int x;
public foo()
{
this.x = 0;
}
public foo Add(int a)
{
this.x += a;
return this;
}
public foo Subtract(int a)
{
this.x -= a;
return this;
}
public int Value
{
get { return this.x; }
}
public static void Main()
{
foo f = new foo();
f.Add(10).Add(20).Subtract(1);
System.Console.WriteLine(f.Value);
}
}
$ ./foo.exe
29
There's a time and a place to do function chaining, and it's not "anytime and everywhere." But, LINQ is a good example of a place that hugely benefits from function chaining.
A class will often return an instance of itself from what is sometimes called a "factory" method. In Java or C++ (etc) this would usually be a public static method, e.g. you would call it directly on the class rather than on an instance of a class.
In your case, in Java, it might look something like this:
List<Change> changes = Change.getRecentChanges();
This assumes that the Change class itself knows how to track changes itself, rather than that job being the responsibility of some other object in the system.
A class can also return an instance of itself in the singleton pattern, where you want to ensure that only one instance of a class exists in the world:
Foo foo = Foo.getInstance();
The fluent interface methods work on the principal of returning an instance of itself, e.g.
StringBuilder sb = new StringBuilder("123");
sb.Append("456").Append("789");
You need to think about what you're trying to model. In your case, I would have a ChangeList class that contains one or more Change objects.
On the other hand, if you were modeling a hierarchical structure where a class can reference other instances of the class, then what you're doing makes sense. E.g. a tree node, which can contain other tree nodes.
Another common scenario is having the class implement a static method which returns an instance of it. That should be used when creating a new instance of the class.
I don't know of any design rule that says that's bad. So if in your model a single change can be composed of multiple changes go for it.