This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Singleton: How should it be used
why we should use singleton class
Well, I would try to avoid using them since effectively you are introducing global elements into your project. However you may decide to use them if you have a resource in your project that you only want to ever have one of. For instance a link to a single database source, a cache or a Factory.
don't............
You are building an application in C#. You need a class that has only one instance, and you need to provide a global point of access to the instance. You want to be sure that your solution is efficient and that it takes advantage of the Microsoft .NET common language runtime features. You may also want to make sure that your solution is thread safe.
Benefits
#
The static initialization approach is possible because the .NET Framework explicitly defines how and when static variable initialization occurs.
#
The Double-Check Locking idiom described earlier in "Multithreaded Singleton" is implemented correctly in the common language runtime.
Liabilities
If your multithreaded application requires explicit initialization, you have to take precautions to avoid threading issues.
Related
This question already has answers here:
Instantiating Internal class with private constructor
(5 answers)
Closed 7 years ago.
I'm either googling the wrong thing or trying to head down the completely wrong path (most likely)... but now I'm curious so I thought I'd ask.
Long story short, I'm trying to tap into the underlying "API" framework of Microsoft's Message Analyzer tool for a custom application. I say "API" because there is no formal support for an API, no documentation, and there won't be any in the near future, if ever (so says Paul at Microsoft anyway). So instead I've been using the IL DASM tool to poke around some of the Message Analyzer and PowerShell .dlls to try to get an understanding of how this stuff works; the ultimate goal of course is to use MA's .dlls and drivers to do what I want for the custom app. I'm looking at Microsoft.Protocols.Tools.PowerShell.dll, which has a class (Microsoft.Protocols.Tools.PowerShell.PpkTraceSession) that I'm trying to instantiate:
However, if you look right below it, it says something about the class being private (it's cut off in the picture, but the class does implement IPpkTraceSession and IPpkTraceSessionEx). Sure enough, when I reference this .dll in some C# code and try to instantiate an object, I get a compile error saying its inaccessible due to its protection level:
Windows PowerShell has no problem at all creating one of these objects. It just so happens the printout seen below matches all the properties (not seen in the first picture) of the PpkTraceSession class, so I know Windows PowerShell is working some magic to create an object of that class,, I just can't figure out how since apparently this class is private.
So my question,, what's going on here? I've poked around in a lot of the classes shown in the IL DASM output, and there are a surprising number of them that appear to be private. Maybe it's just my bad practice, but I've rarely if ever used or seen many private classes. It's my understanding they have to be nested in other classes to be of any particular use. If PpkTraceSession is nested in another class, that's not clear from the IL DASM output at all. You may see the IPpkTraceSession(Ex) interfaces above,, if there's a way to access the class properties using those I haven't figured it out yet. Is there anyway to instantiate an object of this class, or am I going about this all wrong?
This might be close to a duplicate, but not quite I don't think. Any help is much appreciated! I clearly don't know much about Windows programming.
yano
EDIT:::::
Just to tie off all the loose ends (in case somebody else makes my mistake), I discovered the source of my confusion a couple of days ago. All the classes indicated as "private" by the IL DASM tool are actually "internal" classes, meaning that they're meant to be visible only within their own assembly. That was my missing piece, I couldn't understand where all these private classes were coming from when C# won't even let you compile a standalone private class (it must be nested within another class). I should've done some more research on IL DASM before I posted a question, but it didn't even occur to me; I thought private meant private. It's my observation that IL DASM does make a distinction between private/internal classes and nested private classes. This issue has also already been addressed here: When I declare a class as internal, why does the IL show it as private? . Thanks for the help everyone!
I suspect that what you are seeing is that other classes, probably deep inside the PowerShell plumbing, might expose some of the properties of the PpkTraceSession class. You might be able to find them by inspecting the intermediate language of the public classes exposed by the same dll THAT contains the private PpkTraceSession class. However, I suspect that you are wasting your time, and will not find a way to use those classes in your own code.
They are marked private because Microsoft has no intention of supporting them, and their behavior might change without notice. That isn't a problem within the PowerShell team, which has access to them, most likely through other private classes. So, if they need to change the way one of those classes behaves, they can do it, and the affected audience is small and easily reachable.
Speaking as a developer, I can think of a host of reasons that Microsoft might not want to support it, such as that it is very fussy, or that doing so would involve disclosing proprietary or patented technology that they have a legal right to keep secret.
Perhaps you could start a campaign to make them public, but you'll need to make a really good case, and convince a lot of other people, preferably people who already pay Microsoft a lot of money, to get behind you.
Our ticket system vendor provides an .NET API library and I've been trying to make use of this from a multi-threaded application. I'm running into all sorts of connection/stateful issues and I believe this is perhaps because it's not "thread-safe" (I'm still a novice with C# and threaded applications, so just my guess at the moment as some of the symptoms line up).
The API doesn't have a class that is instantiated, you just call the static methods TrebuchetApi.Api.Connect() and TrebuchetApi.Api.Login() from it's namespace (in fact all methods appear to be static).
So I maybe have one thread doing one thing, and another doing something else, and the underlying API is getting confused (static variables that should be set are null and such).
Is there any way of making each of my threads use a brand new 'instance' of the API, or is it simply unavoidable?
Update:
For clarity, after the suggestions for using AppDomains I found this article which provided the exact framework I needed:
http://www.superstarcoders.com/blogs/posts/executing-code-in-a-separate-application-domain-using-c-sharp.aspx
Using appdomains seems like the way to go.
See How do I prevent static variable sharing in the .NET runtime? or In .Net is the 'Staticness' of a public static variable limited to an AppDomain or the whole process? for similar questions people had.
The msdn guide can be found here http://msdn.microsoft.com/en-us/library/ms173138(v=vs.90).aspx
Just keep in mind that AppDomain is a .net concept, unmanaged resources can still be an issue.
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
On Design Patterns: When to use the Singleton?
Hi
Just wondering what are good candidates for singleton?
Just reading about it and wondering if sometimes I have misused it.
Generally speaking when would you use a singleton?
thanks a lot
Basically, whenever I need a class but am not sure I will need a singleton pattern, I code to the singleton interface, but let the implementing class determine whether or not to return a single instance or a new instance. That way, calling classes don't have to worry about changing if the move to singleton (or the move away from singleton) should occur.
Places I've used this successfully is on my repositories. But I always preface every singleton answer with a 'Make sure you pay attention to thread-safety, whichever way you go'. Sometimes weird things can happen in a multi-threaded environment when dealing with a singleton.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
For c# developers that are staring out to learn Java, are there any big underlying differences between the two languages that should be pointed out?
Maybe some people may assume things to be the same, but there are some import aspects that shouldn't be overlooked? (or you can really screw up!)
Maybe in terms of OOP constructs, the way GC works, references, deployment related, etc.
A few gotchas off the top of my head:
Java doesn't have custom value types (structs) so don't bother looking for them
Java enums are very different to the "named numbers" approach of C#; they're more OO. They can be used to great effect, if you're careful.
byte is signed in Java (unfortunately)
In C#, instance variable initializers run before the base class constructor does; in Java they run after it does (i.e. just before the constructor body in "this" class)
In C# methods are sealed by default. In Java they're virtual by default.
The default access modifier in C# is always "the most restrictive access available in the current context"; in Java it's "package" access. (It's worth reading up on the particular access modifiers in Java.)
Nested types in Java and C# work somewhat differently; in particular they have different access restrictions, and unless you declare the nested type to be static it will have an implicit reference to an instance of the containing class.
here is a very comprehensive comparison of the 2 languages:
http://www.25hoursaday.com/CsharpVsJava.html
Added: http://en.wikipedia.org/wiki/Comparison_of_Java_and_C_Sharp
I am surprised that no one has mentioned properties, something quite fundamental in C# but absent in Java. C# 3 and above has automatically implemented properties as well. In Java you have to use GetX/SetX type methods.
Another obvious difference is LINQ and lambda expressions in C# 3 absent in Java.
There are a few other simple but useful things missing from Java like verbatim strings (#""), operator overloading, iterators using yield and pre processor are missing in Java as well.
One of my personal favourites in C# is that namespace names don't have to follow the physical directory structure. I really like this flexibility.
There are a lot of differences, but these come to mind for me:
Lack of operator overloading in Java. Watch your instance.Equals(instance2) versus instance == instance2 (especially w/strings).
Get used to interfaces NOT being prefixed with an I. Often you see namespaces or classes suffixed with Impl instead.
Double checked locking doesn't work because of the Java memory model.
You can import static methods without prefixing them with the class name, which is very useful in certain cases (DSLs).
Switch statements in Java don't require a default, and you can't use strings as case labels (IIRC).
Java generics will anger you. Java generics don't exist at runtime (at least in 1.5), they're a compiler trick, which causes problems if you want to do reflection on the generic types.
.NET has reified generics; Java has erased generics.
The difference is this: if you have an ArrayList<String> object, in .NET, you can tell (at runtime) that the object has type ArrayList<String>, whereas in Java, at runtime, the object is of type ArrayList; the String part is lost. If you put in non-String objects into the ArrayList, the system can't enforce that, and you'll only know about it after you try to extract the item out, and the cast fails.
One thing I miss in C# from Java is the forced handling of checked exceptions. In C# is it far to common that one is unaware of the exceptions a method may throw and you're at the mercy of the documentation or testing to discover them. Not so in Java with checked exceptions.
Java has autoboxing for primitives rather than value types, so although System.Int32[] is an array of values in C#, Integer[] is an array of references to Integer objects, and as such not suitable for higher performance calculations.
No delegates or events - you have to use interfaces. Fortunately, you can create classes and interface implementations inline, so this isn't such a big deal
The built-in date/calendar functionality in Java is horrible compared to System.DateTime. There is a lot of info about this here: What's wrong with Java Date & Time API?
Some of these can be gotchas for a C# developer:
The Java Date class is mutable which can make returning and passing dates around dangerous.
Most of the java.util.Date constructors are deprecated. Simply instantiating a date is pretty verbose.
I have never gotten the java.util.Date class to interoperate well with web services. In most cases the dates on either side were wildly transformed into some other date & time.
Additionally, Java doesn't have all the same features that the GAC and strongly-named assemblies bring. Jar Hell is the term for what can go wrong when linking/referencing external libraries.
As far as packaging/deployment is concerned:
it can be difficult to package up web applications in an EAR/WAR format that actually install and run in several different application servers (Glassfish, Websphere, etc).
deploying your Java app as a Windows service takes a lot more effort than in C#. Most of the recommendations I got for this involved a non-free 3rd party library
application configuration isn't nearly as easy as including an app.config file in your project. There is a java.util.Properties class, but it isn't as robust and finding the right spot to drop your .properties file can be confusing
There are no delegates in Java. Therefore, aside from all the benefits that delegates bring to the table, events work differently too. Instead of just hooking up a method, you need to implement an interface and attach that instead.
One thing that jumps out b/c it's on my interview list is that there is no "new" keyword analogue in Java for method hiding and there fore no compiler warning "you should put new here". Accidental method hiding when you meant to override leads to bugs.
(edit for example)
Example, B derives from A (using C# syntax, Java behaves same way last I checked but does not emit compiler warning). Does A's foo get called, or B's foo? (A's gets called, probably surprising the dev who implemented B).
class A
{
public void foo() {code}
}
class B:A
{
public void foo() {code}
}
void SomeMethod()
{
A a = new B(); // variable's type is declared as A, but assigned to an object of B.
a.foo();
}
Java doesn't have LINQ and the documentation is hell. User interfaces in Java are a pain to develop, you lose all the good things Microsoft gave us (WPF, WCF, etc...) but get hard - to - use, hardly documented "APIs".
The most harrasing difference to me when I switch to java it's the string declaration.
in C# string (most of the time)
in Java String
It's pretty simple, but trust me, it makes you lose so much time when you have the habit to s not S !
The one issue I've run into so far when working with Java coming from C# is Exceptions and Errors are different.
For example you cannot catch an out of memory error using catch(Exception e).
See the following for more details:
why-is-java-lang-outofmemoryerror-java-heap-space-not-caught
It's been so long since I've been in Java but the things I noticed right off the bat in application development was C# event model, C# drag and drop vs using Layout Managers in Swing (if your doing App dev), and exception handling with Java making sure you catch an exception and C# not required.
In response to your very direct question in your title:
"C# developers learning Java, what are the biggest differences one may overlook?"
A: The fact that Java is considerably slower on Windows.
This is a semi-related question to question to the following question I just raised:
Utility classes.. Good or Bad?
After determining that a class is to act as a cache for Url parsing rules stored in an XML file, I have considered that a singleton would solve my problem, but introduce global state (although it is only traveling in one direction XML -> parser), and static dependencies.
The design consideration that led me to consider a singleton was: (note that this is a web application that uses a module to catch and parse ALL requests using the same parser)
I need to cache the url parsing rules stored in the XML, so the class needs to hang around between requests. I also have a method that parses the Url, given the rules, which determines the routing of the request at the HttpModule level.
Is a singleton valid in this case? How would you solve this?
There's no need for a singleton with all of the associated drawbacks (customary anti-singleton link ).
I like the suggestion to store it in HttpContext.Cache. Some similar alternatives:
Store it in HttpApplication.Application
Add a property to your application class to store it, then in the relevant HttpModule, store a class-level reference to your application.
I would consider storing the rules in the HttpContext.Cache which is available to all sessions. You could rebuild the cache anytime it was unloaded (due to lack of usage).
Your solution sounds good to me. Particularly if the consuming code isn't modifying data then using a singleton or static class sounds like it shouldn't be a problem. I'm not sure if labeling it as a "singleton" is necessary although I suppose that's how it's behaving.
You could use either a static class that is inherently "cached" because it's in the ASPNET worker process memory, or you could explicitly cache it into the web cache. If you do the latter, you could benefit by adding a file dependency to the cache entry so any file changes would force a reload from cache.
I would not use a singleton since that makes an application harder to test. Most IoC containers can help you replace this pattern with a "single(ton)" instance that is shared between all classes that would use the singleton.
It's so easy to get an IoC container to provide a singleton for you that I think it would be very hard to justify using the traditional Singleton pattern any more.
Singletons can be justified whenever you might need more than one instance of an object. The term "singleton" is slightly misleading because often the same software design pattern is used to control multiple instances of a class.
You can use a static class, or hang a singleton instance on a static reference, or store it in one of the asp.net web collections. Singletons can participate in inheritance in the future etc. etc...As for static class vs Singleton pattern, I'm staying out of that argument because it has been thoroughly addressed online, even on StackOverflow
Just quickly I would say No, just try to bind it to it's 'scope'. If it is application-wide then try to tie it to the application. If it is session-bound put it in the session etc. This helps you if you for instance want to run 2 apps in the same container. I have no experience with ASP.NET, but there seems to be a 'HttpApplicationState'. Could you use that?