What is lazy instantiation - c#

Is lazy instantiation about using less code but getting the same result? Surely this is generally a good thing to do (providing making the code to short / efficient doesn't damage readability/maintainability).
Please refer to this lazy instantiation:
public sealed class Singleton
{
private Singleton()
{
}
public static Singleton Instance { get { return Nested.instance; } }
private class Nested
{
// Explicit static constructor to tell C# compiler
// not to mark type as beforefieldinit
static Nested()
{
}
internal static readonly Singleton instance = new Singleton();
}
}
There is no private property of Instance (I know it's implicit) - is it that which makes it lazy - the fact we don't have a setter within the public static Singleton Instance property?

Lets say we have a field of a type that is expensive to construct
class Foo
{
public readonly Expensive expensive = new Expensive();
...
}
The problem with this code is that instansiating Foo incurs the performance cost of instansiating Expensive - whether-or-not the Expensive field is ever accessed. The obvious answer is to construct the instance on demand or lazily instansiate the field:
class Foo
{
Expensive _expensive;
public Expensive
{
get
{
if (_expensive == null) _expensive = new Expensive();
return _expensive;
}
}
...
}
This is lazy instansiation.

Lazy initialization is a practice whereby you only load or initialize an object when you first need it.
Potentially, this can give you a big performance boost, especially if you have a vast amount of components in your application.
Look at the Wikipedia page for a greater insight (it features coded examples).

No, lazy instantiation means not spending any time and resources creating something until you actually need it.
In your singleton example, the instance is just an empty reference, until it's actually used. When it's used, then you spend the resources to instantiate the object with a new.

Lazy initialization of an object means that its creation is deferred until it is first used.
For complete reference see msdn post Lazy Initialization
In your above code, the instance of the singleton class is not created until you call it.
So, your program will not use resources until your code gets called.

It's lazy because the instance of the class Singleton isn't created until the first time you ask for it.

Related

Disposing Lazy Singleton object [duplicate]

I have a singleton that uses the "static readonly T Instance = new T();" pattern. However, I ran into a case where T is disposable, and actually needs to be disposed for unit tests. How can I modify this pattern to support a disposable singleton?
The interface I would like is something like:
var x = Foo.Instance;
var y = Foo.Instance; // x == y
...
x.Release(); // this causes the next Foo.Instance to return a fresh object
// also, it assumes no further operations on x/y will be performed.
Note - the pattern has to be thread-safe, of course.
Edit - for the purpose of production code, this is a true singleton. The thing is that it locks some files, and so for cleanup in unit tests we have to dispose it.
I would also prefer a pattern that can be reused, if possible.
At that point I don't think I'd really consider it to be a singleton any more, to be honest.
In particular, if a client uses a singleton they're really not going to expect that they have to dispose of it, and they'd be surprised if someone else did.
What's your production code going to do?
EDIT: If you really, really need this for unit tests and only for unit tests (which sounds questionable in terms of design, to be frank) then you could always fiddle with the field using reflection. It would be nicer to work out whether it should really be a singleton or whether it should really be disposable though - the two very rarely go together.
Mark Release as internal and use the InternalsVisibleTo attribute to expose it only to your unit testing assembly. You can either do that, or if you're wary someone in your own assembly will call it, you can mark it as private and access it using reflection.
Use a finalizer in your singleton that calls the Dispose method on the singleton instance.
In production code, only the unloading of an AppDomain will cause the disposal of the singleton. In the testing code, you can initiate a call to Release yourself.
Singletons should not be Disposable. Period. If someone calls Dispose prematurely, your application is screwed until it restarts.
public class Foo : IDisposable
{ [ThreadStatic] static Foo _instance = null;
private Foo() {IsReleased = false;}
public static Foo Instance
{ get
{ if (_instance == null) _instance = new Foo();
return _instance;
}
}
public void Release()
{ IsReleased = true;
Foo._instance = null;
}
void IDisposable.Dispose() { Release(); }
public bool IsReleased { get; private set;}
}
If the class implements IDisposable (as you imply it does) then just call x.Dispose()
You could use a nested lazy singleton (See here) with some simple modifications:
public sealed class Singleton : IDisposable
{
Singleton()
{
}
public static Singleton Instance
{
get
{
if (!Nested.released)
return Nested.instance;
else
throw new ObjectDisposedException();
}
}
public void Dispose()
{
disposed = true;
// Do release stuff here
}
private bool disposed = false;
class Nested
{
// Explicit static constructor to tell C# compiler
// not to mark type as beforefieldinit
static Nested()
{
}
internal static readonly Singleton instance = new Singleton();
}
}
Remember to throw ObjectDisposedException in all public methods/properties of the object if it has been disposed.
You should also, provide a finalizer method for the object, in case Dispose doesn't get called. See how to correctly implement IDisposable here.
For unit tests you could use a "manual" instance (but you would need a way to instantiate the object).
In your case, probably you should better use the factory pattern (abstract/method - whichever is the best for your case), combined with a singleton.
If you want to test if the singleton has disposed properly of the used objects (in unit test), then use the Factory method, otherwise use the singleton pattern.
By the way, if you don't have access to the singleton source code or you are not allowed to modify it, you would better wrap it to another singleton, and provide all the logic from the new one (more like a proxy). It sounds like overkill, but it could be a viable solution.
Also, in order to be able to control the access to it, provide a factory, and let the clients get the new object only if the object hasn't been disposed.
Another option to make a disposable Singleton is to use SandCastle's [Singleton] atribute for your class, then Castle framework takes care of disposing all disposable Singleton objects

Have I been doing locks wrong this whole time?

I was reading this article about thread safety in Singletons, and it got me thinking that I don't understand the lock method.
In the second version, the author has this:
public sealed class Singleton
{
private static Singleton instance = null;
private static readonly object padlock = new object();
Singleton()
{
}
public static Singleton Instance
{
get
{
lock (padlock)
{
if (instance == null)
{
instance = new Singleton();
}
return instance;
}
}
}
}
Whereas I would've done something more like this:
public sealed class Singleton
{
private static Singleton instance = null;
Singleton()
{
}
public static Singleton Instance
{
get
{
lock (instance)
{
if (instance == null)
{
instance = new Singleton();
}
return instance;
}
}
}
}
Why would you use a padlock object, rather than locking the actual object you want to lock?
What would you expect to happen the first time you accessed the Instance property, before you've got an object to lock on?
(Hint: lock(null) goes bang...)
As a separate measure, I almost always avoid locking on "the actual object" - because typically there may well be other code which that reference is exposed to, and I don't necessarily know what that's going to lock on. Even if your version did work, what would happen if some external code wrote:
// Make sure only one thread is ever in this code...
lock (Singleton.Instance)
{
// Do stuff
}
Now no-one else can even get the instance while that code is executing, because they'll end up blocked in the getter. The lock in the getter isn't meant to be guarding against that - it's only meant to be guarding against multiple access within the getter.
The more tightly you can keep control of your locks, the easier it is to reason about them and to avoid deadlocks.
I very occasionally take a lock on a "normal" object if:
I'm not exposing that reference outside that class
I have confidence that the type itself (which will always have a reference to this, of course) won't lock on itself.
(All of this is a reason to avoid locking on this, too, of course...)
Fundamentally, I believe the idea of allowing you to lock on any object was a bad idea in Java, and it was a bad move to copy it in .NET :(
Locking on this or any other non-private object is dangerous because it can lead to deadlocks if someone else also tries to use that object for synchronization.
It's not terribly likely, which is why people can be in the habit of doing it for years without ever getting bitten. But it is still possible, and the cost of a private instance of object probably isn't great enough to justify running the risk.
For locking you can use any kind of object, the type really doesn't matter, it just used as a flag and only one thread can hold it in a time.
It is of course possible to have this as locking param. But I guess the main reason why it's not recommended is that other class somewhere can also use instance of your class as locking object and that can cause strage problems

Is a class instantiated when a static method is called in a non-static class?

Exactly what happens when Foo.SomeCheck() is called in the Bar class? Is an instance of Foo created in order to call SomeCheck()? If so, is this instance stored on the heap, and is it ever collected through garbage collection?
public class Foo() {
public static bool SomeCheck() {
return true;
}
}
public class Bar() {
public void SomeMethod() {
// what happens when we access Foo to call SomeCheck?
if (Foo.SomeCheck()) {
//do something
}
}
}
Static methods differ from instance methods in that no instance of the class they belong to needs to have been created for them to be called. When you call a static method, you in fact make the call using the name of the type rather than an instance of the type - which should reinforce the idea that static methods are not called on instances. That bears repeating and emphasis: No instance of a class is required to call a public static method of that class.
Now, your example is malformed, but presumably, the line: if( Foo.SomeCheck() ) is calling the SomeCheck static method using the name of the type: Foo - not an instance. Bar however, has to be instantiated in order to make this call - however, in your example, you don't have a well-formed instance of Bar. Code generally has to exist inside a method (or a member initializer) - which you don't have here.
To respond to the other parts of your question. Assuming the code in question is part of an instance method, something has to instantiate Bar - and invoke that method. That something would have to create or otherwise acquire an instance of Bar. Reference types will always be creted on the heap - but that's largely irrelevant here.
As for garbage collection, you normally shouldn't worry about this. The .NET runtime makes sure to cleanup instances that are not referenced from any root object in your program. Roots are typically instances that reside somewhere on the callstack or are referenced by static members of one type or another. Since we don't see any code here that creates or references Bar it's impossible to say when it will be collected. For instance, if Bar is a singleton and stored somewhere in a static variable, it may live for a very long time - perhaps the entire lifetime of the program. You can't really know without seeing all of the code that manipulates and manages Bar.
I highly recommend reading the following article:
Drill Into .NET Framework Internals to See How the CLR Creates Runtime Objects
It explains how the .NET runtime works at a low level, and explains internal nuances like Loader Heaps and how static classes/members work. Technically speaking, there IS an initial instantiation of the 'static instnace' of a classes static members. However, this initiation is handled by the runtime in a different way than it is handled for class instances. Static classes are stored on loader heaps, which are not GC managed. Loader heaps are allocated and grown in a static manner, and are not compacted. The article is a great read, and should give you a thourough understanding of how the CLR operates.
(NOTE: I am not certain of how valid this article is for .NET 4. I do know that there were GC changes in .NET 4, however I am not sure how many fundamental runtime changes there are. The introduction of the DLR and other features may deviate from the explanation in the above article to some degree.)
Foo does not need to be instantiated, neither will it get instantied upon the SomeCheck static method call as per result, you would get the value returned by the method itself, and not an instance of the class.
Please have a look at these references for further details:
Static vs Non-Static Methods;
Static Classes and Static Class Members (C# Programming Guide).
I do hope this helps! =)
It depends on the implementation of SomeMethod. The method will have to be invoked from somewhere, presumably a "driver" class which would instantiate Bar and call SomeMethod. For example:
public class Driver
{
public static void Main()
{
Bar bar = new Bar();
bar.SomeMethod();
}
}
Given your current implementation of SomeMethod, yes, you'd have to instantiate it.
However, as long as SomeMethod only makes a call to another static method, we could make make it static too. In which case you wouldn't have to create an instance of Bar to invoke the method. i.e.
public class Driver
{
public static void Main()
{
Bar.SomeMethod();
}
}
public class Manipulate
{
public static int Main(string[] args) {
Bar bar = new Bar();
bar.BarFoo();
Console.ReadKey();
return 0;
}
}
public class Foo {
public static bool SomeCheck() {
return true;
}
}
public class Bar {
// what happens when we access Foo to call SomeCheck?
public void BarFoo() {
if (Foo.SomeCheck()) {
Console.WriteLine("Hello am true");
}
}
}
Yes you need to create an instance of Bar but not for Foo class since it is a static metod. Only difference is, the static methods are called at class level(compile time) rather than object level(run time), so you don't need to instantiate the Foo class.

lazy initialization of singletons

While reading Jon Skeet's article on singletons in C# I started wondering why we need lazy initialization in a first place. It seems like the fourth approach from the article should be sufficient, here it is for reference purposes:
public sealed class Singleton
{
static readonly Singleton instance=new Singleton();
// Explicit static constructor to tell C# compiler
// not to mark type as beforefieldinit
static Singleton()
{
}
Singleton()
{
}
public static Singleton Instance
{
get
{
return instance;
}
}
}
In the rare circumstances, where you have other static methods on a singleton, lazy initialization may have benefits, but this is not a good design.
So can people enlighten me why lazy initialization is such a hot thing?
In those scenarios where whatever it is you are initializing might not be needed at all, and is expensive to initialize, (in terms of CPU cycles or resources), then implementing a lazy initializor saves that cost in those cases where the object is not required.
If the object will always be required, or is relatively cheap to initialize, then there is no added benefit from a lazy initializer.
In any event, implementing a lazy initializer improperly can make a singleton non-thread-safe, so if you need this pattern, be careful to do it correctly. Jon's article has a pattern, (I think it's the last one), that addresses this issue.
You don't need lazy initialization on a singleton, if the only reason you're going to use that type is to reference the instance.
If, however, you reference any other property or method on the type, or the type itself, you will initialize the singleton.
Granted, good design would leave one task for one type, so this shouldn't be a problem. If you make your singleton class to "complex", however, lazy initialization can help keep you from having consequences due to initializing too soon.
I'm not sure that this applies to C# as well, but I'll answer for C++:
One of the ideas behind Singletons is that the order of initialization of static objects is undefined. So if you have a static class that tries to use another static class, you might be in trouble.
A concrete example: Let's say I have a Log class, which I decided to implement as a Singleton. Let's also assume I have a method called LoadDB, which for whatever reason, is a static called at the start of the program. Assuming LoadDB decides it needs to log something, it will call the Singleton. But since the order of static initialization is undefined, it might be doing something that's an error.
A Singleton fixes this, since once you call GetInstance(), no matter where you are in the initialization process, the object is guaranteed to exist.
Again, I don't know if this is relevant, but at least that's the history of it (as far as I remember).
From Java DI perspective, lazy initialization is good, there are always (say, spring) beans in another API that you might not want to use, for example, an eagerly loaded singleton cache (something that is shared with everyone using the cache) might not be needed for you although it may be referred as a dependency in your same code. Whats the point in loading the singleton wasting resources?
The lazy initialization implementation choice is tricky, in spring, would you choose lazy-init="true" (spring eagerly instantiates singletons), an init-method/destroy-method, #PostConstruct, InitializingBean - afterPropertiesSet() method or return same spring instance in a getInstance() method?
The choice is a tradeoff of testability over reusability outside the spring container.

Advantages to Using Private Static Methods

When creating a class that has internal private methods, usually to reduce code duplication, that don't require the use of any instance fields, are there performance or memory advantages to declaring the method as static?
Example:
foreach (XmlElement element in xmlDoc.DocumentElement.SelectNodes("sample"))
{
string first = GetInnerXml(element, ".//first");
string second = GetInnerXml(element, ".//second");
string third = GetInnerXml(element, ".//third");
}
...
private static string GetInnerXml(XmlElement element, string nodeName)
{
return GetInnerXml(element, nodeName, null);
}
private static string GetInnerXml(XmlElement element, string nodeName, string defaultValue)
{
XmlNode node = element.SelectSingleNode(nodeName);
return node == null ? defaultValue : node.InnerXml;
}
Is there any advantage to declaring the GetInnerXml() methods as static? No opinion responses please, I have an opinion.
From the FxCop rule page on this:
After you mark the methods as static, the compiler will emit non-virtual call sites to these members. Emitting non-virtual call sites will prevent a check at runtime for each call that ensures that the current object pointer is non-null. This can result in a measurable performance gain for performance-sensitive code. In some cases, the failure to access the current object instance represents a correctness issue.
When I'm writing a class, most methods fall into two categories:
Methods that use/change the current instance's state.
Helper methods that don't use/change the current object's state, but help me compute values I need elsewhere.
Static methods are useful, because just by looking at its signature, you know that the calling it doesn't use or modify the current instance's state.
Take this example:
public class Library
{
private static Book findBook(List<Book> books, string title)
{
// code goes here
}
}
If an instance of library's state ever gets screwed up, and I'm trying to figure out why, I can rule out findBook as the culprit, just from its signature.
I try to communicate as much as I can with a method or function's signature, and this is an excellent way to do that.
A call to a static method generates a call instruction in Microsoft intermediate language (MSIL), whereas a call to an instance method generates a callvirt instruction, which also checks for a null object references. However, most of the time the performance difference between the two is not significant.
Source: MSDN - https://learn.microsoft.com/en-us/previous-versions/visualstudio/visual-studio-2012/79b3xss3(v=vs.110)
Yes, the compiler does not need to pass the implicit this pointer to static methods. Even if you don't use it in your instance method, it is still being passed.
It'll be slightly quicker as there is no this parameter passed (although the performance cost of calling the method is probably considerably more than this saving).
I'd say the best reason I can think of for private static methods is that it means you can't accidentally change the object (as there's no this pointer).
This forces you to remember to also declare any class-scoped members the function uses as static as well, which should save the memory of creating those items for each instance.
I very much prefer all private methods to be static unless they really can't be. I would much prefer the following:
public class MyClass
{
private readonly MyDependency _dependency;
public MyClass(MyDependency dependency)
{
_dependency = dependency;
}
public int CalculateHardStuff()
{
var intermediate = StepOne(_dependency);
return StepTwo(intermediate);
}
private static int StepOne(MyDependency dependency)
{
return dependency.GetFirst3Primes().Sum();
}
private static int StepTwo(int intermediate)
{
return (intermediate + 5)/4;
}
}
public class MyDependency
{
public IEnumerable<int> GetFirst3Primes()
{
yield return 2;
yield return 3;
yield return 5;
}
}
over every method accessing the instance field. Why is this? Because as this process of calculating becomes more complex and the class ends up with 15 private helper methods, then I REALLY want to be able to pull them out into a new class that encapsulates a subset of the steps in a semantically meaningful way.
When MyClass gets more dependencies because we need logging and also need to notify a web service (please excuse the cliche examples), then it's really helpful to easily see what methods have which dependencies.
Tools like R# lets you extract a class from a set of private static methods in a few keystrokes. Try doing it when all private helper methods are tightly coupled to the instance field and you'll see it can be quite a headache.
As has already been stated, there are many advantages to static methods. However; keep in mind that they will live on the heap for the life of the application. I recently spent a day tracking down a memory leak in a Windows Service... the leak was caused by private static methods inside a class that implemented IDisposable and was consistently called from a using statement. Each time this class was created, memory was reserved on the heap for the static methods within the class, unfortunately, when the class was disposed of, the memory for the static methods was not released. This caused the memory footprint of this service to consume the available memory of the server within a couple of days with predictable results.

Categories