Typical lazy singleton:
public class Singleton {
private static Singleton INSTANCE;
private Singleton() {
}
public static synchronized Singleton getInstace() {
if(INSTANCE == null)
INSTANCE = new Singleton();
return INSTANCE;
}
}
Typical eager singleton:
public class Singleton {
private static Singleton INSTANCE = new Singleton();
public static Singleton getInstance() {
return INSTANCE;
}
}
Why are we not concerned about synchronization with eager singletons, but have to worry about synchronization with their lazy cousins?
Eager instantiation does not require explicit synchronisation for sharing the reference of the field because the JVM will have handled it for us already as part of the class loading mechanism.
To elaborate in more detail, before a class becomes available to any thread for use, it will have been loaded, verified and initialised. The compiler rewrites the static field assignment into this initialisation stage and via the rules of the Java Memory Model and the underlying hardware architecture will ensure that all threads who access that class will see this version of the class. This means that the JVM will have handled any hardware barriers etc for us.
That said, I would recommend marking the eager initialisation final. This will make your intent clearer and the compiler will enforce that the eager initialisation never changes. If it did, then concurrency control would be required again.
private static **final** Singleton INSTANCE = new Singleton();
FYI If you are interested, section 5.5 of the Java Virtual Machine Specification covers this in much more detail. A couple of choice snippets from the spec are
*"Because the Java Virtual Machine is multithreaded,
initialization of a class or interface requires careful
synchronization"*
*"For each class or interface C, there is a unique initialization lock LC"*
*9&10) "Next, execute the class or interface initialization method of C"
"If the execution of the class or interface initialization
method completes normally, then acquire LC, label the Class object for
C as fully initialized, notify all waiting threads, release LC, and
complete this procedure normally."*
It is in step 10 of the spec where the static fields will have been set, and the use of a lock (LC) is used to ensure that only one thread performs the initialisation and that the result is shared correctly.
Since an eager singleton is initialized when the class if first loaded into memory (jit) and this happens only once. However if two clients will try to call the singleton instance method from two threads at the same time, two singletons may be created.
Because in the latter example the instance of the Singleton is always present when the getInstance is called - nothing to synchronize here. That is in contrary to the first example where the instance isn't necessary initialized yet. In this case the getInstance contains critical section (the if and it's body) which needs to be protected (e.g. by synchronization) against simultaneous access.
Related
When reading about singletons, I have found this explanation as a reason to use singleton:
since these object methods are not changing the internal class state, we
can create this class as a singleton.
What does this really mean ? When you consider that some method is not changing internal class state ? If it is a getter ? Can someone provide code examples for class that uses methods that are not changing its internal state, and therefore can be used as a singleton, and class that should not be a singleton ?
Usually, when people are explaining singleton pattern, they use DB connection class as an example. And that makes sense to me, because I know that I want to have only one db connection during one application instance. But what if I want to provide an option to force using the new connection when I instantiate DB connection class? If I have some setter method, or constructor parameter that forces my class to open new connection, is that class still a subject to be a singleton ?
I am using PHP, but may understand examples written in JAVA, C#...
This is the article reference. You can ctrl+f search for "internal". Basically, autor is explaining why FileStorage class is a good candidate to be a singleton. I do not understand this sentance
"These operations do not change the internal class state, so we can
create its instance once and use it multiple times."
and therefore I do not understand when to use singletons.
In their example, they have some FileStorage class :
class FileStorage
{
public function __contruct($root) {
// whatever
}
public function read() {
// whatever
}
public function write($content) {
// whatever
}
}
And they say that this class can be a singleton since its methods read() and write() do not chage internal class structure. What does that mean ? They are not setters and class is automatically singleton ?
The quote reads:
These operations do not change the internal class state, so we can create its instance once and use it multiple times.
This means that the object in question has no interesting internal state that could be changed; it’s just a collection of methods (that could probably be static). If the object has no internal state, you don’t have to create multiple instances of it, you can keep reusing a single one. Therefore you can configure the dependency injection container to treat the object as a singleton.
This is a performance optimization only. You could create a fresh instance of the class each time it’s needed. And it would be better – until the object creation becomes a measurable bottleneck.
I am developing a compiler for an object oriented language targeted on a virtual machine I wrote that I am using as a cross platform abstraction layer. I am sort of confused about how inherited methods works. Lets say I had the following lines of C# code.
class myObject : Object {
public int aField;
public override string ToString() {
return "Dis be mah object";
}
public void regularMethod() { }
}
Object test = new myObject();
Console.WriteLine(test.ToString());
Now this would output 'Dis be mah object'. If I called regularMethod however the compiled code would in reality do something like this:
struct myObject {
public int aField;
}
public static void regularMethod(ref myObject thisObject)
{
}
How would the inherited method ToString be handled after compilation? The compiler could not do what I did above with regularMethod, because if it did then 'Dis be mah object' would only be returned when creating myObject types and not plain Object types. My guess is that the struct myObject would contain a function pointer/delegate that would get assigned when a new instance is created.
If you are dealing with static overloading, it is really simple: you bind to the correct implementation when processing the code.
But, if you are working with dynamic overloading, you must decide things at runtime. For this you need to use dynamic dispatch, using the real object type. This is the same thign that is done with method overriding.
Dynamic dispatching is not the same as late binding. Here, you are chosing an implementation and not a name for your operation (despite the fact that this binding will occur at compile time, the implementation will only occur at runtime).
Staticly, you would only bind to implementation of the declared type of the object. It is done at compile time.
The are some mechanisms you could use to achieve the dynamic dispathing, it will dictate your language paradigm.
Is your language typed? Weakly typed?
C++, for instance, offers the two types of dispatch I mentioned. For the dynamic one (which I believe is the one you are interested), it uses a virtual table to do the mapping for one class. Each instance of that class will point have a pointer to that vtable.
Implementing
The vtable (one for all objects of same class) will have the addresses of all dynamicly bound methods. One of those addresses will be fetched from this table when a call is made. Type-compatible objects have tables with addresses with the same offset for the methods of all compatible classes.
Hope I've helped.
I have little doubt about adapter class. I know what's the goal of adapter class. And when should be used. My doubt is about class construction. I've checked some tutorials and all of them say that I should pass "Adaptee" class as a dependency to my "Adapter".
e.g.
Class SampleAdapter implements MyInterface
{
private AdapteeClass mInstance;
public SampleAdapter(AdapteeClass instance)
{
mInstance=instance;
}
}
This example is copied from wikipedia. As you can see AdapteeClass is passed to my object as dependency. The question is why? If I'm changing interface of an object It's obvious I'm going to use "new" interface and I won't need "old" one. Why I need to create instance of "old" class outside my adapter. Someone may say that I should use dependency injection so I can pass whatever I want, but this is adapter - I need to change interface of concrete class. Personally I think code bellow is better.
Class SampleAdapter implements MyInterface
{
private AdapteeClass mInstance;
public SampleAdapter()
{
mInstance= new AdapteeClass();
}
}
What is your opinion?
I would say that you should always avoid the new operator in a class when it comes to complex objects (except when the class is a Builder or Factory) to reduce coupling and make your code better testable. Off course objects like a List or Dictionary or value objects can be constructed inside a class method (which is probably the purpose of the class method!)
Lets say for example that your AdapteeClass is a Remote Proxy. If you want to use Unit Testing, your unit tests will have to use the real proxy class because there is no way to replace it in your unit tests.
If you use the first approach, you can easily inject a mock or fake into the constructor when running your unit test so you can test all code paths.
Google has a guide on writing testable code which describes this in more detail but some important points are:
Warning Signs for not testable code
new keyword in a constructor or at field declaration
Static method calls in a constructor or at field declaration
Anything more than field assignment in constructors
Object not fully initialized after the constructor finishes (watch out for initialize methods)
Control flow (conditional or looping logic) in a constructor
Code does complex object graph construction inside a constructor rather than using a factory or builder
Adding or using an initialization block
AdapteeClass can have one or more non-trivial constructors. In this case you'll need to duplicate all of them in your SampleAdapter constructor to have the same flexibility. Passing already constructed object is simpler.
I think creating the Adaptee inside the Adapter is limiting. What if some day you want to adapt a pre-existing instance?
To be honest though, I'd do both if at all possible.
Class SampleAdapter implements MyInterface
{
private AdapteeClass mInstance;
public SampleAdapter()
: base (new AdapteeClass())
{
}
public SampleAdapter(AdapteeClass instance)
{
mInstance=instance;
}
}
Let's assume you have an external hard drive with a regular USB port and you are trying to hook it up with a Mac which only has type-c ports. Yes, you can buy a new drive which has a type-c port but what about the data in it?
It's the same for the adapter pattern. There're times you initialize AdapteeClass with tons of flavors. When you do the conversion, you want to keep all the context.
Context: .NET, C#, but the question is about OOP in general.
When I write a class that should act as a "service", like a socket listener, or a timer, I see two approaches when it comes to coding it:
Create a constructor, and inside the constructor, immediately start the background task. For instance:
public class MyTimer
{
private readonly TimeSpan interval;
public MyTimer(TimeSpan interval)
{
this.interval = interval;
StartTicking();
}
private void StartTicking()
{
// do the ticking logic
}
}
Create a constructor that accepts the class' settings, and add an explicit method for starting up:
public class MyTimer
{
private readonly TimeSpan interval;
public MyTimer(TimeSpan interval)
{
this.interval = interval;
}
public void StartTicking()
{
// do the ticking logic
}
}
I tend to think that the second approach is better:
A. The constructor is used only for creating a valid instance, keeping it minimal and clean.
B. The developer who actually uses my class is less astonished.
C. The hardware resources are not overused, since the "service" class does not immediately use them.
What do you think? Is it only a matter of coding style, or is it more than that?
Keep your constructor minimal, and require the calling code to call a specific function in order to do anything but the most simple initialization. This is what the Stopwatch class does in .NET, for instance.
Besides avoiding surprises for the person invoking the constructor, this also allows you to make better use of Dependency Injection (i.e. having your class injected into the constructor of a class that needs it, but which doesn't want to use it right way).
I've also found that certain types of bugs are more difficult to catch when they occur in constructors than when they are in some other method.
Don't start running in your constructor.
Users of your API won't expect that, and it makes your class harder to use
From an exception handling standpoint, you want to be able to report an error that happens when constructing an object, separately from an error that happens during execution.
It prevents sharing instances of your object, if you ever wanted to do something like a static factory singleton pattern.
I would second StriplingWarrior's point that there are many good reasons, like dependency injection, where object creation needs to happen first so that some other class can run it later.
Nearly every service-type class that I've seen exposes methods to start and stop it. If it is auto-starting, it is usually very explicitly so (the class name might be MyAutostartingTimer or something..)
I want to implement singleton for httpconnection....
I have a servlet as a server and client side I use android. I have to use the connection many times. Currently, each time I am doing a new connection, but that is not the right way.. So I want to implement singleton for the httpconnection so I can use that instance in each android class.....
so help me.. what type of code i write..
Show some code from what you have, and I can help you more...
Off the cuff, I would say make the httpconnection object a member variable of the class, and any time you're making a new one, reference the member variable instead.
While binding a singleton with a live HTTPUrlConnection instance is good from a reusable practice, but you should also consider how often a call will be made to the server. If your Android application[s] make a lot of connections and need fast response, then there's no point creating a chokehold on such a resource. But if that's not the case, you can simply have an instance variable, and initialise it within the constructor of your particular class. Something like -
public SomeClass {
HTTTPUrlConnection conn = new HTTPUrlConnection(...);
SomeClass instance = new SomeClass();
private SomeClass() {}
public static getInstance() {
return instance;
}
}
Some might contend why initialise the instances inline and not within the getInstance method, but i believe this is best in terms of thread safety. Just Google on Singletons are not good from thread-safety perspective.