Creating class static getter instead of object link - java

When you have many classes, it is often necessary to get access to fields/methods of one class from the other one. I'm not very experienced with Java and I've recently found this method which seem to be very convenient (better than passing variables from one class to another):
class MyClass {
private static MyClass _instance = null;
public MyClass(){
...
}
public static getInstance(){
if (_instance == null) {
_instance = new MyClass();
}
return _instance;
}
}
Now in any other class I can simply do
MyClass.getInstance().callSomething()
However I do not see such way of accessing other classes in Java examples and tutorials that I find in the Internet. So that got me thinking, are there maybe some potential problems with such approach? Especially when you have many classes and hence many such static calls in each?

MyClass.getInstance().callSomething()
However I do not see such way of accessing other classes in Java
examples and tutorials that I find in the Internet.
The approach you have specified is one of the most commonly used design pattern called Singleton pattern.
In Java the Singleton pattern will ensure that there is only one instance of a class is created in the Java Virtual Machine. It is used to provide global point of access to the object. In terms of practical use Singleton patterns are used in logging, caches, thread pools, configuration settings, device driver objects. Design pattern is often used in conjunction with Factory design pattern.
However, your code does not seem to fulfill the contract of Singleton Design pattern. It primarily requires your class to have only private constructors (to avoid other classes from instantiating it).
public MyClass(){ // Constructor needs to be private
...
}
Also the getInstance() method does not even seem to be valid.
Try this:
public static MyClass getInstance(){
It is recommended to implement Singleton in Java 5 or above version using Enum.
Enum is thread safe and implementation of Singleton through Enum ensures that your singleton will have only one instance even in a multithreaded environment
Follow this link for detailed understanding of Singleton pattern using Enum
Here is a good link which can help you understand Singleton pattern in detail.

This design pattern is called Singleton, have a look at the following question.
What is so bad about singletons?

Related

Is Java's Runtime class a proper example of a Singleton?

I have been reading about singleton pattern for a while now and when I searched for Singleton classes in Java language I found Runtime as an example but when I looked into the source I found a very basic Singleton implementation:
private static Runtime currentRuntime = new Runtime();
public static Runtime getRuntime() {
return currentRuntime;
}
private Runtime() {}
Whereas on the internet there is a lot written about how a singleton class should be. What I wanted to know is which of the Java language classes is best fit as a Singleton class example and why?
Yes, that's a very basic singleton. It does what it's supposed to do with no special frills.
The examples you find on the internet usually describe a lazy initialized singleton with emphasis on the performance of getInstance() (i.e. avoid synchronized, don't allow creating multiple instances if multiple threads call getInstance() at the same time and so forth).
If you don't need lazy initialization it becomes very simple to create a singleton, as you can see with Runtime.
Finally, you can find a lot of things written about the singleton pattern (some of them misleading), but it doesn't really warrant it. It's not that interesting, some consider it an anti-pattern, and if you find yourself writing your own singletons a lot, you're probably doing something not quite right.
Extra finally, if you do think you need a lazily initialized singleton, the current standard implementation is with enum.
public enum MySingleton {
INSTANCE
public String getSarcasticMessage() {
return "I'm a lazy loaded singleton, use me for everything!";
}
}
MySingleton.INSTANCE.getSarcasticMessage(); // This is how to use it

What are the essential elements of the Singleton pattern?

The core question is in the title but the answer I believe is right is as follows;
It ensures that only one instance is created
It provides a global point of access to an object
I am asking because I am unsure that the above is correct answer to the question. I did a little research but the above answer keep coming up. Is there anything to add or is the answer wrong completely.
Yes you are correct.
Singleton pattern restricts the instantiation of a class and ensures that only one instance of the class exists in the java virtual machine. The singleton class must provide a global access point to get the instance of the class. Singleton pattern is used for logging, drivers objects, caching and thread pool.
Singleton pattern is not difficult to understand.
Singleton it use to limit the numbers of object instance to one. Generally it use with factories.
Singleton class is like this :
public class YourClass{
private static final YourClass INSTANCE = new YourClass();
private YourClass{Your code..}
//This is the factorie
public static YourClass getInstance(){return INSTANCE;}
}
You can't create many instance of your class. The program return always the same object.
You can find many other explanation on this page : https://www.tutorialspoint.com/java/java_using_singleton.htm

why are there java singleton classes? When would you need to use one

I understand that a singleton class is one where there can be only one instantiation, but I don't understand why this would be useful. Why won't you just create a class with static variables and methods and use synchronize if needed to make sure that no two threads were executing a method in the class simultaneously. I just don't get why anyone would go through the trouble of creating this kind of class. I know I'm missing something here.
Thanks,
While I agree with the other answers, the OP was asking why not have a class with all static methods (possibly with static fields) instead of a singleton where you have one instance.
Why use Singletons?
You can Google "singleton" to find all sorts of reasons. From JavaWorld:
Sometimes it's appropriate to have
exactly one instance of a class:
window managers, print spoolers, and
filesystems are prototypical examples.
Typically, those types of
objects—known as singletons—are
accessed by disparate objects
throughout a software system, and
therefore require a global point of
access. Of course, just when you're
certain you will never need more than
one instance, it's a good bet you'll
change your mind.
Why use a Singleton instead of a class with all static methods?
A few reasons
You could use inheritance
You can use interfaces
It makes it easier to do unit testing of the singleton class itself
It makes it possible to do unit testing of code that depends on the singleton
For #3, if your Singleton was a database connection pool, you want to insure that your application has only one instance, but do unit testing of the database connection pool itself without hitting the database (possibly by using a package-scope constructor or static creational method):
public class DatabaseConnectionPool {
private static class SingletonHolder {
public static DatabaseConnectionPool instance = new DatabaseConnectionPool(
new MySqlStatementSupplier());
}
private final Supplier<Statement> statementSupplier;
private DatabaseConnectionPool(Supplier<Statement> statementSupplier) {
this.statementSupplier = statementSupplier;
}
/* Visibile for testing */
static DatabaseConnectionPool createInstanceForTest(Supplier<Statement> s) {
return new DatabaseConnectionPool(s);
}
public static DatabaseConnectionPool getInstance() {
return SingletonHolder.instance;
}
// more code here
}
(notice the use of the Initialization On Demand Holder pattern)
You can then do testing of the DatabaseConnectionPool by using the package-scope createInstanceForTest method.
Note, however, that having a static getInstance() method can cause "static cling", where code that depends on your singleton cannot be unit tested. Static singletons are often not considered a good practice because of this (see this blog post)
Instead, you could use a dependency injection framework like Spring or Guice to insure that your class has only one instance in production, while still allowing code that uses the class to be testable. Since the methods in the Singleton aren't static, you could use a mocking framework like JMock to mock your singleton in tests.
A class with only static methods (and a private contructor) is a variant where there is no instance at all (0 instances).
A singleton is a class for which there is exactly 1 instance.
Those are different things and have different use cases. The most important thing is state. A singleton typically guards access to something of which there is logically only ever one. For instance, -the- screen in an application might be represented by a singleton. When the singleton is created, resources and connections to this one thing are initialized.
This is a big difference with a utility class with static methods - there is no state involved there. If there was, you would have to check (in a synchronized block) if the state was already created and then initialize it on demand (lazily). For some problems this is indeed a solution, but you pay for it in terms of overhead for each method call.
Database instances is one place singletons are useful, since a thread only wants one DB connection. I bet there are a lot of other instances like database connections where you only want one instance of something and this is where you would use a singleton.
For me the reason to prefer singleton over a class with static methods is testability. Let's say that I actually need to ensure that there really is one and only one instance of a class. I could do that with either a singleton or a static class with only static methods. Let's also say that I'd like to use this class in another class, but for testing purposes I'd like to mock the first class out. The only way to do that is to inject an instance of the class into the second class and that requires that you have a non-static class. You still have some pain with respect to testing -- you might need to build in some code you can invoke with reflection to delete the singleton for test purposes. You can also use interfaces (though that would explicitly would allow the use of something other than the singleton by another developer) and simply provide the singleton as an instance of the interface to the class that uses it.
One consideration is that making a singleton an instance allows you to implement an interface. Just because you want to control instantiation to it, does not mean you want every piece of code to know that it's a singleton.
For example, imagine you had a connection provider singleton that creates DB connections.
public class DBConnectionProvider implements ConnectionProvider {}
If it were a class with static methods, you couldn't inject the dependency, like this:
public void doSomeDatabaseAction(ConnectionProvider cp) {
cp.createConnection().execute("DROP blah;");
}
It would have to be
public void doSomeDatabaseAction() {
DBConnectionProvider.createConnection().execute("DROP blah;");
}
Dependency injection is useful if you later want to unit test your method (you could pass in a mocked connection provider instead) among other things.
Use the singleton pattern to encapsulate a resource that should only ever be created (initialised) once per application. You usually do this for resources that manage access to a shared entity, such as a database. A singleton can control how many concurrent threads can access that shared resource. i.e. because there is a single database connection pool it can control how many database connections are handed out to those threads that want them. A Logger is another example, whereby the logger ensures that access to the shared resource (an external file) can be managed appropriately. Oftentimes singletons are also used to load resources that are expensive (slow) to create.
You typically create a singleton like so, synchronising on getInstance:
public class Singleton {
private static Singleton instance;
private Singleton(){
// create resource here
}
public static synchronized Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
But it is equally valid to create it like so,
public class Singleton {
private static Singleton instance = new Singleton();
private Singleton(){
// create resource here
}
public static Singleton getInstance() {
return instance;
}
}
Both methods will create a single instance PER classloader.
A singleton has the advantatage over a class with static variables and methods : it's an object instance, which can inherit from a class (example : an application that ahas a single principal JFrame), and extend one or more interfaces (and thus be treated as any other object implementing these interfaces).
Some people think that singletons are useless and dangerous. I don't completely agree, but some points about it are valid, and singletons should be used carefully.
Static classes used in place of singletons are even worse in my opinion. Static classes should be mainly used to group related functions which don't share a common resource. java.util.Collections is a good example. It's just a bunch of functions that aren't tied to any object.
Singletons, on the other hand, are true objects. Ideally, singleton should be implemented without singleton pattern in mind. This will allow you to easily switch to using multiple instances if you suddenly need it. For example, you may have only one database connection, but then you have to work with another, completely unrelated database at the same time. You just turn your singleton into a "doubleton" or "tripleton" or whatever. If you need, you can also make its constructor public which will allow creation of as many instances as you want. All this stuff isn't so easy to implement with static classes.
Simply put, a singleton is a regular class that has one instance globally available, to save you from all the trouble of passing it everywhere as a parameter.
And there is not much trouble in creating a singleton. You just create a regular class with a private constructor, then implement one factory method, and you're done.
When would you need to use one?
There are many objects we only need one of: thread pools, caches, dialog boxes, objects that handle preferences and registry settings, objects used for logging, and objects that act as device drivers to devices like printers and graphic cards. For many of these types of object if we were to intantiate more than one we would run intol all sorts of problems like incorrect program behavior or overuse of resources
Regarding the usage of synchronization it is definitly expensive and the only time syncrhonization is relevant is for the first time or the unique instatiation once instantiated we have no further need to synchronize again. After the first time through, syncrhonization is totally unneeded overhead :(
Others have provided better answers while I was replying, but I'll leave my answer for posterity. It would appear unit testing is the big motivator here.
For all intents and purposes, there is no reason to prefer a singleton to the approach you described. Someone decided that static variables are capital-b Bad (like other sometimes useful features like gotos) because they're not far off from global data and in response we have the workaround of singletons.
They are also used with other patterns. See Can an observable class be constructed as a singleton?

java singleton instantiation

I've found three ways of instantiating a Singleton, but I have doubts as to whether any of them is the best there is. I'm using them in a multi-threaded environment and prefer lazy instantiation.
Sample 1:
private static final ClassName INSTANCE = new ClassName();
public static ClassName getInstance() {
return INSTANCE;
}
Sample 2:
private static class SingletonHolder {
public static final ClassName INSTANCE = new ClassName();
}
public static ClassName getInstance() {
return SingletonHolder.INSTANCE;
}
Sample 3:
private static ClassName INSTANCE;
public static synchronized ClassName getInstance()
{
if (INSTANCE == null)
INSTANCE = new ClassName();
return INSTANCE;
}
The project I'm using ATM uses Sample 2 everywhere, but I kind of like Sample 3 more. There is also the Enum version, but I just don't get it.
The question here is - in which cases I should/shouldn't use any of these variations? I'm not looking for lengthy explanations though (there's plenty of other topics about that, but they all eventually turn into arguing IMO), I'd like it to be understandable with few words.
The most secure and easy way to implement a singleton in java is by using enums (like you mentioned):
public enum ClassName {
INSTANCE;
// fields, setters and getters
}
The enum semantics guarantees that there will be only one INSTANCE
If not using the enum approach, you must take care of quite a lot aspects, like race conditions and reflection. I've been breaking singletons of some frameworks, and abusing them, because they weren't properly written. The enum guarantees no one will break it.
Sample 1 does not use lazy initialisation.
Sample 2 and 3 are both lazy. Sample 2 uses the Initialization on demand holder idiom (IODH) which has no synchronisation overhead. Therefore it is faster than Sample 3.
In Effective Java (Item 3), Joshua Bloch recommends that a single-element enum type is the best way to implement a singleton.
However, if you are unsure about the enum type, stick with IODH.
First of all, make absolutely sure that you need a singleton, and that you want to provide "global-level" access to the singleton. I've found that in many cases clients of the singleton have no need to know that it is a singleton. Rather, they just need to get a service when they are instantiated.
Thus, regardless of how you obtain the singleton (if at all), consider changing the way your classes gain access to this object. While this means modifying constructors and changing "distribution changes", I've found that dependency injection frameworks reduce the cost. The DI framework can also then take care of singleton instantiation (e.g., Guice does that).
Aside from that. option 3 is the typical and most common (and thread safe) version that I'm familiar with. Option 1 is mostly for non-lazy initialization (not always acceptable). I've never seen 2 used.
Sample 1: Use if you don't need a lazy Singleton.
Sample 2: Never use - it gets confusing with too much classes. And an inner class just to hold one variable seems to be a bit unnecessary.
Sample 3: This is a lazy Singleton. Use it if you need it.

Implementing the singleton pattern in Java

Can anyone provide an example of a singleton pattern and explain why they are necessary?
Before going the singleton route, reconsider. Do you really need a singleton? If you're asking for scenarios when you need to implement singletons, it's because the need for them didn't really express. You're better off not introducing singletons in your code base just because it feels cool to follow design patterns.
Clean Code Talks - Global State and Singletons
Once Is Not Enough
Performant Singletons
However, what's really worth knowing is Dependency Injection.
Now if you really want to implement singletons in Java, I would recommend Joshua Bloch's "Effective Java" way of implementing them:
public class Singleton
{
public static Singleton getInstance() {
return SingletonHolder.instance;
}
private Singleton() {}
private static final class SingletonHolder {
static final Singleton instance = new Singleton();
}
}
The JLS guarantees the JVM will not initialize instance until someone calls getInstance();
Final note, the Double Checked Locking Pattern is broken in Java up to Java 5. The Java 5 memory model makes the DCL pattern thread safe but it makes it slower than the SingletonHolder class method while the original intent was performance optimization.
EDIT: As #Luno pointed out, since the second edition of the book, the preferred way is:
As of release 1.5, there is a third approach to implementing singletons. Simply make an enum type with one element:
// Enum singleton - the preferred approach
public enum Elvis {
INSTANCE;
public void leaveTheBuilding() { ... }
}
This approach is functionally equivalent to the public field approach, except that it is more concise, provides the serialization machinery for free, and provides an ironclad guarantee against multiple instantiation, even in the face of sophisticated serialization or reflection attacks. While this approach has yet to be widely adopted, a single-element enum type is the best way to implement a singleton.
Basically, in Java you implement singleton by giving a class a private no-args constructor (private MyClass()), and statically (or lazily) initializing a single instance of the class which is returned by a static MyClass getInstance() method.
You would use this when you want there to be no more than a single instance of your class throughout the entire application.
danben has a pretty good summary of what a singleton is, so I won't rehash it.
As far as uses go, singletons are often thinly veiled implementations of global variables (which is a bad idea). They can be useful for things like message routers or manager classes (among other things).
'Simply Singleton' at JavaWorld
And if you really want to get into the trenches, start reading about "static vs singleton" on the groups, or Google it. Always a hot topic to say the least!
One often underappreciated place where singletons are good is when you want to abstract away the existence of state. An example is a random number generator. At the level of the abstraction, it just generates random numbers and doesn't have any state that the caller should need to care about. At the implementation level, though, state is involved. Another is when a function caches results or intermediate computations, but you want to hide this detail from the caller.
There is a significant tradeoff here. If you make things like these singletons, you decrease the amount of implementation details the caller of your function has to care about, thus decreasing coupling in that direction. However, at the same time you strongly couple your function to the singleton object, making it harder to test, etc. The decision about whether to use a singleton should be made based on which direction you care about reducing coupling in more.
assume you have only one printer in office and you need Ensure a printer class has only one instance
printer{
private static printer instance =null;
private printer(){}
public static printer getinst(){
if( instance==null){
instant = new printer();
}
return instance;
}
}
in the main
printer v=printer.geti();

Categories

Resources