I'm using a static code block to initialize some controllers in a registry I have. My question is therefore, can I guarantee that this static code block will only absolutely be called once when the class is first loaded? I understand I cannot guarantee when this code block will be called, I'm guessing its when the Classloader first loads it. I realize I could synchronize on the class in the static code block, but my guess is this is actually what happens anyway?
Simple code example would be;
class FooRegistry {
static {
//this code must only ever be called once
addController(new FooControllerImpl());
}
private static void addController(IFooController controller) {
// ...
}
}
or should I do this;
class FooRegistry {
static {
synchronized(FooRegistry.class) {
addController(new FooControllerImpl());
}
}
private static void addController(IFooController controller) {
// ...
}
}
Yes, Java static initializers are thread safe (use your first option).
However, if you want to ensure that the code is executed exactly once you need to make sure that the class is only loaded by a single class-loader. Static initialization is performed once per class-loader.
This is a trick you can use for lazy initialization
enum Singleton {
INSTANCE;
}
or for pre Java 5.0
class Singleton {
static class SingletonHolder {
static final Singleton INSTANCE = new Singleton();
}
public static Singleton instance() {
return SingletonHolder.INSTANCE;
}
}
As the static block in SingletonHolder will run once in a thread safe manner you don't need any other locking. The class SingletonHolder will only get loaded when you call instance()
In usual circumstances everything in the static initialiser happens-before everything that uses that class, so synchronisation is not usually necessary. However, the class is accessible to anything that the static intiailiser calls (including causing other static initialisers to be invoked).
A class can be loaded by a class loaded but not necessarily initialised straight away. Of course, a class can be loaded by multiples instances of class loaders and thereby become multiple classes with the same name.
Yes, sort of
A static initializer only gets called once, so by that definition it's thread safe -- you'd need two or more invocations of the static initializer to even get thread contention.
That said, static initializers are confusing in many other ways. There's really no specified order in which they're called. This gets really confusing if you have two classes whose static initializers depend on each other. And if you use a class but don't use what the static initializer will set up, you're not guaranteed the class loader will invoke the static initializer.
Finally, keep in mind the objects you're synchronizing on. I realize this isn't really what you're asking, but make sure your question isn't really asking if you need to make addController() thread-safe.
Yes, Static initializers are run only once. Read this for more information.
So basically, since you want a singleton instance, you should do it more or less the old-fashioned way and make sure your singleton object is initialised once and only once.
Related
I'm following this tutorial for create Singleton and the owner have comment when the method below http://www.journaldev.com/1377/java-singleton-design-pattern-best-practices-examples
public class EagerInitializedSingleton {
private static final EagerInitializedSingleton instance = new EagerInitializedSingleton();
//private constructor to avoid client applications to use constructor
private EagerInitializedSingleton(){}
public static EagerInitializedSingleton getInstance(){
return instance;
}
}
If your singleton class is not using a lot of resources, this is the
approach to use. But in most of the scenarios, Singleton classes are
created for resources such as File System, Database connections etc
and we should avoid the instantiation until unless client calls the
getInstance method.
The Problem Is:
They say we should avoid the instantiation until unless client calls the getInstance method
BUT as I know in this code the instantiation (of object instance) always happened when class EagerInitializedSingleton load, and EagerInitializedSingleton just only load when we call EagerInitializedSingleton.getInstance()
=> The instantiation will happened on time with getInstance() and never before getInstance()
Reference:
Static variables are initialized only once , at the start of the execution(when the Classloader load the class for the first time) .
(from https://stackoverflow.com/a/8704607/5381331)
So when are classes loaded?
There are exactly two cases:
- when the new bytecode is executed (for example, FooClass f = new FooClass();)
- and when the bytecodes make a static reference to a class (for example, System.out)
(from http://www.javaworld.com/article/2077260/learn-java/learn-java-the-basics-of-java-class-loaders.html)
Am I wrong or correct. Please give me some sugestion.
In this case with that specific code, you are probably correct.
However, if you had static methods of EagerInitializedSingleton, or static non-final members of EagerInitializedSingleton referenced somewhere in your code base prior to the invocation of getInstance, the instance variable of EagerInitializedSingleton would initialize.
Same with a reflective invocation of Class.forName on your EagerInitializedSingleton class.
Note (and forgive the obvious here) that there are alternative ways of declaring a singleton, including lazy-initialization or enums.
I think the problem is when a class gets loaded without the need to get the instance, but for some other reason. You assume that class will be used the first time when user will want to get an instance of that singleton, but it may happen for some other reason, he may just call a class loader for something, or use some 3rd party software to validate a class, anything that comes to mind that involves loading a class but not getting an instance of a singleton.
They say we should avoid the instantiation until unless client calls
the getInstance method
The solution is lazy loading.
From wikipedia, Initialization-on-demand holder idiom
When the class Something is loaded by the JVM, the class goes through
initialization. Since the class does not have any static variables to
initialize, the initialization completes trivially. The static class
definition LazyHolder within it is not initialized until the JVM
determines that LazyHolder must be executed. The static class
LazyHolder is only executed when the static method getInstance is
invoked on the class Something, and the first time this happens the
JVM will load and initialize the LazyHolder class.
public class Something {
private Something() {}
private static class LazyHolder {
private static final Something INSTANCE = new Something();
}
public static Something getInstance() {
return LazyHolder.INSTANCE;
}
}
Usually I use the first implementation. Couple of days ago I found another.
Can anyone explain me the difference between these 2 implementations ?
The 2nd implementation is thread safe?
What is the advantage of using inner class in the 2nd example?
//--1st Impl
public class Singleton{
private static Singleton _INSTANCE;
private Singleton() {}
public static Singleton getInstance(){
if(_INSTANCE == null){
synchronized(Singleton.class){
if(_INSTANCE == null){
_INSTANCE = new Singleton();
}
}
}
return _INSTANCE;
}
}
//--2nd Impl
public class Singleton {
private Singleton() {}
private static class SingletonHolder {
private static final Singleton _INSTANCE = new Singleton();
}
public static Singleton getInstance() {
return SingletonHolder._INSTANCE;
}
}
The first implementation uses what is called a "double checked lock". This is a Very Bad Thing. It looks thread-safe, but in fact it is not.
The second implementation is, indeed, thread-safe.
The explanation for why the first implementation is broken is fairly involved, so I'd recommend you get a copy of Brian Goetz's Java Concurrency in Practice for a detailed explanation. The short version is that the compiler is allowed to assign the _INSTANCE variable before the constructor has completed, which can cause a second thread to see a partially-constructed object.
The first implementation is only and only thread-safe if the _INSTANCE is made volatile. The second one is thread safe because the _INSTANCE is only initialized once the SingletonHolder is loaded by the class loader.
So when the inner class is accessed for the time (much later than the whole program was loaded), the class loader loads the inner-class and initializes the variable. So for any later access, the object is readily available
Hence the method getInstance() is thread-safe.
The beauty of the second implementation, is you dont have to worry about synchronization or count as class loader does it for you
#1 is designed to ensure lazy initialization. But, in the given case, #2 ensures lazy initialization too. _INSTANCE is created only when Singleton.class is loaded, and Singleton.class is loaded on first invocation of getSingleton(). There is no other method in the class. No double checked locking needed. And of course in #1 _INSTANCE should be volatile.
Note: I do not agree that double checked locking is bad. When implemented correctly it may be very useful.
The first code snippet is an example of the double-checked locking idiom, which used to be quite popular but is now known to be unsafe and should never be used.
The second snippet uses the combination of the semantics of class loading and of the final keyword, as defined by the Java language specification, to ensure lazy initialization and thread safety, so it is much better.
For collection of smaller helper utility classes, I have created a general class MyUtils:
// MyUtils.java
public final class MyUtils
{
public static class Helper1 {};
public static class Helper2 {};
//...
}
This helper classes from inside MyUtils will be used in the other files of the package:
// MyClass1.java
public class MyClass1
{
private MyUtils.Helper1 help1 = new MyUtils.Helper1();
public void method ()
{
private MyUtils.Helper2 help2 = new MyUtils.Helper2();
}
}
To let them accessible, I have made them static inside MyUtils (which doesn't have any data/function member of its own). My code is thread safe before creating MyUtils.
My worry is, by making these inner classes staticwill they remain thread safe, when their multiple instances will exist across the files ? Or is their any bad implication am I missing due to making them static ?
Edit: I am not touching any shared variable inside the helper classes. My only concern was that will the instance of the static classes be thread safe (since they are static).
If you're asking whether these is any bad implication of going from:
public class Helper1 {}
...to:
public class MyUtils {
public static class Helper1 {}
}
Then no, there is not. The static keyword in this case is just "promoting" the nested inner class to a top-level class, so that you can instantiate it without needing an enclosing instance of MyUtils. Here is a passable article on the subject:
http://www.javaworld.com/javaworld/javaqa/1999-08/01-qa-static2.html
In essence, doing public static class X on a nested inner-class is the same as doing public class X in a standard top-level class.
There is no meaning to a "class" itself being thread-safe or not thread safe. Therefore, whether or not it is static is irrelevant.
When someone refers to a class being thread-safe or not thread-safe, they really mean that the functionalities provided by that class are thread-safe or not. Accordingly, it's what the inner classes do themselves that actually makes the difference.
There's nothing inherent about methods that make them unsafe to be reentrant. Problems arise when you start accessing shared variables, etc. So, for example, a member of the class accessed by the methods needs to be synchronized appropriately. But if the methods don't store any state, etc., then there's nothing stopping you from using them across multiple threads.
Hope that helps.
You will need to guard the access to help1 since this is an instance level (shared) variable.
While help2 is safe if you dont allow it to skip the method.
There is nothing special about the static classes and instance created out of it.
Same rules of thread safety applies to instances of static classes also which applies to normal cases.
static methods and inner classes don't have any access to the variables of their dynamic counter part, and consequently can't use monitors/synchronize on an instance of their parent class. Of course this doesn't mean that declaring them and using them is inherently non-thread safe. It's just that if you need to synchronize any of those static methods on an instance of the parent class, then you need to be sure that you synchronize/lock before entering them or else you must explicitly pass a reference to a parent instance into them.
I have got the answer. Making MyUtils an interface is more cleaner design, as I can get away with the static identifienr from the helper classes
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.
I'm creating a static class which is going to hold some vectors with info.
I have to make it synchronized so that the class will be locked if someone is editing or reading from the vectors.
What is the best way to do this?
Is it enough to have a function which is synchronized inside the class like this:
public synchronized insertIntoVector(int id)
{
}
Thanks in advance :)
Firstly, you need to define exactly what you mean by "static class". At first, I thought you meant a class where all methods were static (that wasn't meant to be instantiated) - but your code snippet implies this isn't the case.
In any case, synchronized methods inside the class are equivalent to synchronized(this) if they are instance methods, or synchronized(TheContainingClassName.class) if they're static methods.
If you are either creating a non-instantiable class with all static methods, or if you are creating a class that will act as a singleton, then synchronizing every method of the class will ensure that only one thread can be calling methods at once.
Do try to ensure that your methods are atomic though, if possible; calls to different methods can be interleaved by other threads, so something like a getFoo() call followed by a setFoo() (perhaps after incrementing the foo variable) may not have the desired effect if another thread called setFoo() inbetween. The best approach would be to have a method such as incrementFoo(); alternatively (if this is not possible) you can publish the synchronization details so that your callers can manually hold a lock over the class/instance during the entire sequence of calls.
AFAIK, there's no such thing as "static class" in Java. Do you mean a class that contains only static methods? If so, then
public static synchronized void insertIntoVector(int id) {
}
synchronizes with respect to the class object, which is sufficient, if there are only static methods and all of them are synchronized.
If you mean static inner class (where the word "static" has a different meaning than in static methods), then
public synchronized void insertIntoVector(int id)
{
}
synchronizes with respect to an instance of that static inner class.