On the thread safety of instance variable initialization - java

I see this idiom of initializing instance variables quite a bit
public class Test{
private Long l = 1l;
private MyClass mc = new MyClass();
public Test(){}
...
}
But I would prefer
public class Test{
private Long l;
private MyClass mc;
public Test(){
l = 1l;
mc = new MyClass();
}
...
}
Considering that these are non-final variables, are the 2 approaches equivalent or is one "more" correct than the other in terms of thread safety?

Thread safety isn't an issue because this happens at construction phase, and two threads cannot be constructing the same object. Well, if you let this escape from the constructor, it might be possible for another thread to access the object during construction, but you really shouldn't do that. Functionality-wise, the two options are the same, so even if there were thread-safety issues, they would affect both the same way.
The first option, of initializing the fields at their declaration, is not always possible if you need to do some computation that cannot be done in an initializer (even then, you can keep the initialization out of the constructor if you do it in an initializer block, though). But if either way is possible, then it's purely a style issue, and I don't think there is a clear preference among Java programmers, so go with whichever seems better to you.

since your variables are instance variables, not class variables, you don't have a thread safety issue during initialization using either method. I'm sure others will chime in if there's a Java-standard-recommended best practice.

I think it's the matter of personal preference and your project coding standards.
Just make sure you only initialize variables in one place ( either constructor, or inline ).
Having initialization work done in the constructor gives you a better place for exception handling.

They are both not thread-safe. If thread A constructs the object, then thread B may or may not observer an incompletely initialized Test object or MyClass object. The visibility guarantees after a constructor exits only apply to final fields.
See http://pveentjer.wordpress.com/2007/03/18/immutability-doesnt-guarantee-thread-safety/

In terms of thread safety, they are equivalent. Both will need to execute the same instructions, and if you prefer the second (which I agree with you in your preference) then I would use that. If you want thread safety around a constructor, you would need a synchronized call around the constructor call.

I am not sure if this was answered earlier. But, I have a doubt on the following scenario:
I am trying to create a #Component class where in, I have an instance variable. Now, I want to create a new object of the instance variable for each request. I am not sure which one is the right way to do it?
**Option 1:**
#Component
public class ClassA {
private ClassB classB = new ClassB();
public ClassB create(){
return classB;
}
}
**Option 2:**
#Component
public class ClassA {
private ClassB classB = null;
public ClassB create(){
classB = new ClassB();
return classB;
}
}
**Option 3:**
#Component
public class ClassA {
public ClassB create(){
ClassB classB = new ClassB();
return classB;
}
}

Related

singleton public static final

I've been wondering about singletons in Java. By convention, a singleton is set up something like this:
private static MyClass instance = null;
public static MyClass getInstance(){
if (instance == null){
instance = new MyClass();
}
return instance;
}
private MyClass(){}
Recently I've switched to using the following:
public static final MyClass instance = new MyClass();
private MyClass(){}
This is a lot shorter, faster as there's no null-check, and typing MyClass.instance feels nicer to me than typing MyClass.getInstance(). Is there any reason why the second is not the mainstream way to do this?
The first version creates the instance the first time it is actually needed, while the second (the shorter) runs the constructor as soon as the class is initialized
A class or interface type T will be initialized immediately before the
first occurrence of any one of the following:
T is a class and an instance of T is created.
T is a class and a static method declared by T is invoked.
A static field declared by T is assigned.
A static field declared by T is used and the field is not a constant
variable (§4.12.4).
T is a top level class (§7.6), and an assert statement (§14.10)
lexically nested within T (§8.1.3) is executed. [...]
Invocation of certain reflective methods in class Class and in
package java.lang.reflect also causes class or interface initialization.
The initialization upon first usage is a performance improvement that may speed up the startup of the application if the code in the constructor makes expensive operations. On the other hand, the second version is straightforward to read and is automatically thread-safe.
Anyway, the state of the art is not creating singleton in either ways: for a bunch of KB you can get dependency injection libraries that make it working for you, and also handle more complex scenarios (for example look at Spring and AOP-backed injection).
Note: the first version is not thread safe in the pasted snippet
The way you have first described is known as lazy instantiation, i.e the object will only be created when it is first called. This method is not thread-safe as it is possible for a second thread to create a second instance.
If you read the following book:
Effective Java by Joshua Bloch
He explains that the best implementation of the singleton pattern is through the use of an Enum :
public enum Singleton {
INSTANCE;
public void doSomething() {
...
}
}
Then you would call your singleton through the Enum as follows:
public class Test {
public void test(){
Singleton.INSTANCE.doSomething();
}
}
This fits nicely with what you are saying in terms of it looks nicer and shorter to write but also guarantees there can never be a second instance.
I can think of two reasons:
The first is Encapsulation: you might have second thoughts about how and when your singleton is initialized, after your class has been exposed to client code. And an initialization method gives you more freedom as to changing your strategy later on. For example you might change your mind and decide to use two different constructors instead of one, according to another static variable's value at runtime. With your solution you're bound to using just one constructor at the time your class is loaded into memory, whereas with getInstance() you can change the initialization logic without affecting the interface to the client code.
The second is Lazy Initialization : with the conventional singleton implementation the MyClass object is loaded into memory only when needed by the client code for the first time. And if the client code doesn't need it at all, you save on the memory allocated by your application. Note that whether your singleton is needed or not might not be certain until the program runs. For example it might depend on the user interaction with the program.
However the Lazy Initialization is not something you might necessarily want. For example if you're programming an interactive system and the initialization of your singleton is time consuming, it might actually be better to initialize it when the program is loading rather than when the user is already interacting with it, cause the latter might cause a latency in your system response the first time getInstance() is called. But in this case you can just have your instance initialized with the public method as in:
private static MyClass instance = getInstance();
The best way to synchronize the threads is using Double Checked (to ensure that only one thread will enter the synchronized block at a time and to avoid obtaining the lock every time the code is executed).
public class DoubleCheckLocking {
public static class SearchBox {
private static volatile SearchBox searchBox;
// private attribute of this class
private String searchWord = "";
private String[] list = new String[]{"Stack", "Overflow"};
// private constructor
private SearchBox() {}
// static method to get instance
public static SearchBox getInstance() {
if (searchBox == null) { // first time lock
synchronized (SearchBox.class) {
if (searchBox == null) { // second time lock
searchBox = new SearchBox();
}
}
}
return searchBox;
}
}
Reflection: Reflection can be caused to destroy singleton
property of singleton class, as shown in following example:
// Java code to explain effect of Reflection
import java.lang.reflect.Constructor;
// Singleton class
class Singleton
{
// public instance initialized when loading the class
public static Singleton instance = new Singleton();
private Singleton()
{
// private constructor
}
}
public class GFG
{
public static void main(String[] args)
{
Singleton instance1 = Singleton.instance;
Singleton instance2 = null;
try
{
Constructor[] constructors =
Singleton.class.getDeclaredConstructors();
for (Constructor constructor : constructors)
{
// Below code will destroy the singleton pattern
constructor.setAccessible(true);
instance2 = (Singleton) constructor.newInstance();
break;
}
}
catch (Exception e)
{
e.printStackTrace();
}
System.out.println("instance1.hashCode():- "
+ instance1.hashCode()); //366712642
System.out.println("instance2.hashCode():- "
+ instance2.hashCode()); //1829164700
}
}

initialization block vs constructor vs variable initialization

I'm trying to clean the code of a class that use initialization bloks in a manner I would never do, and I'm just wondering if I am missing some informations. The code looks like this:
#Entity
class MyClass extends BaseClass {
#ManyToMany(fetch=FetchType.EAGER)
private Set<OherClass> others;
{
if (others == null)
others = new HashSet<OtherClass>();
}
public MyClass(){
super();
}
//getters, setters and other stuff follows
}
I think there is no reason to prefer the above code against this:
#Entity
class MyClass extends BaseClass {
#ManyToMany(fetch=FetchType.EAGER)
private Set<OherClass> others = new HashSet<OtherClass>();
}
Or this:
#Entity
class MyClass extends BaseClass {
#ManyToMany(fetch=FetchType.EAGER)
private Set<OherClass> others;
public MyClass(){
this.others = new HashSet<OtherClass>();
}
}
I asked my college, but the only thing he was able to answer is how initialization block works and other things I already know. I wonder if there are some subtle misbehaviour of java (even old one already fixed) or frameworks (hibernate, spring) in case of serialization, reflection, database persistence, injection or any unusual situation that could make that code necessary.
private Set<OherClass> others;
{
if (others == null)
others = new HashSet<OtherClass>();
}
The above code was written without an understanding of Java semantics. others == null will always be true. Therefore this is nothing but a very convoluted and confused way of writing
private Set<OherClass> others = new HashSet<OtherClass>();
Hibernate will indeed wrap some "magic" around the object construction, but it will still need to obtain an instance from the default constructor. At that point all the instance initializers have run.
On a more general note, always prefer to immediately initialize collection-valued variables with constant expressions and, even better, make the field final. That's one less worry for the rest of your code.
With the above you still have all the options open on how to populate the set, which can differ from constructor to constructor.
The only place I see this could be useful, is when the initialization of others needs more than one step and if in the constructor of BaseClass a method is invoked that may be overridden by a sub-class such as MyClass but you want to be sure that others is already properly initialized as it is used by this method. Sounds complicated. I hope that the Java code makes this more clear:
public class BaseClass {
public BaseClass() {
init();
}
public void init() {
// do something...
}
}
public class MyClass extends BaseClass {
private Set<OtherClass> others;
{
others = new HashSet<OtherClass>();
others.add(new OtherClass("hallo"));
// or do more complicated stuff here
}
public MyClass() {
super(); // explicit or may also be implicit
}
#Override
public void init() {
// use initialized others!!
doSomething(this.others);
}
....
}
However, this is a very, very bad pattern and you should never invoke a non-final or non-private method in your constructor as the sub-class may not be properly initialized yet.
Beside that, others is always null if not initialized and you don't have to test this.

Java static initializer seems to be redundant

So I did read the tread of what and when static initalizer is executed from this thread. Static initializer in Java. But I am running into some old code written by someone else and can't seem to understand why he would use it the way he did.
My Class:
public class ClassA extends Thread {
.... private vars ....
private static Config config;
static {
config = null;
}
public ClassA(Config config) {
ClassA.config = config;
}
}
Why didn't he just do this?
public class ClassA extends Thread {
.... private vars ....
private static Config config = null;
public ClassA(Config config) {
ClassA.config = config;
}
}
I understand that static initalizer gets call as the class being redenered, so it sets config => null, while if i don't use static initalizer, instance variables get initalizer right before the constructor, and right after super. So wouldn't the two class be doing the same thing?
These classes are doing the same thing, but more complex static initializers can't always be done on a single line.
The static initializer in your first example won't have any effect on the behavior of that class. You could remove it entirely and nothing would change.
Why did I write x = x + 1 instead of x++ ? No particular reason, I just did it that way. I think it's the same here, because the 2 are basically identical and it doesn't really matter. On the other hand, if more complicated initialization is desired sometime in the future, maybe he can't do that in that single line of code.
The static block will initialize config only once when class is loaded, no matter how many instances of ClassA there are.
It doesn't matter which solution, it's just a technicality, I've seen people use both.
Both are doing exactly the same thing, It a matter of design choice.

Why initialize some variables in a class declaration with one constructor?

I'm new to Java but experienced in C++. I came across some code that I didn't understand:
public class SomeClass {
private SomeOtherClass someOther = new SomeOtherClass();
private AThirdClass thirdClass;
SomeClass() {
this.thirdClass = new AThirdClass();
}
}
Why when there is only a single constructor would you have someOther initialized in the initialization and thirdClass initialized in the constructor?
The below is one reason you may wish to do that.
public class SomeClass {
private SomeOtherClass someOther = new SomeOtherClass();
private AThirdClass thirdClass;
SomeClass( int x ) {
this.thirdClass = new AThirdClass( x );
}
}
But that only explains why you would want to initialize thirdClass in the constructor. I am at a loss to explain why you would want to initialize someOther in the init block.
There is absolutely no reason, unless you get into static declarations, in which case it could make some sense.
There's nothing in your example that would suggest a reason, but underlying implementations may have problematic and poorly-considered code to consider. It may be important for you to know that the initialization of SomeOtherClass in your example will always run before the initialization in the constructor. Someone may have thought that was important.
Or, it could simply be two different developers with two different style preferences. Neither is technically wrong, but both have their (dis)advantages.

Simplified Singleton pattern in Java

The default way to implement singleton pattern is:
class MyClass {
private static MyClass instance;
public static MyClass getInstance() {
if (instance == null) {
instance = new MyClass();
}
return instance;
}
}
In an old project, I've tried to simplify the things writing:
class MyClass {
private static final MyClass instance = new MyClass();
public static MyClass getInstance() {
return instance;
}
}
But it sometimes fail. I just never knew why, and I did the default way.
Making a SSCCE to post here today, I've realized the code works.
So, I would like to know opinions..
Is this a aleatory fail code?
Is there any chance of the second approach return null?
Am I going crazy?
--
Although I don't know if is the right answer for every case, it's a really interesting answer by #Alfred:
I also would like to point out that singletons are testing nightmare and that according to the big guys you should use google's dependency injection framework.
The recommended (by Effective Java 2nd ed) way is to do the "enum singleton pattern":
enum MyClass {
INSTANCE;
// rest of singleton goes here
}
The key insight here is that enum values are single-instance, just like singleton. So, by making a one-value enum, you have just made yourself a singleton. The beauty of this approach is that it's completely thread-safe, and it's also safe against any kinds of loopholes that would allow people to create other instances.
The first solution is (I believe) not thread-safe.
The second solution is (I believe) thread-safe, but might not work if you have complicated initialization dependencies in which MyClass.getInstance() is called before the MyClass static initializations are completed. That's probably the problem you were seeing.
Both solutions allow someone to create another instance of your (notionally) singleton class.
A more robust solution is:
class MyClass {
private static MyClass instance;
private MyClass() { }
public synchronized static MyClass getInstance() {
if (instance == null) {
instance = new MyClass();
}
return instance;
}
}
In a modern JVM, the cost of acquiring a lock is miniscule, provided that there is no contention over the lock.
EDIT #Nate questions my statement about static initialization order possibly causing problems. Consider the following (pathological) example:
public ClassA {
public static ClassB myB = ClassB.getInstance();
public static ClassA me = new ClassA();
public static ClassA getInstance() {
return me;
}
}
public ClassB {
public static ClassA myA = ClassA.getInstance();
public static ClassB me = new ClassB();
public static ClassB getInstance() {
return me;
}
}
There are two possible initialization orders for these two classes. Both result in a static method being called before the method's classes static initialization has been performed. This will result in either ClassA.myB or ClassB.myA being initialized to null.
In practice, cyclic dependencies between statics are less obvious than this. But the fact remains that if there is a cyclic dependency: 1) the Java compiler won't be able to tell you about it, 2) the JVM will not tell you about it. Rather, the JVM will silently pick an initialization order without "understanding" the semantics of what you are trying to do ... possibly resulting in something unexpected / wrong.
EDIT 2 - This is described in the JLS 12.4.1 as follows:
As shown in an example in §8.3.2.3, the fact that initialization code is unrestricted allows examples to be constructed where the value of a class variable can be observed when it still has its initial default value, before its initializing expression is evaluated, but such examples are rare in practice. (Such examples can be also constructed for instance variable initialization; see the example at the end of §12.5). The full power of the language is available in these initializers; programmers must exercise some care. ...
The second example is preferable, since the first isn't thread safe (as pointed out in the comments). The first example uses a technique called lazy instantiation (or lazy initialization), which ensures that the Singleton instance isn't created unless it's actually needed. This isn't really necessary in Java because of the way Java handles class loading and static instance variable initialization.
I also would like to point out that singletons are testing nightmare and that according to the big guys you should use google's dependency injection framework.
Remember, you need to declare a private constructor to ensure the singleton property.
The second case could be even simpler with just
class MyClass {
public static final MyClass instance = new MyClass();
private MyClass() {
super()
}
}
`
As others have noted, the first is not thread-safe. Don't bother with it as the second is perfectly fine, and will instantiate the object only when MyClass is referenced. Further it makes the reference final which expresses the intent better.
Just make sure that the declaration
private static final MyClass INSTANCE = new MyClass();
is the first static declaration in your class to avoid risk of calls to getInstance() or INSTANCE before it is initialized.
Don't forget the SingletonHolder pattern. See this SO question.
I don't know the answers to your questions, but here is how I might structure the same thing.
class MyClass {
private static MyClass instance;
static {
instance = new MyClass();
}
private MyClass() { }
public static MyClass getInstance() {
return instance;
}
}

Categories