singleton-early initialization ,static field initialization and class loading - java

Conside this code:
class MyClass {
private static MyClass myobj = new MyClass();
private MyClass() {
}
public static MyClass getMyobj() {
return myobj;
}
}
1)IN above code when will myobj get initialiazed-when Myclass gets loaded OR when getMyobj() will be called first time as MyClass.getMyobj();?
2) Suppose we call twice as:
MyClass.getMyobj();
MyClass.getMyobj();
will it create new MyClass() object on second call?

When your class will be loaded
No , it won't create another object, it will use the already existing one

1)IN above code when will myobj get initialiazed
When the class is first loaded.
2) Suppose we call twice as:...will it create new MyClass() object on second call?
No mainly because myobj is static so getMyobj() will always return the same instance, the one created at load time.

When MyClass gets loaded.
Even if you call it ten times, only one instance exists for MyClass.

As has been pointed out the object will be created when the class is initialised, and because the method simply returns it, no other such instances will be created in the example code.
However, if you want to do such a thing you could also create an enum with a single instance:
public enum MyClass {
myobj;
}
Then code which needs to work with myobj can simply access the MyClass.myobj field while the code itself retains singleton behaviour. Of course a similar effect may be accomplished with a public static final field.
The enum has the benefit that the compiler knows you do not want to accidentally create arbitrary objects. It has the downside that if you want lazy initialisation instead you would need to introduce an additional delegate for the lazily loaded part.

As soon as MyClass is loaded, it will get initialized.But it will initialize only one time.

It is not correct to say that a class gets initialised as soon as it is loaded. A class will only be initialised once a running program creates an instance of that class (by calling its constructor with the new keyword) or once any of the static methods or fields belonging to the class are used.
See the Java Language Specification section 12.4.1 for the JVM rules on initialisation.
I should point out that I only know this thanks to the excellent book by Joshua Bloch, "Effective Java, Second Edition". Item 71 offers advice about lazy initialization and the "lazy initialization holder class idiom".
So, in answer to your question, MyClass.myobj will only be initialised when a running program (such as your main() method) actually makes a call to MyClass.getMyobj() and not a moment before then.
And because static fields are only initialised once per class, the next time MyClass.getMyobj() is called, it will simply return the existing value for MyClass.myobj, so you will get two references to exactly the same MyClass object.

Related

Object and instance are same things?

While reading about synchronization, I read static synchronized method locked on class object and synchronized method locks on current instance of an object.
I have confusion what is class object and instance of an object? Don't object and instance are same things?
For every class loaded into JVM , an instance of class Class will be created.
for ex:
Student student = new Student()
when above line of code executed class (Student) get loaded into JVM first bcz JVM needs template to create object .And based on template JVM creates instance of Student in heap .Along with Student instance JVM creates instance of class Class in heap.This class instance all the information about STudent like number of constructors,methods,variables etc we use for reflection.
Now all the instances (object) created will have a lock associated with then which comes into picture when executing synchronized methods or blocks (which can be static or instance) . if you are executing any static methods in synchronized context then lock of Class class (of STudent) will be acquired until its completion .
The operative word there is class. Every class has an instance of java.lang.Class that represents it in the current classloader.
Consider this simple example:
public class MyClass {
public synchronized void instanceMethod() {
// This method will synchronize on the instance of MyClass that called it
}
public static synchronized void staticMethod() {
// This method will synchronize on MyClass.class
}
}
I think whatever you are reading this from could have worded this in a better way.
The difference between synchronised instance methods and synchronised static methods is that the latter "locks" the class while the former locks the instance of that class on which the synchronised method is called. See this answer for more info.
Assuming the author knows what he/she is talking about, the word "class object" creates confusion, because classes themselves are not objects. Is he/she talking about instances of Class<T>? Probably not. The author should have just said "class".
As to what's the difference between "object" and "instance" outside of the context of synchronisation, they mean really the same thing - those things that you create by calling constructors (and string literals).
Personally, I think that the word "object" has a higher level abstraction. When I am talking at a low level of abstraction (talking about individual lines of code e.g. "I created an instance of Foo here by writing new Foo()"), I would use "instance". When I am talking about things on a higher level (like how the whole system works), I tend to use "object". But this might be just me. Other people might use them interchangeably.

When using a static method, does the class every get instantiated?

Say I have a static method increment:
public class StaticTest {
private static int no = 0;
public static void increment()
{
no++;
}
}
When I call increment using the StaticTest.increment() syntax, does the class ever get instantiated? What if no object of that type exists on the heap already?
When I call increment using the StaticTest.increment() syntax, does the class ever get instantiated?
The class, itself, is loaded (by the classloader), if it isn't already loaded. If it's already loaded, it is not loaded a second time. No instances of the class (objects of that class's type) are created, because you haven't created any.
Assuming all of the code that calls StaticTest.increment() is using the same classloader (which is normally the case), it doesn't matter how many different bits of code call that static method, just a single copy of the class is used. They all share it. E.g.:
// Some bit of code somewhere
StaticTest.increment();
// Another bit of code somewhere else
StaticTest.increment();
// A third bit of code in yet another place
StaticTest.increment();
Once all of those have run, the no private static member in StaticTest has the value 3.
What if no class of that type exists on the heap already?
Then then classloader loads it.
Contrast that code with this (no statics):
public class NonStaticTest {
private int no = 0;
public void increment()
{
no++;
}
public int getNo() // So we can see the results
{
return no;
}
}
Now, we can't do this:
NonStaticTest.increment(); // WRONG, fails with error saying `increment` is not static
We do this instead:
NonStaticTest instance = new NonStaticTest();
instance.increment();
System.out.println(instance.getNo()); // "1"
The first time code does that, the NonStaticTest class is loaded by the classloader. Then, the new NonStaticTest() expression creates an instance of the class, which has a no member. The second time code does that, NonStaticTest has already been loaded, so it's not loaded again. Then the new NonStaticTest() expression creates a second instance of the class.
If we had three bits of code all doing the above, each of them would see "1", because no is specific to an instance of the class rather than being attached to the class itself.
You have to clearly differentiate between 2 things:
classes, which are sort of "custom types" (I'm simplifying here)
objects, which are instances of these classes
Classes are loaded once by the classloader, whereas objects of a class are created each time you call new ClassName() (if the class is called ClassName).
Now, back to your problem: the use of the static keyword makes your declarations independant of any instance (object) of your class.
Therefore, when you use StaticTest.increment(), no object of the class StaticTest is created (and no object is needed).
You instantiate an instance with new StaticTest and unless you created one of those, you haven't created an instance.

Java Object Class, Constructor Chaining

Does this code get called for every object creation in Java, because every object extends Object ? Or does the JVM optimize it in some way to avoid the creation of some many Object's object in the heap.
What exactly happens in this method registerNatives().
package java.lang;
public class Object {
private static native void registerNatives();
static {
registerNatives();
}
Static blocks are only executed once, when the class is loaded.
As explained here or here, a block that will be executed every time an object of the class is initialized can also be defined : just remove the static keyword.
It does n't matter what registerNatives(). does. What does matter here is that you have enclosed it in static block. Static Blocks loaded and run when java Class Loader loads classes. So it is guaranteed to run exactly once per JVM.
1. The question here is not about Constructor chaining, but about static.
2. static variable will be initialized when the JVM loads the class, and JVM loads the class when the class is instantiated or any static method of that class is called.
3. So this static block will run every one time the JVM loads the class.

Deferred initialization of immutable variables

I've been using scala's lazy val idiom a lot and I would like to achieve something similar in Java. My main problem is that to construct some value I need some other value which is not known at object construction time, but I do not want to be able to change it afterwards. The reason for that is, I'm using a GUI library which instanciates the object on my behalf and calls a different method when everything I need is created, which is when I know the values I need.
Here are the properties I try to achieve:
* Immutability of my variable.
* Initialization in some other method than the constructor.
I do not think this is possible in Java, for only final achieves immutability of the variable and final variables cannot be initialized outside of the constructor.
What would be the closest thing in Java to what I am trying to achieve ?
One way to do it would be to push the actual instantiation of the value in question into another class. This will be final, but won't be actually created until the class is loaded, which is deferred until it is needed. Something like the following:
public class MyClass
{
private static class Loader
{
public static final INSTANCE = new Foo();
}
Foo getInstance()
{
return Loader.INSTANCE;
}
}
This will lazily initialise the Foo as and when desired.
If you absolutely need the Foo to be an instance variable of your top-level class - I can't think of any way off-hand to do this. The variable must be populated in the constructor, as you noted.
In fact I'm not sure exactly how Scala gets around this, but my guess would be that it sets the lazy val variable to some kind of thunk which is replaced by the actual object when first evaluated. Scala can of course do this by subverting the normal access modifiers in this case, but I don't think you can transparently do this in Java. You could declare the field to be e.g. a Future<Foo> which creates the value on first invocation and caches it from that point on, but that's not referentially transparent, and by the definition of final I don't see a way around this.
Andrzej's answer is great, but there is also a way to do it without changing the source code. Use AspectJ to capture Constructor invocations and return non-initialized objects:
pointcut lazyInit() : execution(* com.mycompany.expensiveservices.*.init(*));
void around() : lazyInit() && within(#Slow *) {
new Thread(new Runnable(){
#Override
public void run(){
// initialize Object in separate thread
proceed();
}
}
}
Given this aspect, all constructors of objects marked with a #Slow annotations will be run in a separate thread.
I did not find much reference to link to, but please read AspectJ in Action by Ramnivas Laddad for more info.

Java member object inside class of same type

I am looking at a codebase and I often see something like:
public class SomeClass
{
protected static SomeClass myObject;
//...
public static SomeClass getObject()
{
return myOjbect
}
}
I'd like to make sure I understand the purpose behind this. Is it to ensure one instance of the class gets shared even if it is instantiated multiple times? I am not sure about the vocabulary here, or else I'd search for the answer, so if this pattern has a name, please let me know.
Also, this seems a little chicken-and-egg definition because the class includes an object of the type of the class. Why isn't this actually paradoxical?
Thanks!
This is really only common with the Singleton Pattern where there is only this one instance of the class. While it has its uses, Singleton is over- and misused more often than not (usually to disguise procedural programming as OO). It also occurs very often in example code for Java AWT or Swing, where you typically subclass Frame / JFrame, and create an instance in a main method inside the same class.
Also, this seems a little
chicken-and-egg definition because the
class includes an object of the type
of the class. Why isn't this actually
paradoxical?
Why do you think it is? The class mainly describes what members instances of this type have - but a static member does not belong to an instance, it belongs to the class itself, so it doesn't have anything to do with the "blueprint" role of the class. Static members are really somewhat un-OO because of that.
But even on the instance level you can have references of the same type. For example, an entry in a linked list would typically have two references to the next and previous entries, which are of the same class.
This is called the Singleton design pattern.
You are correct in stating that the purpose is to ensure only one instance of the class gets created.
Wikipedia has a preyty good article on the pattern.
The pattern you mentioned is called "Singleton", but from your code sample it is not clear if this is really what is intended. Due to the fact that the member is protected, I would guess not - if there are subclasses, then there would probably not be a single instance.
It's called Singleton. You ensure the creation of just ONE (1) object of a given class.
You should add a private Constructor, so the only one who create the object is the class.
public class SomeClass
{
// Using private constructor
protected static SomeClass myObject = new SomeClass();
private SomeClass(){
//...
}
public static SomeClass getObject()
{
return myOjbect
}
}
Much much more here, in Wikipedia
You may want to take a look to Factory Pattern
It's not all that uncommon; it can be a good way to implement the Singleton pattern. There can be other uses as well - sometimes you will want a handful - and no more - of objects of a given class; that class is a good place to hang onto them. In the event that you don't want other classes to be able to create objects of this class, it is common to give the class a private constructor as well.
It's not paradoxical, because the compiler can be aware of a reference to the class before it has fully compiled the class. Later - if you like to think of it this way - it can "fill in the blanks".

Categories

Resources