Yet Another Query About the Thread Safety of a (Java) Singleton - java

Consider the following:
public class Singleton {
private static Singleton instance;
// NO INSTANCE VARIABLES
private Singleton() {
super(); // Just to have something to write here.
}
public static Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
public String parseSomething(MyObject myObject) {
// Do stuff
}
public void doAnotherThing(String value) {
// Do something else
}
}
Are parseSomething() and doAnotherThing() thread-safe? In other words, if I have multiple threads getting the Singleton instance and making possibly simultaneous calls to those two methods, will it end lives?
My instinct (and limited experience) says "no," because those methods do not act on anything outside their scope; they do not carry state in any instance variables in Singleton. Each calling thread would have the parameters and locally-scoped variables in their own stack, so (in theory) they shouldn't collide.
Unfortunately, I can't seem to Google up any questions on this topic that don't involve some action by the instance methods on a state-carrying instance variable in Singleton.
Edit: Trying the instance thing again. My real question here, though, is, assuming N threads have a handle on the instance and are making calls to parseSomething() and doAnotherThing(), will they murder each other?

Are parseSomething() and doAnotherThing() thread-safe?
Highly depends, on what they do, and how they do it, singleton pattern, has nothing to do with thread safety, it supposed to guarantee that there is only one instance of the object in the running system, which by the way this implementation does not (You can create another instance of Singleton, using reflections, or if getInstance is called in parallel on getInstance call).
So, if this methods are stateless, and do not have any shared state, then they are thread safe. You can just make those methods static in your singleton class, and make a utility class out of this Singleton.

Related

I dont understand the concept of a singleton class

I know how to make a singleton class in java but what I dont understand is the concept of singleton. Like why would I need a singleton class and why would I use a singleton instead of a regular class?
"Singleton pattern restricts the instantiation of a class and ensures
that only one instance of the class exists in the java virtual
machine."
I just read that definition but I dont get it, what does it change if there is one or more instances of a class.
Why would I want to only have one instance of a class.
In some cases, we need to expose a shared resource throughout the application e.g. DB connection but we don't want to
create shared object up-front (before creation of client objects).
explicitly pass shared object to each client object.
then we can use Singleton design pattern.
Typical Singleton class looks like
public class MySingleton {
private MySingleton INSTANCE
private MySingleton() {
}
public static MySingleton getInstance() {
if (INSTANCE == null) {
syncronized (MySingleton.class) {
if (INSTANCE == null) {
INSTANCE = new MySingleton();
}
}
}
return INSTANCE;
}
// instance methods exposing business operation
}
But we can achieve the similar behaviour by making each and every instance methods which are exposing business operation as static. In this approach we don't even need to create single object.
Then why do we need Singleton?
Well, the answer is simple. To isolate actual implementation from the client. Basically we are applying abstraction OOP principle here.
This is helpful If the singleton class is part of library which is used by various clients and library wants to vary the implementation as per the client.
Sample for such singleton can be
public class MySingleton {
private MySingleton INSTANCE
private MySingleton() {
}
public static MySingleton getInstance() {
if (INSTANCE == null) {
syncronized (MySingleton.class) {
if (INSTANCE == null) {
INSTANCE = new MySingletonChild(); // here we are creating an object of subclass of MySingleton.
}
}
}
return INSTANCE;
}
// instance methods exposing business operation
}
Hope this help in understanding Singleton design pattern.
Singletons are used for when you want exactly one instance of a class, that the entire application shares.
Good examples for this principle are classes that are in charge of accessing external resources. For example, you'd want the entire application share the same database connection (or at least connection pool), not have every class that needs it open its own connection.
Singletons are classes with properties which can be shared with other classes in the same context. (Application, session, ...)
For example if you have to count the number of connected users in a web application. Every time a user connect, you increment a counter in a unique shared class.

When should I use lazy Singletons over normal Singletons?

So far I have seen two examples of Singletons.
Normal Singletons,
public class Singleton {
private static Singleton instance;
static {
instance = new Singleton();
}
private Singleton() {
// hidden constructor
}
public static Singleton getInstance() {
return instance;
}
}
and Lazy Singletons,
public class Singleton {
private Singleton() {
// hidden constructor
}
private static class Holder {
static final Singleton INSTANCE = new Singleton();
}
public static Singleton getInstance() {
return Holder.INSTANCE;
}
}
Coding is from this thread and this user. I have just recently gotten into trying to learn Singletons as my previous methods have been
1.) Using static in order to create something like ...
static MyClass instance;
2.) I would attempt to pass an instance in a seemingly odd way,
MyClass instance;
#Override
public void onEnable() { instance = this; }
// Transition to different class - - -
public OtherClass(MyClass myClass) {
this.instance = myClass;
}
Lastly, what is my end goal? I am mainly using it in order to pass variables from my main class to other classes. I'm currently attempting to learn how to properly use Files and FileConfiguration, so I want to easily share them throughout my classes.
If I seem like a beginner, instead of going out of your way to tell me to learn Java, please provide a resource to help me with my problem first and foremost.
As to when, rather than how: I would use lazy instantiation of a singleton or of any other object when there is a fair chance of the object not being needed, and immediate instantiation when the likelihood of it being needed is high. In general, if instantiation were to fail, and the object is needed, it is better that it fail as early as possible.
This link explains it fairly well and even uses a similar example.
In software engineering, the initialization-on-demand holder (design pattern) idiom is a lazy-loaded singleton. In all versions of Java, the idiom enables a safe, highly concurrent lazy initialization with good performance.
Regarding why you should use this: if the creation of this instance is expensive, then this design pattern essentially delegates the expensive computation for when it is needed, rather than when the outer class, Singleton in your case, is first accessed.
Another reason is given by this other link. It states:
A singleton implementation may use lazy initialization, where the instance is created when the static method is first invoked. If the static method might be called from multiple threads simultaneously, measures may need to be taken to prevent race conditions that could result in the creation of multiple instances of the class.

Is there a difference between Singleton and a class that can have only one user at a time?

I think I understand the Singleton pattern. It seems to me that there are many cases where more than one user is accessing the single instance that the pattern enforces. But is there a refinement that prevents that instance from being used (even read-only) while another user is accessing it or is that still a Singleton?
EDIT: So if a Singleton does not prevent more than one thread from accessing it, is there a standard way to enforce this further functionality. To be clear, if a thread attempts to get the instance before the first thread that accessed the Singleton is done, an exception is thrown or the thread blocks?
A Singleton can only be instantiated once. This says nothing about the number of (simultaneous) users it has.
What you say: a class which instance can have only one user, this means: per user, there is a different instance, not that only one user can use it.
So: there's a big difference there.
No. The singleton pattern makes sure that there's only one instance of a class. It does not do any kind of synchronization.
You are of corse free to implement this in your class by using synchronized methods.
You can use this aproach of thread safe singleton:
https://stackoverflow.com/a/16106598/327786
public class CassandraAstyanaxConnection {
private static class Holder {
static final CassandraAstyanaxConnection INSTANCE = new CassandraAstyanaxConnection();
}
public static CassandraAstyanaxConnection getInstance() {
return Holder.INSTANCE;
}
// rest of class omitted
}

Can objects have access modifiers?

I was going through a piece of code when I came across this:
public class ClassicA {
private static ClassicA instance = null;
}
I have never used such a thing and wanted to know what it means and how it is used. Also, what is the purpose of the access modifier for the object? Any examples/links are welcome.
It probably means that ClassicA is a Singleton. It is usually involved with declaring a private constructor, and a single public static getInstance() method.
Singletons are used when you want to make sure there is only one global instance of ClassicA in your entire application. Instead of instantiating it, you call getInstance(), which will check if it was instantiated once or not. If it was, it will instantiate it, and store the the resulting object in the private instance field. If it was already constructed, just return the instance field without re-instantiating.
Note that this is considered bad practice. See: https://softwareengineering.stackexchange.com/questions/40373/so-singletons-are-bad-then-what
Well, the class ClassicA has a private and static field instance which is null.
If there are no getters/setters the only way to access that field would be using reflection.
Since this looks like a singleton, I guess there's a getter as well that returns instance and if it is null first creates an instance and assigns it to the field.
It's a (static) member of the class, and yes, these can have access modifiers. (And as others have noted, it indeed looks like a portion of a Singleton.)
its a singleton
basically the author intended there to be only 1 instance of this class alive (the instance field)
the constructor is probably private and used only within the class.
This is used typically for a class that exhibits the Singleton design pattern.
The point is that for these types of objects you only want a single instance at most. What you do is create a private constructor for the class and then usually a public static method called, getInstance in which you check if the private instance variable has been set yet or not. If it has not yet set, you create a new instance of the class and assign it to instance, then you return that instance. If the object was already created you simply return it. Like this:
public class MySingleton {
private static MySingleton instance=null;
private MySingleton() {
//do stuff
}
public static MySingleton getInstance() {
if (instance == null) {
instance = new MySingleton();
}
return instance;
}
}
Then from throughout your program you can easily get the singleton object from anywhere.
Thus, a singleton is effectively just a glorified global variable in languages such as PHP. I would argue though that it is a lot cleaner as you can prevent others from reassigning the reference to the instance and other trickery that may be very bad from a design standpoint.
Typically people use it for classes that manage some type of data access, such as a DB object, for Factory classes and builder classes, see this for more info
This is used for singleton pattern. See here
private static means that the instance is available to all the instances and static methods of the class, but only to them. It's actually like having static private method.
Such tricks can be used for example for implementing a singleton: you keep internally a single instance of a class, and you can give it to the class's clients on demand. Or for any other case when you need something shared just between the static methods and instances of some class.

static method and thread safety

Is the following code threadsafe ?
public static Entity getInstance(){
//the constructor below is a default one.
return new Entity();
}
Assuming the constructor itself is thread-safe, that's fine.
It would be very unusual for a constructor not to be thread-safe, but possible... even if it's calling the default auto-generated constructor for Entity, the base constructor may not be thread-safe. I'm not saying it's likely, just possible :)
Basically there's no magic thread-safety applied to static methods or instance methods or constructors. They can all be called on multiple threads concurrently unless synchronization is applied. If they don't fetch or change any shared data, they will generally be safe - if they do access shared data, you need to be more careful. (If the shared data is immutable or only read, that's generally okay - but if one of the threads will be mutating it, you need to be really careful.)
Only static initializers (initialization expressions for static variables and static { ... } blocks directly within a class) have special treatment - the VM makes sure they're executed once and only once, blocking other threads which are waiting for the type to be initialized.
It depends on the details of the Entity constructor. If the Entity constructor modifies shared data, then it is not.
It's probably thread safe, but what's the point? If you're just using a factory method to redirect to the default constructor then why not use the constructor in the first place? So the question is: what are you trying to achieve? The name getInstance() suggests a singleton (at least that's common practice), but you clearly don't have a singleton there. If you do want a singleton, use a static inner holder class like this:
public class Singleton {
private Singleton() {
}
public static Singleton getInstance() {
return InstanceHolder.INSTANCE;
}
private static final class InstanceHolder {
public static final Singleton INSTANCE = new Singleton();
}
}
but if you don't, why bother with such a factory method, as you're not adding any value (method name semantics, object pooling, synchronization etc) through it
Thread safety is about access to shared data between different threads. The code in your example doesn't access shared data by itself, but whether it's thread-safe depends on whether the constructor accesses data that could be shared between different threads.
There are a lot of subtle and hard issues to deal with with regard to concurrent programming. If you want to learn about thread safety and concurrent programming in Java, then I highly recommend the book Java Concurrency in Practice by Brian Goetz.
Multiple threads could call this method and each one will get an unique instance of 'Entity'. So this method 'per se' is thread safe. But if there is code in the constructor or in one of the super constructors that is not thread safe you might have a safety problem anyhow.

Categories