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.
Related
I was reading about volatile when I came across this statement that using volatile and synchronize keyword would slow down your overall performance hence the following code to make a singleton class
public enum Singleton {
INSTANCE
}
Is better making a singleton class which includes a volatile instance and a synchronised method to return that static instance.
Though both the classes are thread safe and give the same desired result. Apart from the code readability , are there are any performance benefits of using enums.
Maybe volatile does not do what you think it does. The text of your question looks like you are asking about two different ways of safely publishing a singleton in a multi-threaded environment. But, that is not what volatile is for. volatile solves a more general problem.
You can declare a variable to be volatile if it needs to be shared between different threads, but it does not need to be synchronized with any other variable. The volatile declaration ensures that any time a thread looks at the variable, it always will see the newest value that was assigned to it, even if that value was assigned by some other thread.
Yes. volatile is costly. It would be a mistake to use it when you don't need it (e.g., it would be a mistake to use it on a variable that is not shared, and it would be a mistake to use it on a shared variable that already is protected by other means.)
synchronized keyword by definition slow down the performance as it allows only one thread to process the synchronized code block. The only reason to use synchronized and volatile for creating a singleton class is to provide for lazy initialization of the single instance of the class.
private static volatile ThreadSafeLazySingleton instance;
private ThreadSafeLazySingleton(){}
public static synchronized ThreadSafeLazySingleton getInstance(){
if(instance == null){
instance = new ThreadSafeLazySingleton();
}
return instance;
}
Lazy initialization is helpful when the instantiation is resource heavy and you want to delay the creation of instance to the last moment.
It is possible to break the singleton design of a class by using Reflection and setting the private constructor Singleton.class.getDeclaredConstructors() access to true by using constructor.setAccessible(true).
Using enum to design a singleton class overcomes the above drawback as Java ensures that enums are always instantiated only once. However, the benefits of lazy initialization are lost in this approach. As synchronization is not used, this approach will have better performance than the synchronized approach.
The best way to design a singleton class is by using the method suggested in this answer
I am reading about java singleton and I've met strange things.
I will refer to following artice as example(you can easy find more)
Author provides the following singleton:
public class ASingleton {
private static ASingleton instance = new ASingleton();
private ASingleton() {
}
public static ASingleton getInstance() {
return instance;
}
}
and comments:
Pros:
-Thread safety without synchronization
- Easy to implement
Cons:
- Early creation of resource that might not be used in the application.
-The client application can’t pass any argument, so we can’t reuse it.
For example, having a generic singleton class for database connection
where client application supplies database server properties.
I want to get clarification about Thread safety without synchronization point.
I've read concurrency in practice book and don't remember anything related with this.
I missed something or this clarification is not relevant?
Additionally I want to tell you that you can encounter the same singleton but field marked as static final instead of just static
P.S.
I understand that I can read JMM and this one contains the answer but I am usual guy and I can't undertand this source.
According to securecoding.cert.org this is a valid pattern:
Variables that are declared static and initialized at declaration or from a static initializer are guaranteed to be fully constructed before being made visible to other threads. However, this solution forgoes the benefits of lazy initialization.
The point is: loading classes is a well defined operation. And executing static initializing code falls into the same category.
It is important to understand: JMM knowledge is only "required" when you go for the static field + lazy init variant:
Initialization of the static helper field is deferred until the getInstance() method is called. The necessary happens-before relationships are created by the combination of the class loader's actions loading and initializing the Holder instance and the guarantees provided by the Java memory model (JMM). This idiom is a better choice than the double-checked locking idiom for lazily initializing static fields [Bloch 2008]. However, this idiom cannot be used to lazily initialize instance fields [Bloch 2001].
Finally: the final keyword should not affect this at all. Using final is much more about expressing your intent to declare a well, final thing - instead of one that gets potentially updated later on.
That idiom is sound with respect to the JMM.
There is a happens before relationship between the static initialization of a class and the use of any static variables. This is a consequence of the locking that occurs during the initailization procedure described in JLS 12.4.2.
According to my reading, instance does not need to be declared as final here to get the required happens-before. It is advisable for other reasons though.
something about static:
instances of class share static method
the similar questions:
Java: when to use static methods
What does the 'static' keyword do in a class?
I am confusing about:
static method just have only one memory block?
if i use static method in multithreading, will it block?
I am confusing about:
static method just have only one memory block? if i use static method
in multithreading, will it block?
The static keyword in Java simply means "without regard or knowledge of any particular instance of an object."
An instance method can use this to access the fields of its associated instance, but a static method has no associated instance and so this makes no sense.
In multithreading, thread safety involves protecting the consistency and integrity of mutable data. Because objects encapsulate the state of their instance fields, instance methods only need to be concerned about thread safety in those circumstances in which more than one thread will be accessing the same object.
So while thread confinement of an object is a valid thread safety policy for instances of a class, this same reasoning is invalid for static methods because they have no instance.
This has nothing to do with memory blocks at all. It just has to do with access. An object instance is accessed through a reference. If the reference is thread confined, then the object to which that reference points will always be thread safe. But any thread anywhere that can access your class can potentially get to its static members because no reference to an instance is needed to use them.
Static methods are non-blocking by default. You can implement your own synchronization/thread safety policy and have your static method block if you wish.
Each thread has its own stack space, each time a thread calls a method (static or virtual) that call allocates a stack frame, which holds local variables. nothing about this is specific to static methods.
Static methods can be called concurrently by multiple threads, unless you specifically do something to thwart that, such as requiring that the caller acquire a lock (such as using the synchronized keyword).
Static methods are good for cases where there is no shared state. They may be ok in cases accessing or modifying threadsafe shared state, depending on what level of concurrency is needed and how efficient the threadsafe things being accessed are.
Look out for bottlenecks. Putting the synchronized keyword on a static method may be a problem as that limits your application to calling it with only one thread at a time. Alternative strategies including using atomic objects, using threadsafe data structures designed for high concurrency, or using thread confinement may be preferable to locking.
static method just have only one memory block?
No, methods don't have memory blocks. Threads executing those methods do. Each thread will have it's own memory on the stack where it stores all the method arguments and variables.
if i use static method in multithreading, will it block
A thread cannot access the memory of another thread, but if there is some resource that belongs to all instances and is supposed to be accessed sequentially, then you can synchronize or lock the static method, thus making it a blocking one. Otherwise, no.
Even though there is one instance of a static method, each thread gets its own stack-frame, which means each thread can exercise the same method but in a separate "world" from other threads.
Threads always get their own stack, even for a singleton class (one instance):
so, when to use static methods and when to not?
The main reason for not using static methods everywhere is that they are difficult to unit-test barring manipulating compiled code (Powermock), so static methods should have no dependencies that would require mocking, i.e. the test calls the real method with an input and asserts the output, verbatim, in two steps.
Non-static methods allow you to isolate your test solely to that method by stubbing, mocking, or spying on objects that the method depends on.
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
}
My question is broad, so I've split in two parts, and tried to be as specific as I can with what I know so far.
First part
A singleton holds a private static instance of itself. Some questions about singletons:
1. Should it's members also be static, or does that depend on the requirements?
2. If the answer to 1. is unequivocally yes, then what would be the point of having a private instance variable to begin with, if all members belong to the class?
3. Is the private instance needed because the JVM needs a referable object (THE singleton) to hold on to for the length of its (JVM's) life?
Second part
There is a requirement to make multiple concurrent remote calls within a tomcat hosted web application (the app utilizes GWT for some components, so I can utilize a servlet for this aforementioned requirement if a good solution requires this). Currently, I create an executor service with a cached thread pool into which I pass my callables (each callable containing an endpoint configuration), for each individual process flow that requires such calls. To me it would make sense if the thread pool was shared by multiple flows, instead of spawning pools of their own. Would a singleton holding a static thread pool be a good solution for this?
One note is that it is important to distinguish between the concept of a singleton (a class/object that has only a single instance) and the design pattern which achieves this via a class holding a single static instance of itself accessible in the global static name space. The concept of a singleton is frequently used in designs, the implementation of it via the singleton design pattern, however, is often frowned upon.
In the below, singleton is used to refer to the specific design pattern.
Part 1
A Singleton's members do not need to be static, and usually are not.
See 1.
A singleton (design pattern) requires an instance to itself in order to return that instance to users of the singleton, as well as keeping a reference to itself active to avoid garbage collection (as you suggest). Without this single instance, the object is essentially not an implementation of the singleton design pattern. You can create a class for which you only create a single instance and pass this class around where it is required (avoiding the global static namespace), and this would essentially be a recommended way to avoid using the singleton pattern.
Part 2:
Sharing your thread pools is probably wise (but depends on your requirements), and this can be done in a number of ways. One way would be to create a single pool and to pass this pool (inject it) into the classes that require it. Usual recommendation for this is to use something like Spring to handle this for you.
Using a singleton is also an option, but even if your thread pool here is encapsulated in a singleton, it is still generally preferable to inject this singleton (preferably referenced via an interface) into dependent objects (either via a setter or in their constructor) instead of having your objects refer to the singleton statically. There are various reasons for this, with testing, flexibility, and control over order of instantiation being some examples.
A Singleton's members need not be be static.
Invalidated by answer to point 1.
The instance of itself that the singleton need not be private either. You need an instance stored to a static member (public or private) if you have any other non-static member on the singleton. If there is any non-static member(it depends on your requirement) , then you need an instance to access that member(yes, JVM needs a referable object if the member is non-static)
Singleton member doesn't need to be static
Look at point 1
Singleton instance must be static (of course) and must be accessed by a static method; in addiction must have a private constructor to prevent new instance to be created
public class SingletonNumber10 {
public static SingletonNumber10 getInstance() {
if(null == instance) {
instance = new SingletonNumber10(10);
}
return instance;
}
private int number;
private static SingletonNumber10 instance;
private SingletonNumber10(int number) {
this.number = number;
}
public int getNumber() {
return this.number;
}
public static void main(String[] args) {
System.out.println(SingletonNumber10.getInstance());
System.out.println(SingletonNumber10.getInstance());
}
}
A singleton holds a private static instance of itself.
Not always, in fact, that's not even the best way to do it in Java.
public enum Director {
INSTANCE;
public int getFive() {
return 5;
}
}
Is a perfectly valid singleton, and is far more likely to remain the only copy in existence than a class that holds a private static instance of itself.
1. Should it's members also be static
No, the members should not be static, because then there is no need for a class, and therefore no need for that class to be a singleton. All static routines are subject to code maintenance issues, similar to C / C++ functions. Even though with singletons you won't have multiple instances to deal with, having the method off of an instance provides you with certain abilities to morph the code in the future.
2. If the answer to 1. is unequivocally yes.
It's not, so no need to answer #2.
3. Is the private instance needed because the JVM needs a
referable object (THE singleton) to hold on to for the
length of its (JVM's) life?
No, the private instance is needed because you have to have some ability to determine if the constructor was called previous to the access. This is typically done by checking to see if the instance variable is null. With race conditions and class loader considerations, it is incredibly difficult to make such code correct. Using the enum technique, you can ensure that there is only on instance, as the JVM internals are not subject to the same kinds of race conditions, and even if they were, only one instance is guaranteed to be presented to the program environment.
There is a requirement to make multiple concurrent remote calls within
a tomcat hosted web application (the app utilizes GWT for some components,
so I can utilize a servlet for this aforementioned requirement if a good
solution requires this). Currently, I create an executor service with a cached
thread pool into which I pass my callables (each callable containing an endpoint
configuration), for each individual process flow that requires such calls. To
me it would make sense if the thread pool was shared by multiple flows, instead
of spawning pools of their own. Would a singleton holding a static thread pool be
a good solution for this?
It depends. What are the threads in the pool going to be doing? If it's a thread to handle the task, eventually they will all get tied up with the long running tasks, possibly starving other critical processing. If you have a very large number of tasks to perform, perhaps restructuring the processing similar to the call-back patterns used in NIO might actually give you better performance (where one thread handles dispatching of call-backs for many tasks, without a pool).
Until you present a second way of handling the problem, or make more details of the operating environment available, the only solution presented is typically a good solution.
PS. Please don't expand on the details of the environment. The question submission process is easy, so if you want to expand on the second part, resubmit it as an independent question.