Friday, 5 November 2010

a good webiste : 2010.11.5.20.33

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML><HEAD>
<META http-equiv=Content-Type content="text/html; charset=gb2312">
<META content="MSHTML 6.00.2900.6036" name=GENERATOR></HEAD>
<BODY>
<P><BR><FONT face=@新宋体 size=5>hello,my friend<BR>&nbsp;<BR>Thanks for your
attention on our web <A href="http://t1eshop.com">t1eshop.com</A> in the past
time.</FONT></P>
<P><FONT face=@新宋体 size=5>Now,I want to tell you guys a good news.Our web has
more products,so you can enjoy yourselves by buying.</FONT></P>
<P><FONT face=@新宋体 size=5>If there is no what you want, please tell
us.</FONT></P>
<P><BR><FONT face=@新宋体 size=5>regards </FONT></P></BODY></HTML>


<hr>

2010.11.5.20.33

Friday, 26 February 2010

Loading, Linking, & Initialization of Types in Java

The Java Virtual Machine makes the Types (we'll discuss here the user defined Types - classes and interfaces... built-in types also undergo similar set of phases and they are normally loaded as part of the JVM process start-up) available to a Java program under execution and any Type undergoes the following phases during its entire life cycle:-

* Loading - this is the process of loacting the bytecodes (.class file) of the correponding Type and bringing that into the JVM memory.
* Linking - this is the process of incorporating the loaded bytecodes into the Java Runtime System so that the loaded Type can be used by the JVM.
* Initialization - this is the process of executing the static initializers of the loaded and linked Type.
* Unloading - this is the process of reclaiming the memory occupied by the Loaded, Linked, and Initialized Type. This happens when there are no references of that Type and hence the Type becomes eligible for garbage collection. It's important to note that garbage collection of objects is different from that of Types. An object of a Type is collected during the next garbage collection cycle soon after it becomes unreachable, but the Type is unloaded only when all the objects of that Type are already garbage collected and the Type doesn't have any other reference to it.

Creation of java.lang.Class instance of a Type


An instance of the class java.lang.Class is created for every Type loaded into the underlying JVM. This instance creation marks the end of the loading phase of the Type. If an application is distributed across multiple JVMs then for the same application one (or more) Types may be required to be loaded multiple times (one per JVM) as a JVM can't use a Type without the corresponding java.lang.Class instance. While loading a Type, the bytecodes (of the .class file) are first converted into a binary stream so that they can be brought into the JVM memory. Once the stream has been successfully brought into JVM memory, the format of the stream is checked to verify if it's as per the specifications or not. This step helps making the Java code very secure as the underlying Security Manager can simply raise an alarm if the loaded binary stream is not havng a valid structure (either tempered accidently or intentionally) and hence it can safely eliminate the possibility of running a malicious and dangerous code on the machine. This is not possible in other languages like C, where the compiled and linked .exe (on Windows) and .out (on Linux) files are directly executed by the underlying Operating Systems as they are composed of native instructions.


But, we know Verification is a part of the Linking phase, so what does the verification done in the Loading phase mean? How are the two verifications different? Well... verification is certainly a part of the Linking phase (it's the first step of the Linking phase), but implementations do use verifications of different type during various other stages as well. This is done to ensure the integrity of the running JVM. The specification clearly says that a loaded Type should not cause the JVM process to hang and if the implementations remove the verification part completely from the Loading phase then a malicious bytecode may cause the JVM to hang (or to perform something unpredictable) while creation of the java.lang.Class instance for the loaded Type.


This java.lang.Class instance is actually the complete representation of the loaded Type built using the implementation dependent internal data structures. This is subsequently used by the various steps of the Linking phase (and also during the Initialization phase). These two phases - Linking and Initialization don't deal with the raw byte stream loaded during the Loading phase.


java.lang.LinkingError - what does it signify & when is it thrown?


The Java Specifications doesn't enforce any restriction on the actual timing of the Loading & Linking phases of a Type (also not on the exact timing of the Unloading phase as that is decided by the garbage collection algorithm), but Initialization phase is required to be done only when the Type gets its first active usage. One thing is very obvious that these phases will be performed in this order only. How will a Type be linked before being loaded otherwise? Without linking how will the initializers be executed otherwise? Most of the implementations do the Loading (and also the Linking in many) in anticipation of the usage of Types and only Initialization is required to be done at first usage of those Types in such cases.


Any problem encountered while any of the three phases is captured by instances of LinkageError class or an appropriate sub class of this class. Most of the JVM implementations normally load the Types much earlier and delay the linking and initialization phase till the first use of the Type. Many others delay only the Initilization till the first use and they perform both Loading and Linking much before the first usage of the Type. Irrespective of whether the any or all the phases are completed just before first use or earlier, any error encountered during any of the phases (captured by the appropriate subclasses of the LinkageError claas) must be thrown only at the time when the Type's first use is encountered not before that. If a Type is never used actively then the captured error is never thrown and the program proceeds normally.


Thus we see that the loading, linking, and initialization of a Type must give an impression that they are done only when the Type is actually used even if Loading and/or Linking phases have already been completed in the particular JVM implementation.


java.lang.LinkageError simply indicates that the loaded class has encountered some problem during Loading, Linking or Initialization phase. The name is misnomer here and as it doesn't only indicate a problem encountered only during the Linking phase (It'll be clear in the next paragraph).


One possible scenario when this error java.lang.LinkageError (or a suitable subclass of this class) may occur:- Suppose we have two classes and one is dependent on the other. Now, after compilation of the dependent class if the other class is changed and compiled then the former class may throw LinkageError while linking - such a situation will actually throw an instance of the subclass of this class named IncompatibleClassChangeError.


java.lang.LinkageError has seven subclasses - all specifying a specific scenario indicating the kind of error encountered while Loading, Linking, or Initialization of a Type. These sub classes are:-

* ExceptionInInitializerError - some unexpected exception occured in a static initializer
* ClassFormatError - malformed or unrecognizable .class file
* NoClassDefFoundError - the .class file couldn't be located by the ClassLoader
* ClassCircularityError - when a circularity is detected while initialization
* UnsatisfiedLinkError - if the JVM can not find the native language definition of a native method
* VerifyError - if the JVM detects any problem with the structure of the .class file
* IncompatibleClassChangeError - an incompatible change detected in a class by a dependent class

As you can easily notice that the LinkageError doesn't only specify a problem encountered only in the Linking phase, instead it has specific sub classes to capture the potential errors which may occur during any of the three phases - Loading, Linking, and Initialization.

Java architecture, JRE, Java Platform, JVM, JDK

Java Architecture


Java is much more than just a popular programming language instead it's a complete architecture. The entire Java archirecture can be broadly categorized into three technologies which work together to make Java a powerful software development architecture. The components of the Java architecture are:-

* The Java Programming Language - JLS (Java Langauge Specifications) provide the syntax, constructs, grammar, etc. of the Java language.
* The Java APIs - Java Application Programming Interfaces (APIs) make available plethora of functionalities to the application developers so that they can focus on their core business functionality without bothering about the common tasks including those from the areas - I/O, Network, Language Constructs, Multithreading, Serialization, etc. Many vendors have implemented these APIs including the standard implementation given by Sun Microsystems which is normally used as a benchmark. The Java APIs are simply a collection of Java .class files. A .class file is the bytecode representation of a valid Java program. Bytecodes are a collection operator-operand tuples which are converted into the native machine level instructions by the underlying JVM.
* The Java Virtual Machine - The JVM is the abstract machine which runs all the bytecodes on a particular machine. JVM converts the bytecodes into native instructions which are executed by the underlying Operating System.


JVM - Java Virtual Machine


This software component is the key to achieve Platform Independence feature of Java. Most of the popular platforms have their own JVM implementations and hence a Java program written and compiled on a Java-compliant platform can be run on any other Java-compliant platform.


JVM is mainly composed of two components - Classloader and Execution Engine. The first component loads the .class files after converting them into the implementation dependent internal data structures. The Execution Engine uses these data structures are converts the bytecode instructions into machine-level instructions for the underlying Operating System which are subsequently executed by the OS.


Java Runtime Environment (JRE) / Java Platform


Both the terms JRE and Java Platform represent the same thing. Java Platform started with the verion 1.2, and it was called The Java 2 Platform. JRE is nothing but a combination of JVM and Java APIs - Java SE APIs as well as Java Web (Deployment) which consists of Java Web App Development/Deployment, Java Web Start, and Applet (plug-in).


Java Development Kit (JDK)


As the name suggest it's a Kit and it contains all the software components used for compiling, documenting, and executing Java programs. It's basically a logical collection of the The Java Programming Language, JRE (JVM + Java APIs), and Tools & Tool APIs, which include java, javac, javadoc, apt, jar, javap, Deploy, Monitoring, Java VisualVM, Scripting, etc.

Java architecture, JRE, Java Platform, JVM, JDK

Java Architecture


Java is much more than just a popular programming language instead it's a complete architecture. The entire Java archirecture can be broadly categorized into three technologies which work together to make Java a powerful software development architecture. The components of the Java architecture are:-

* The Java Programming Language - JLS (Java Langauge Specifications) provide the syntax, constructs, grammar, etc. of the Java language.
* The Java APIs - Java Application Programming Interfaces (APIs) make available plethora of functionalities to the application developers so that they can focus on their core business functionality without bothering about the common tasks including those from the areas - I/O, Network, Language Constructs, Multithreading, Serialization, etc. Many vendors have implemented these APIs including the standard implementation given by Sun Microsystems which is normally used as a benchmark. The Java APIs are simply a collection of Java .class files. A .class file is the bytecode representation of a valid Java program. Bytecodes are a collection operator-operand tuples which are converted into the native machine level instructions by the underlying JVM.
* The Java Virtual Machine - The JVM is the abstract machine which runs all the bytecodes on a particular machine. JVM converts the bytecodes into native instructions which are executed by the underlying Operating System.


JVM - Java Virtual Machine


This software component is the key to achieve Platform Independence feature of Java. Most of the popular platforms have their own JVM implementations and hence a Java program written and compiled on a Java-compliant platform can be run on any other Java-compliant platform.


JVM is mainly composed of two components - Classloader and Execution Engine. The first component loads the .class files after converting them into the implementation dependent internal data structures. The Execution Engine uses these data structures are converts the bytecode instructions into machine-level instructions for the underlying Operating System which are subsequently executed by the OS.


Java Runtime Environment (JRE) / Java Platform


Both the terms JRE and Java Platform represent the same thing. Java Platform started with the verion 1.2, and it was called The Java 2 Platform. JRE is nothing but a combination of JVM and Java APIs - Java SE APIs as well as Java Web (Deployment) which consists of Java Web App Development/Deployment, Java Web Start, and Applet (plug-in).


Java Development Kit (JDK)


As the name suggest it's a Kit and it contains all the software components used for compiling, documenting, and executing Java programs. It's basically a logical collection of the The Java Programming Language, JRE (JVM + Java APIs), and Tools & Tool APIs, which include java, javac, javadoc, apt, jar, javap, Deploy, Monitoring, Java VisualVM, Scripting, etc.

Concurrent execution of static and non-static synchronized methods

We have a scenario where we have a static synchronized method and a non-static synchronized method. As we know that a static method can only access static members of the class whereas a non-static method can access both static as well as non-static members. This liberty can put us into a situation where a non-static method might be updating some static data which a static method would also be changing. What will happen if two different threads try to access the static and non-static synchronized methods concurrently and in turn try to change the static data using the two methods? Will the synchronization guarantee mutual exclusion in such a case?


No... synchronization won't guarantee mutual exclusion in such a case as both the threads may access the static and non-static synchronized methods concurrently because a non-static synchronized method requires the invoking thread to acquire a lock of the particular object on which the thread invokes the non-static synchronized method whereas a static synchronized method will require the invoking thread to acquire a lock on the java.lang.Class object associated with the particular class (which the static method is a part of). Both these locks have nothing to do with each other and they can be acquired by different threads at the same time and hence two different threads may execute a static method and a non-static synchronized method of a class respectively at the same time (of course once they acquire the two locks).


It is certainly not advisable to allow such a thing to happen and hence the design of such a class needs to be re-checked. Otherwise the errors caused by simultaneaous modification of the same static data by different threads may infuse some really-hard-to-detect bugs.


Thus, we see that only declaring the methods as synchronized doesn't ensure mutual exclusion and the programmer should always think about the locks involved to achieve the actual purpose of synchronization.


Have a look at the following simple example where the same static data is being modified by two public synchronized methods - one being static and the other being non-static. The whole purpose of synchronization is getting defeated here as in such a case mutual exclusion can't be guaranteed, which is one of main purposes of using synchronization.


public final class BadDesign{

private static int sensitiveData;

public synchronized static void changeDataViaStaticMethod(int a){

//... updating the sensitiveData

sensitiveData = a;

}


public synchronized void changeDataViaNonStaticMethod(int b){

//... updating the sensitiveData

sensitiveData = b;

}


public static void showSensitiveDataStatic(){

System.out.println("Static: " + Thread.currentThread().getName()+ " - " + sensitiveData);

}


public void showSensitiveData(){

System.out.println(Thread.currentThread().getName() + " - " + sensitiveData);

}


public static void main(String[] args){

new Thread(new TestThread11()).start();

new Thread(new TestThread11()).start();

}


}


class TestThread11 implements Runnable{


public void run(){

int i = 0;

do{

BadDesign.changeDataViaStaticMethod(5);

BadDesign.showSensitiveDataStatic();


//... new object for every iteration

//... so synchronization of non-static method

//... doesn't really do anything significant here

BadDesign bd = new BadDesign();

bd.changeDataViaNonStaticMethod(10);

bd.showSensitiveData();

}while (i++ < 100);

}

}


An excerpt from the output:-

...

Static: Thread-0 - 5

Thread-0 - 10

Static: Thread-0 - 5

Thread-0 - 10

Thread-1 - 10

Static: Thread-0 - 5

Static: Thread-1 - 5

Thread-1 - 10

...


By looking at the above exceprt you can easily conclude that the static and non-static synchronized method calls are intermixed between the two threads: Thread-0 and Thread-1. In this case the non-static synchronized method is always being called on a new object (as the do-while loop of the run() method is creating a new object of the class BadDesign for every non-static synchronized method call) by both the threads and hence synchronization doesn't really do anything significant for them as every new object will have its own lock which will be easily acquired by the invoking thread everytime the do-while loop iterates. I've kept this just to make the code simple as my purpose of the above example is just to show that static synchronized methods and non-static synchronized methods are completely independent of each other and both of them can run at the same time by different threads for the simple reason that both these methods are governed by different locks which may be acquired at the same time by two different threads.

Deadlock - what's it? How to deal with a Deadlock situation?

What's Deadlock?


It's basically a situation where two or more threads are blocked forever waiting for each other to release an acquired monitor to proceed further.


Let me try to explain it using an example. Suppose we have two thread - threadA and threadB. There are two objects of a class TestClass - objA and objB and we have two synchronized instance methods in TestClass named A and B. Method A accepts an argument of type TestClass and calls method B from the passed object reference. Now, consider a situation where the first thread - threadA acquires the monitor of objA and enteres into the synchronized method A() on objA with the passed object reference as objB and at the same time threadB enteres into the same synchronized method 'A' on the object reference - objB with the passed object reference to the method as objA. Now, both the threads will keep waiting for the monitors of the objects - objB and objA respectively to complete the execution of the synchronized method A() and hence such a situation will result into a Deadlock. Of course such a situation will probably happen only rarely, but it's definitely a possible scenario. Calling the start() method on a Thread instance only ensures that the particular thread will participate in the CPU Scheduling, but we never know when exactly the thread will actually be allocated the CPU and in turn will start the execution.


Example: Java program having a possibility of Deadlock


public class PossibleDeadlockDemo {


static class TestClass {

...

...


public synchronized void A (TestClass testClass) {

...

testClass.B();

}


public synchronized void B () {

...

}

}


public static void main(String[] args) {

final TestClass objA = new TestClass("ObjectA");

final TestClass objB = new TestClass("ObjectB");


Thread threadA = new Thread(new Runnable() {

public void run() { objA.A(objB); } });


Thread threadB = new Thread(new Runnable() {

public void run() { objB.A(objA); } });


threadA.start();

threadB.start();

}


}


How to deal with a Deadlock situation?


Probably the only possible way to rectify a Deadlock situation is to avoid it. Once the deadlock has already happened then you'll probably left with the only option of restarting the JVM process again OR it may even require you to restart the underlying OS. This is very hard to reproduce and debug because one can never be sure about when exactly the threads will be executed and hence the deadlock may not happen when you test it and eventually it may happen when the code actually goes into production. So, review the design of your mulithreaded application before you really start coding. You may somehow manage to escape any such situation or at least minimize the possibility to a great extent with a better design.

Guarded Blocks in Java - what are they & why are they used?

This is one of the most popular mechanisms of co-ordinating the execution of multiple threads in a multithreaded application. Such a block keeps checking for a particular condition to become true and only in that case the actual execution of the thread resumes.

Why should a thread's execution required to be co-ordinated with that of other threads? There may be several reasons - one of them being, if multiple threads are modifying a shared data and one (or maybe more) threads can't really proceed unless the shared data acquires a particular value (otherwise the execution may cause some incosistency/business-error or something of that sort) then in such a case we can have a condition checking the value of that shared data in that particular thread and can allow the execution of the thread to proceed only when the condition is true.

Now what the thread will do until then? Based on how the thread reacts to a 'false' condition, guarded blocks are of two types:-

* synchronized guarded block - in this case if the condition is false then the block (which is a synchronized block) simply calls the Object.wait() method to release the acquired monitors on that object and leaves the processor to be used by other threads (probably more effectively as the current thread would not have done anything significant in this case unless the condition becomes true).
* non-synchronized guarded block - in this case we simply cause the execution to keep executing a blank loop until the condition becomes true. This approach has an obvious disadvantage of wasting the precious CPU time, which could have been better utilized by some other threads otherwise.


Example: synchronized guarded block - Java code snippet

public synchronized guardedBlock() {

while(!sharedBooleanFlag) {
try {
wait();
} catch (InterruptedException e) {}
}

System.out.println("Shared Boolean Flag is true - you may proceed now!");

}

non-synchronized guarded block - Java code snippet

public guardedBlock() {

while(!sharedBooleanFlag) {
//... empty loop
}

System.out.println("Shared Boolean Flag is true - you may proceed now!");

}

A thread which is in waiting state on an object may be interrupted/notified by some other thread either intentionally or accidentally and hence may start execution after getting re-scheduled, but that doesn't guarantee that the condition (which is required to be true for the thread to proceed further) has also become true and hence one needs to make sure that the wait() method is always called inside the loop which checks for the condition. If the thread wakes up and starts its execution before the condition becomes true then it'll immediately go to the waiting state once again which will obviously save the precious CPU time to be utilized by other threads and at the same time such an approach will always guarantee that the execution of the thread will proceed only in the expected manner.

Don't forget to ensure that the application has other threads which acquire locks on the objects (on which few other threads have previously called wait() method) and call either notify() and notifyAll() methods so that the application can avoid startvation of those threads which have called wait() on the objects under consideration. notifyAll() scheduled all the waiting threads whereas notify() randomly picks one of the waiting threads and schedules it. Use the method which suits the design of your application.

Can we access an unreachable object in Java?

Yeah... we can. Sounds strange? But, it's true. We can access an unreachable object in Java.


This can be done by overriding the finalize() method and inside the method we can assign the reference 'this' to some other active reference and this way the unreachable object becomes reachable again which can be accessed like any other object. However this is not a good practice and it's seldom used (if at all).


What's finalization in Java and what's it used for?


In Java it's mainly used for doing the postmortem cleanup activities particularly used for reclaiming native resources or any other non-memory resources which can't directly be recollected by the Garbage Collector.


How the finalization of an object happens internally?


protected void finalize() throws Throwable is the signature of the finalize() method in the Object class and whenever any class overrides this method then an object of that class is internally marked by the JVM as finalizable. If such an object becomes unreachable then the Garbage Collector adds it to the JVM's finalization queue. It also makes sure that all the objects reachable from that object are also retained as it can't be sure what all objects may be accessed from inside the finalize() method. Now the object is dequeued from the finalization queue and the finalize() method is executed on that object. Once the control exits from the finalize() method then the object is considered to be finalized which is again tested by the Garbage Collector and if the GC finds that the finalilzed object is unreachable then it reclaims the memory space occupied by that object and also the spaces occupied by other unreachable objects which were retained simply because they were reachable from the finalizable object.


You can easily deduce that such a lengthy process obviously takes time and consequently slows down the performance. Hence it's always advisable to use (override) the finalize() judiciously.


What if the super class is finalizable but not the sub class?


This is not possible as the sub class will automatically become finalizable by inheriting the finalize() method from the super class. Do consider the consequences thoroughly before making any class finalizable otherwise you may end up with memory renetion problems. For example: if a super class is finalizable and sub class which is not explicitly finalizable is having fields occupying huge memory chunks then reclamation of memory occupied by a sub class instance will be delayed till the associated super class instance gets finalized. How to deal with such a situation? Well... you can use composition in stead of inheritance to avoid this problem. This will make sure that reclaimation of only the field of the finalizable class type gets delayed and not the entire object. You can easily have a method disposing the other fields which otherwise would have kept occupying the precious memory for no real purpose. This approach is quite useful in case you are using a third-party finalizable class.


In case you are writing the class yourself then you may break the class into two class - one having the code which really require finalization (i.e., the code which uses native or other non-memory resources) and the other class which simply uses the former class as a member and other non-finalizable members. Now you only need to make the former class finalizable and not the latter.


The bottom line is that don't make any class finalizable unless you have a very good reason behind it and in case you need to make then also make sure that the finalization process doesn't really cause unnecessary memory-renetion.


Is finalization guaranteed? What's the actual contract?


No... it's not guaranteed that the finalization of all the finalizable objects will happen before they are reclaimed so it obviously doesn't make sense to put any other code except the clean-up code inside the finalize() method. In fact finalizer is mainly used for having clean-up code for non-memory and native resources only.


The JVM doesn't guarantee the actual order in which the finalization of the finalizable objects will take place. All the finalizers either from the application or from the libraries are treated equally with no exception.


The JVM doesn't guarantee which thread will invoke the finalize() method of a particular object and only guarantees that the thread which will invoke the method will not have any user-visible synchronization lock at the time of finalize() invocation.


Grrr... so much of non-determinism involved. Yeah... unfortunately it's like this only. So think twice before making any class finalizable.


What if the finalize() method throws any Exception?


If an uncaught exception is thrown from within the finalize() method then it's simply ignored and the finalization of that object terminates immediately.


Any alternative to Finalization in Java?


One possible alternative is to use weak references instead of finalization. This will ensure that the programmer has a complete control over how to reclaim the resources, how to prioritize the reclaimation process (may be based on the availability of a particular native or non-memory resource), etc. We'll discuss about the weak references and about this approach in some other article.

How many ways of creating objects in Java?

Well... there aren't many different ways I suppose. But from an application programmer perspective here are the different possible ways of creating objects in Java:-

* Using new operator - the most commonly used way by far. 'new' is an operator and the only operand it requires is a constructor which will be used for initializting the newly created instance. 'new' operator allocates the memory space and initializes the fields with their default values. Then it executes the code inside the specified constrcutor which normally re-writes the default values of some (or all) fields with the particular values mentioned in the constructor definition.
* Using clone() method - Cloning (Shallow or Deep) makes a new copy of the specified object. It doesn't call the 'new' operator internally. Object.clone() is a native method which translates into instructions for allocating the memory and copying the data. Remember that even if we override the clone() method either to implement Deep Cloning or to make the clone() method as 'public' but then also we keep the line super.clone() inside the overriden definition which ultimately calls Object.clone() method only. You might wonder about what the 'new' operator actually translates into and how this approach is different from that. Okay... we all know that 'new' does three tasks - allocating the memory, initializing the fields with default values, and calling the specified constructor. Now the first task is same in both the approaches and there would probably be the same native allocator being used in both the cases. But in case of Cloning, the allocated memory is not initialized with default values and also no constructor is called in this case. Only a datacopy instruction will be executed which copies the data from the original object to the cloned object. Read more about Cloing in this article - Cloning in Java >>
* Using De-Serialization - this can be thought of another different way of creating an object in Java. Again you might wonder that this internally uses 'new' operator only so why to consider this as a new way. Yeah... you're right. It does uses the 'new' operator internally and always calls the default constructor. But two noticeable differences between the two approaches are:- In case of an explict 'new' call we may specify any constructor which is not the case here. It'll always invoke the default constructor. Another difference is that in this case the newly created object is initialized (or better to say re-written as the implicit 'new' call with default constructor would have already initialized the object first with the default value and then with the specified value in the default constructor) with the data from the Input Stream fetched usually from a persistent medium. This step is obviously not involved in an explicit 'new' call.
* Using Class.forName() and newInstance() - A calss can be dynamically loaded using the Class.formName() method. This method has two variants - one which accepts only a String type parameter which is the qualifies name of the class to be loaded and the other variant expects three parameters - the String type qualifies class name, boolean type flag to specify if the class should be initialized, and the ClassLoader name which should be used to load the class. The former variant also internally calls the three-parameter variant only by assuming the boolean flag as 'true' and the ClassLoader as returned by the getClassLoader() method. That means 'Class.forName("qualified.ClassName")' is internally translated into 'Class.forName("qualifies.ClassName", true, this.getClass().getClassLoader())'. Once the class has been loaded then a call of the method newInstance() on the loaded Class object will first check if the Class object is initialized or not and if not then it will initialize the Class object and create a new object as if the 'new' operator has been called with the default constructor of the class under consideration. Again you may argue how is this different from an explicit 'new' call and it won't take much of an effort to identify the most obvious difference between the two as the inability of this approach to call any other constructor except the default constructor. Another difference is that the newInstance() call may throw a SecurityException as well because it checks if a Security Manager is installed or not and if it finds a security manager then it checks for access to the class as wellas to the package (if any package specified in the qualified name). Either of two checks may throw a SecurityException. This step is obviously not involved with an explicit 'new' call. Another slightly different way of object creation is by using the loadClass() method of the ClassLoader class which returns a Class object of the specified class and then on the returned Class object we may call newInstance() method to create a new object. I've not put this as a completely separate way because I think Class.forName() method also internally calls this method only - either for the explcitly supplied ClassLoader or for the implcitily obtained ClassLoader as discussed above. What's the difference between the two approaches then? The only difference which I can see is that the former checks for the access to the class (and package) and hence it may throw SecurityException if a Security Manager is installed. But the latter doesn't do these checks and hence doesn't throw SecurityException. It's normally advised not to call the loadClass() method directly as almost always you can call Class.forName() by supplying the particular ClassLoader reference.

Is there any other different way of creating objects in Java? I don't think that there is any other way. Using JNI may pop up as another possible way, but I don't think that JNI offers any different way of object creation due to the fact that JNI is not meant for object creation instead it's used for interacting with native methods written in some other languages (mainly in C/C++) and hence a Java class using JNI code is same as any other Java from object creation perspective. Therefore, I think it uses any one of the above mentioned approaches only - most commnonly the explicit 'new' calls. I personally don't have much exposure to JNI and I sincerely welcome comments from the JNI experts if they think otherwise.

Structural Design Patterns - Adapter, Decorator, Composite, etc.

Structural Design Patterns

Design Patterns belonging to this category are used to combine classes and objects to form larger structures to suit your requirements. How do we actually achieve this? Class based structural design patterns use Inheritance to form larger structures whereas Object based structural design patterns use Composition for the same. The most popular structural design patterns are The Adapter Design Pattern, The Decorator Design Pattern, The Bridge Design Pattern, The Composite Design Pattern, The Proxy Design Pattern, The Facade Design Pattern, and The Flyweight Design Pattern.

We'll see Adapter, Decorator, and Composite Design Patterns in this article and discuss the other structural design patterns in subsequent articles. In this article we'll also see how the three design patterns (which look to be very similar) - Adapter, Decorator, and Composite differ from each other.

Adapter Design Pattern

As the name might suggest this design pattern is used where an unrelated class having a different interface is required to accept calls to the methods which are actually part of some other class having a different interface. How to do it? Well... there are the same two ways which we discussed above - using Interfaces and Composition. Suppose we have two classes A and B where we would like to have an instance of the type A to accept calls to the methods of class B then using inheritance we can derive a sub-class (say C) from A and add those methods of Class B into the new sub-class C so that they can be called on an instance of class C which will of course be of type A. Using composition we can simply have a new class which will have the original non-compliant class as a member and we'll add the required methods in this new class to internally call the corresponding methods of the non-compliant member class.

Example: Adapter Using Inheritance

class A{

public void methodA(int a){
...
}

...

}

class B{

public void methodB(){
...
}

...

}

class C extends class A{

public void methodB(){

...

int intValue = 5; //compute the actual int value

methodA(intValue);

}

...

}

Example: Adapter Using Composition

class A{

public void methodA(int a){
...
}

...

}

class B{

public void methodB(){
...
}

...

}

class C{

private A objectRefA;
...

public void methodB(){

int intValue = 5; //compute the actual int value

objectRefA.methodA(intValue);

}

...

}

Decorator Design Pattern

This design pattern is used to decorate the behavior of individual objects of a class without having to create a new derived class. It's normally used in UI design. Suppose there is a requirement where some of the instances of an UI component need a differnt look and feel (maybe based on the section of the screen they appear at or due to any other possible reason) then in such a case creating those many position-based derived classes of that UI component doesn't seem to be a good idea. Instead we can have a Decorator class having the basic look and feel and from it we can derive classed which will render those specific position-based look and feel. This will make the UI design more flexible by separating the actual UI component with its position-dependent look-n-feel. The same UI component can be used for all its occurrences with the corresponding decorator classes. Here the decorator classes will contain the actual UI component as a member and apply the area/position based look-n-feel logic on the contained instance(s).

class UIComp1{
...
}

class Decorator{

//...basic decoration of components
...

}

class DecoratorUIComp1Header extends Decorator{

//...Header specific decoration for UIComp1
...

}


Composite Design Pattern

This design pattern is used to make a composite of several primitive or composite member objects to have a common class which can accept calls intended to a variety of specialized objects (or cases). The composite children are normally termed as nodes and the primitives are called leaves. Example: suppose we need a common method which returns the specialized technical skills of an employee and all of its reportees (if the employee has any) then the Employee class may have a data structure (say a Vector) to store all the reportees which will themselves be instances of the Employee class only. Now we can have a common method getExpertise which will club the skills of the Employee which those of the reportees (if any) and return the clubbed data.

class Employee{

...
private String skill;
private Vector reportees;
...

public String getExpertise(){

String expertise = skill;

for(int i = 0; i < reportees.length; ++i)
expertise += ((Employee)reportees.elementAt(i)).getExpertise();

return expertise;
}

...

}

How do Adapters, Decorators and Composites differ?

Adapters may seem to decorate, but they are primarily used for enabling a class to accept calls belonging to a different interface. We have already sen above how inheritance and composition can be used to achieve this.

Decorators are not used to add different methods to all the instances instead they are used to add specific behavior to some specific instances. Though Adapters making use of composition may also be used here, but the intention is different here with what it's in case of a Adapter.

As discussed above, Composites are mainly used to provide a single interface to multiple instances which internally may have different structures depending on the values of the composed members in each of these instances. In the example discussed above we see that every Employee instance will invoke the same method 'getExpertise()' irespective of whether the instance represents a Employee having no reportees or the one who is having reportees (each of these reportees may themselves have their own reportees).

What are Design Patterns?

Design Patterns are basically a catalog of common interactions between objects. These interactions have been found, tested/tried, and optimized by skilled programmers to help others in solving some of their very common programming problems in an efficient way. Design Patterns simply illustrate how objects can communicate with each other without being much concerned about their individual data models and methods. This clear separation helps building robust and scalable design solutions to various programming problems. If you've already made this separation in your code (which is highly possible in Object Oriented Dev) then you're already using some of the widely used Design Patterns.


There are various formal definitions of Design Patterns and almost all of them convey the same message. Find below one such popular definition given by Gamma, et al., 1993.


“Patterns identify and specify abstractions that are above the level of single classes and instances, or of components.”


What are Communication Patterns?


Design Patterns do discuss design of objects as well, but what makes them even more important is that they describe an elegant and efficient methods of communication between the involved objects and this is the reason why Design Patterns are also referred to as Communication Patterns.


How many Design Patterns are currently available?


There is no fixed answer to this question. The original Design Patterns book included 23 design patterns and these are the most widely used patterns having several known applications using them. But, we currently have hundreds of Design Patterns documented/presented in some form or the other and many of them have already gained a good popularity. There are few which are suitable only for some very specific problems and hence not so popular. These Design Patterns are applicable at many levels ranging from very low level specific problems to general system-wide problems. Understanding of these Design Patterns may become extremely beneficial in designing solutions as they have been found/tested/tried by experts and it's highly unlikely that most of us will come up with a better design on the fly.


Types of Design Patterns


The authors of the original Design Pattern book deivided the 23 patterns into three categories based on what actually the patterns do in a design solution. These categories are:-

* Creational - the design patterns belonging to these category are used for creating objects. Using such a design pattern provides more flexibility where we require a control over the creation of objects. One very common use case is the usage of a creational design pattern to restrict the total number of instances of a class. Example: The Singleton Pattern, The Abstract Factory Method Pattern, etc.
* Structural - as the name suggests this category groups all those design patterns which help the user to group objects into larger structures to meet the complex requirements in a structured way. A common use case is to use such a design pattern for designing a complex user interface. Example: The Adapter Pattern, The Proxy Pattern, etc.
* Behavioral - the patterns belonging to this category are used to define communication between objects of a proposed solution. In other words such design patterns helps defining the flow of a complex system. Example: The Chain of Responsibility Pattern, The Strategy Pattern, The Iterator Pattern, etc.


What do Design Patterns suggest for Object Oriented programming?


The goal of Design Patterns (as discussed in the first section of the article) is to maintain a clear separation between classes so that they need to know (and hence depend) very little on each other. Object Oriented Programming has two popular mechanisms of enforcing separation which are: Inheritance and Encapsulation. Based on these two separation mechanisms Design Patterns suggest two important precepts which are:-


Programs should be based on Interface and NOT on implementation - If you're using inheritance then you may have unnecessary access to other methods/members of the base class and you may keep carrying all that extra load throughout the inheritance chain and this may subsequently cause many undesirable issues especially when the inheritance chain the underlying system becomes large and complex. You can avoid such a potential issue by having an abstract class at the top of the hierarchy and having the specific implementation in the corresponding sub classes only.


Composition should be preferred over Inheritance - does it seem contrary to the customs of Object Oriented Programming Methodology? Well... it isn't actually. Interitance may cause some undesirable side-effects in certain cases whereas Composition is usually (or probably always) pretty safe to use without worrying about any possible side-effects even when the classes evolve to newer versions which may not be the same in case of Inheritance.

Creational Design Patterns

As the name suggests these design patterns are used to control the instantiation of a class. Why do we need it? Because the program should not be dependent on how an user of the class instantiates it. The supplier of the class should take the responsibility of controlling the instantiation process in case it affects the execution of the program. For Example: if a class is supposed to have only one instance for it to work properly for an application then in such a case the supplier of the class needs to make the necessary arrangements that all the users of that cass get only the one shared instance. This is normally achieved by using the Singleton Design Pattern which we'll discuss next.


Few popular Creational Design Patterns


The Singleton Pattern - this design pattern is used to ensure that only one instance of the class is being used across the entire application. For example: you may like to use this design pattern to implement Cache of an application. How do we implement the singleton Design Pattern? The easiest way is to have a static variable storing the refence of the shared instance and keeping the constructor(s) private so that the users can't call the new operator to create instances. Such an implementation provides a static public method to the consumers to get the shared instance.


class SingletonImpl{
...
private static singletonInstance = null;
...
private SingletonImpl(){
...
}
public synchronized static getSingleton(){
if(singletonInstance == null) singletonInstance = new SingletonImpl();
return singletonInstance;}
...
}


The Factory Pattern - this design pattern is used to return an instance of one of several possible classes depending on what parameters are actually passed by the consumer. How do we implement this design pattern? We normally use inheritance to implement this. Suppose we have a base class named 'Base' and two chilldren of this base class named 'Child1' and 'Child2'. Now the Factory class which is the decision making body based on what the consumer provides decides whether to return an instance of the class 'Child1' or 'Child2'. We can easily set the return type of the method of the Factory (which is exposed to the consumers) as the Base Class type and then the method can easily return instances of either of the two children.


class BaseClass {
...
}
class Child1 extends BaseClass{
...
}
class Child2 extends BaseClass{
...
}
public class FactoryImpl{
...
public BaseClass getChild(String parameter){
...
if(parameter.equals("Child1")) //... sample cond impl

return new Child1();

else return new Child2();
}
...
}


The Abstract Factory Pattern - this design pattern is very similar to the Factory Pattern with the only difference that it takes the abstraction to another level higher. This pattern is basically used to return one of several related classes of objects i.e., one of several Factories (which in turn return the actual instance based on the passed parameter as explained above). One common example of this design pattern is to implement user interfaces. Suppose you're building an UI for three platforms - Windows, Mac, and Linux. Now you can use Abstract Factory pattern to return each of the Factories (Windows, Mac, and Linux) which will themselves return one of the various UI Components based on the passed parameter.


public abstract class UI{
public abstract UIComponent getButton(int, int, int, int);

...
}
public class UIComponent{
private int x1;private int y1;private int x2;private int y2;
public UIComponent(int x1, int y1, int x2, int y2){...}
}
public class Button extends UIComponent{...}

...
public class WindowsUI extends UI{...}
public class UIFactory {
private UI ui;
public UI getUI(String type){
if(type.equals("Win")) ui = new WindowsUI();

...

return ui;

}
}


This is just a sample implementation to help you understand how actually we make use of the Abstract Factory Pattern. The actual UI implmenetation will of course be quite different.

Finding the name of a Class in Java from within a static method

One of the many possible ways of finding the name of the class in Java from within a static method is by using a static nested class, which will have a public instance method returning the class name of the enclosing class (in our case the class where we have the particular static method).


public class GetClassNameInStaticMethod {

public static void main(String[] args) {
// Calling a Static Method
System.out.println("Current Class Name: " + getCurClassName());
}
public static String getCurClassName(){
return (new CurClassNameGetter()).getClassName();
}

//Static Nested Class doing the trick
public static class CurClassNameGetter extends SecurityManager{
public String getClassName(){
return getClassContext()[1].getName();
}
}
}


Output


Current Class Name: GetClassNameInStaticMethod

Tricky-use-of-static-initializer-in Java - Override println

Can we get a different output without changing the main-method definition?


public class HelloMain {

/**
* @param args
*/
public static void main(String[] args) {
System.out.println("Mr. main.");
}

}


Can we have the output of the above code-segment as "Hi, Mr. main. Bye!" without changing the main-method code?

Yeah, we can have the required output by using 'static initializer' blocks effectively. As we know that a static initializer block is called when a class is loaded into memory and hence it'll obviously run before the main method. Let's see how this can be used here.

The required output can be broken into three pieces - "Hi, ", "Mr. main.", and " Bye!". These parts should get printed in this order only which means the string "Hi, " should be printed before the 'println' call inside the main method prints "Mr. main." and subsequently the last string " Bye!" should be printed.

As we know that 'println' method by default ends with a new line and hence to have the last part (" Bye!") being printed in continuation with the main-method println string, we probably have only two ways:-

1. Re-define the default 'println' behavior - we can create an anonymous subclass (as we would not be requiring that anywhere else) of the PrintStream class and then re-define the 'println' method as per our needs.
2. Changing the default line separator - we can use the third part " Bye!" as the new line separator (it can be passed as a command-line argument while calling the class) in which case the 'println' of the 'main' would print this as the line separator and we will end up getting the required output.

Solution #1: Overriding 'println' in a static initializer block in Java


import java.io.PrintStream;

public class HelloMain
{

static
{
// as we are using System.out as the output stream in main
final PrintStream currentOut = System.out;

// anonymous as we would need this sub class here only
PrintStream newOut = new PrintStream(currentOut)
{
// Overriding 'println' method
public void println(String string)
{

// Printing Part - 1 first
print("Hi, ");

//Printing Part -2
print(string);

// Printing Part - 3, but this should use original 'println' def
// and hence the usage of 'super' comes here.
super.println(" Bye!");
}
};

// Now we are ready with the modified PrintStream and hence setting that

System.setOut(newOut);

}

/**
* @param args
*/
public static void main(String[] args) {
System.out.println("Mr. main.");
}
}


Output: below is the screenshot displaying the output of Solution #1
Hi, ", "Mr. main. Bye!

Solution #2: using an appropriate 'line separator' with a static initializer block


public class HelloMain {

static
{
//Printing Part - 1
System.out.print("Hi, ");
}

/**
* @param args
*/
public static void main(String[] args) {
System.out.println("Mr. main."); //Printing Part - 2
}
}


Part - 3 is printed by changing the default line separator, which is done by setting the string " Bye!" as the new line separator using command line arguments.


java -Dline.separator=" Bye!" HelloMain


Output: below is the screenshot displaying the output of Solution #2

Hi, ", "Mr. main. Bye!

Static Initialization Blocks and their alternatives in Java

Why do we need Static Initialization Blocks?

The easiest way of initializing fields (static or instance) in Java at the time of their declaration is simply by providing a compile time constant value of a compatible data type. For example:


public class InitializationWithConstants{

public static int staticIntField = 100;
private boolean instanceBoolField = true;

}


This type of initialization has its limitation due to its simplicity and it can not support initialization based even on some moderately complex logic - like initializing only selected elements of a complex array using some logic in a for loop.

Here comes the need for static initialization blocks and initializer blocks for initializing static and instance fields, respectively.

Static Initialization Blocks - what are they and how to use them?

It's a normal block of code enclosed within a pair of braces and preceded by a 'static' keyword. These blocks can be anywhere in the class definition where we can have a field or a method. The Java runtime guarantees that all the static initialization blocks are called in the order in which they appear in the source code and this happens while loading of the class in the memory.


public class InitializationWithStaticInitBlock{

public static int staticIntField;
private boolean instanceBoolField = true;

static{
//compute the value of an int variable 'x'
staticIntField = x;
}
}


Since static initialization blocks are actually code-blocks so they will allow us to initialize even those static fields which require some logical processing to be done for them to get their initial values.

Alternative to Static Initialization Blocks

A private static method is a suitable alternative to the static initialization blocks. In fact it has some advantages over static initialization blocks as well like you can re-use a private static method to re-initialize a static field in case you need it. So, you kind of get more flexibility with a private static method in comparison to the corresponding static initialization block. This should not mislead that a 'public' static method can't do the same. But, we are talking about a way of initializing a class variable and there is hardly any reason to make such a method 'public'.


public class InitializationWithPrivateStaticMethod{

public static int staticIntField = privStatMeth();
private boolean instanceBoolField = true;

private static int privStatMeth() {
//compute the value of an int variable 'x'
return x;
}
}

Nested Classes in Java

A nested class is a class defined inside the definition (body) of another enclosing class. A nested class can be of two types - static or non-static. A nested class is treated as a member of the enclosing class. A static nested class is not very tightly integrated with the enclosing class and it lives its own independent life as well i.e., a static nested class can be instantiated like any other class from just about anywhere. They are defined inside the definition of an enclosing class just to get a logical grouping of the classes, which in turn increases readability and provides better packaging convenience.

A static nested class can't directly access the members of the enclosing class. Like any other top-level class it needs to access the members of the enclosing class via object references only.

Example: a static nested class

class EnclosingClass{
...
...
static class StaticNestedClass{
//...definition of the static nested class
...
...
}
...
...
}

A static nested class is accessed using the enclosing class name as follows:

EnclosingClass.StaticNestedClass staticNestedObjectRef = new EnclosingClass.StaticNestedClass();

Inner Classes in Java

A non-static nested class is called an inner class and it's tightly integrated with the enclosing class unlike a static nested class. An inner class instance can't exist independent to the enclosing class instance. An inner class instance always exist within the instance of the enclosing class. Since, it's always associated with the enclosing class instance and it has direct access to all the members of the enclosing class - even the private members.

Example: an inner class

class EnclosingClass
{
...
...
class InnerClass{
//...definition of the inner class
...
...
}
...
...
}

Since, an instance of an inner class always exists within an instance of the enclosing class, hence we must instantiate the enclosing class first and then on that instance we can instantiate the inner class:-

EnclosingClass enclosingObjectRef = new EnclosingClass();
EnclosingClass.InnerClass innerObjectRef = enclosingObjectRef.new InnerClass();

Can an Inner Class declare static members?

No. Because any instance of an inner class is always associated with an instance of the enclosing class.

Can we have private or protected access for classes in Java?

Yeah... but only for nested classes and not for top-level classes. Nested classes are treated as members of the enclosing classes and hence we can specify any of the four access specifiers - private, package, protected, or public. We don't have this luxury with top-level classes - they can only be declared public or package.

How to choose a suitable access control specifier of a method or a field?

Access Control Modifiers available for classes and members in Java

Top-level classes in Java can have only two access control modifiers - public and default (package-private) whereas the members have four access control modifiers - public, protected, default (package-private), and private. Nested Classes are treated as members of the top-level classes so all four access control modifiers are applicable to them.

Choosing suitable access control modifier for methods in Java?

Here I'm assuming that your top-level (i.e., a class which is not nested) class is 'public' as otherwise if it's having the default access control modifier then you would probably never make any member public or protected owning to the fact the class itself can't be used outside the package.

When to pick 'public' as the access control modifier?

How do you normally go about choosing the access specifier/modifier of a method in your class definition - whether you start from 'public' and move on to 'private' to see which specifier would actually suit the requirements or do you go about the other way round? It probably makes more sense to go the other way - starting from 'private' and moving onto 'public'. There should be a very strong reason why you would need a method to make 'public' as it would then become a part of the public interface of the class - a commitment from the class designer to all (those who are already consuming or those who would be consuming in future).

Therefore, choosing 'public' as the access specifier should be given a thorough review as consumers of the class can (which they normally do) use them in their implementation and hence once you make something public you got to support that for the consumers of your class till eternity (making a 'public' member deprecated and subsequently getting rid of it will be a difficult and time consuming exercise). A big ask especially in a professional environment where your class is being consumed by many critical applications. So as a thumb rule make only those members 'public', which you can't make either 'private', 'package-private (default)' or 'protected'.

When to pick 'protected' as the access control specifier?

A 'protected' modifier specifies that the member can be accessed from within the same package as well as by a sub-class in some other package.

Let's pick the suitable access modifier for a member which you want any of your sub-classes to have access to. Of course you can't choose 'private' here as the access will then be limited to your class only. Next up the ladder is 'package-private (default)' which will restrict the access limited to all the classes (either a sub class or not) in the same package only. But, if you want any sub class of your class to access the member then the default access modifier won't do it for you. Next up the ladder is 'protected' which suits fine here so no need to go further up. Quite simple to pick the suitable access modifier, isn't it?

Making something 'protected' also puts you in some sort of commitment in case you are not making your class as 'final' as otherwise the sub-classes of your class may write their implementation based on the availability of your 'protected' member. You have to be careful with the fact that the 'protected' members can be used by any class in the same package, so even if you have made your class as 'final' the commitment to make the 'protected' members available to all the classes in the same package still remains. But, why would you come up with such a design? If you want the member to be accessible only from within the same package, better make it package-private (default). Making a class 'final' which is having 'protected' members would certainly draw attention as to why would anyone like to do it. You would better need to review the class design in such a case.

When to pick default access control modifier?

'package-private' or the default access control modifier puts you under only one commitment. This is towards all the classes in the same package as they will have access to all your package-private members and hence they can have their implementation dependent on those members.

When to pick 'private' access control modifier?

'private' is something private to your class and hence you have no commitment towards others. You can change them anytime you want as long as it doesn't hurt the functioning of any public/protected/default member.

How to pick access control modifier for fields in Java?

For fields, the thumb rule is quite simple - make all instance fields 'private' and have getters/setters to access/modify them. However, you would probably like to make most of your static fields as 'public' as they are class variables and meant to be accessed from outside either on the class name (preferred way) or on any instance.

Initializer Blocks in Java and their possible alternatives

Initializer Blocks - what are they, why & how are they used?

These blocks are similar to the static initialization blocks with the only difference being the absence of the 'static' keyword. The Java compiler copies all the initializer blocks in the same order as they are in the source code in every constructor before any executable statement in that constructor.


public class InitializationWithInitializerBlock{

public static int staticIntField = 100;
private boolean instanceBoolField;

{
boolean y;

y = true; //or, y = ;

instanceBoolField = y;
}
}


So if you see all your constructors having same code-segment at the top then you will probably be better off keeping that in an initializer block as anyway the compiler would copy the block in every constructor at the top. This way you can at least make the code more readable, maintainable (as the common code will only be at one place), and if the size of common code is significant and if you have multiple constructors then using initializer block you can also reduce the size of your source code.


public class InitializerBlocks {

public static void main(String[] args) {
new InitializerBlocks();
}
//Constructor - 1
public InitializerBlocks(){
System.out.println("3");
}
//Initializer Block - 1
{
System.out.println("1");
}
//Initializer Block - 2
{
System.out.println("2");
}
}

Output

1
2
3

(Of course the above code is not making a good use of initializer blocks as they not initializing anything what they are actually meant to. The purpose here is just to show how a Java compiler places all the initializer blocks at the top in every constructor in the same order as they appear in the code.)

Alternative to Initializer Blocks in Java

You can use an instance method to initialize an instance field - in most of the cases you would like to make this instance method as 'final' as there will hardly be any need for the subclasses to override such a method (evidently, a non-final instance method would also do the job). Similarly if you need to call the method only from within the same class, you would probably make it 'private'.


public class InitializationWithPrivateInstanceMethod{

public static int staticIntField = 100;
private boolean instanceBoolField = privInstanceMeth();

private final boolean privInstanceMeth() {
boolean y;
//computing the value of y
y = ;
return y;
}
}


The advantage of using an instance method over an initializer block is that it gives you flexibility of re-initializing those instance fields by calling the corresponding final instance method(s) in some setter or in some other method. Another interesting scenario where you can't use an initializer block and you would probably need an instance method to do it for you: Suppose you have a need of using the code of initializer block in any of your sub-classes and suppose all your constructors have extra code as well in addition to the initializer block code which would be added to them on the top during compilation. Now in such a situation, if you need to set only those fields which are set in the initializer block then you can't do that directly in your subclass as the most you can do here is to call a super class constructor (that too would normally re-set all the instance fields) ... right? Having a final instance method would solve your problem here. Choosing a suitable access specifier will again follow the same rules what has been discussed in article mentioned in above paragraph. In this case since the sub-classes require access to that method, so choosing 'protected' as the access specifier should be fine.

Choosing the Most Specific Method - Tricky Method Overloading

Let's start with looking at a code-segment and try to think of the output/error, it would produce when compiled/executed and subsequently we'll discuss the behavior of code.


public class NullTest {

public static void method(Object obj){
System.out.println("method with param type - Object");
}

public static void method(String obj){
System.out.println("method with param type - String");
}

public static void main(String [] args){
method(null);
}
}


So, what do you expect as the output here? Before thinking about the output, do you really expect the code to compile successfully? Well... yeah, the code will compile and run fine as opposed to anyone who might have sensed an ambiguity here - we'll see the reason soon.

Since the methods are overloaded, the resolution will be done at compile-time only. Which method do you see being bind here - the one with parameter type 'Object' or the one with parameter type 'String' and why? Of course, the compiler can't bind two methods with one call, so on what basis would it pick the most suitable? Which method would be picked, is evident from the output given below:-


method with param type - String


Any guesses for why a special treatment is being given to 'String' here? Well... it's not actually for 'String' class specifically, but any sub-class would get a preference over the super class in such a situation. But, why? Because JLS (Section: 15.12.2.5) allows this. It clearly says:

"If more than one member method is both accessible and applicable to a method invocation, it is necessary to choose one to provide the descriptor for the run-time method dispatch. The Java programming language uses the rule that the most specific method is chosen."

As you easily deduce that the compiler should be able to pick 'the most specific', failing which it will throw a compile-time error. Let's understand it with the below code-segment which doesn't compile because the compiler can't pick 'the most specific' here.


public class NullTest {

public static void method(Object obj){
System.out.println("method with param type - Object");
}

public static void method(String str){
System.out.println("method with param type - String");
}

public static void method(StringBuffer strBuf){
System.out.println("method with param type - StringBuffer");
}

public static void main(String [] args){
method(null); //... compile-time error!
}
}


Why is the compiler not able to pick 'the most specific' here - because both String and StringBuffer are are sub-classes of the Object class, but without being in the same inheritance hierarchy. For finding 'the most specific' method, the compiler needs to find a method having the parameter type, which is a sub-class of the parameter types of all other overloaded methods.

This holds true for overloaded methods having more than one parameters as well. The compiler would pick 'the most specific' by looking which method is having at least one of its parameter types as a clear sub-class of the corresponding parameter type and other parameter types being either the same or clear sub-classes, in all other overloaded methods. If it can find one, good, otherwise it will throw a compile-time error. For example:


public class NullTest {

public static void method(Object obj, Object obj1){
System.out.println("method with param types - Object, Object");
}

public static void method(String str, Object obj){
System.out.println("method with param types - String, Object");
}

public static void main(String [] args){
method(null, null);
}
}

Output

method with param types - String, Object


In this case the compiler can easily pick 'the most specific' as the method having parameter types (String, Object) as the other overloaded method is having its parameter types as (Object, Object) - clearly 'String' is a subclass of 'Object' and the other parameter is of same type, so the method with parameter types (String, Object) can be picked with ease. But, the below code would throw a compile-time error as none of the methods satisfy the condition for being picked as 'the most specific' method.


public class NullTest {

public static void method(Object obj, String obj1){
System.out.println("method with param types - Object, String");
}

public static void method(String str, Object str1){
System.out.println("method with param types - String, Object");
}

public static void main(String [] args){
method(null, null); //... compile-time error!
}
}

Why wait(), notify() and notifyAll() methods have been defined in the Object class?

Java concurrency model uses locks to implement mutually exclusive access to objects in a multi-threaded environment and locks are associated with every object in Java (of type 'Object'), not only with Threads.

wait, notify/notifyAll methods are used by threads to communicate with each other while trying to access a common object. Putting it differently, objects become a medium via which threads communicate with each other. For example: suppose there is a 'telephone' object, which at one point of time can be used by only one thread. Like every other object in Java, 'telephone' object would also have an intrinsic lock (monitor) associated with it which at one point of time can be acquired by only one thread. Suppose the 'telephone' object requires activation before it can be used and suppose only a few admin threads can activate the 'telephone' object.

As soon as a thread needs access to the 'telephone' object, it checks if the lock on that 'telephone' object is available or not, if yes, it acquires that and checks if the 'telephone' is active or not. If yes, it starts using it otherwise it calls 'wait()' on the telephone object which effectively releases the monitor of the 'telephone' object (eventually to be acquired by one of the admin threads for its activation) and puts the requester thread into the wait-set of the 'telephone' object. The requester thread goes into WAITING state. The way every object in Java has an intrinsic lock associated with it, it has an intrinsic wait-set associated with it as well.

Every other non-admin requester thread goes through the same process as discussed above till one of the admin threads acquire lock on the 'telephone' object and eventually activates it and subsequently calls 'notify()' or 'notifyAll()' on the 'telephone' object. 'notify()' will simply pick one of the threads from the wait-set of the 'telephone' object (which one will be picked is an implementation dependent stuff and Java Language specification doesn't enforce any restriction on which one to be picked) and the chosen thread will now get out of WAITING mode and start trying to acquire the monitor/lock of the 'telephone' object along with any other thread that might be vying to access the 'telephone' at that point of time.

The only difference between 'notify' and 'notifyAll' is that in case of the latter all the threads of the corresponding wait-set are picked and they all start trying to acquire the lock on the object (with any other incoming requester thread) at the same time.

Evidently you see that these three methods are essentially object-related and not thread-related and hence the designers of Java Language considered it wise to put them in the Object class instead of putting them into the Thread class. The usage of the 'object' (in our case 'telephone') is the particular object's prerogative and not that of the requester threads'. Putting these three methods in the Object class helps the objects owning/controlling their usage in a better way as in that case a thread needs to first acquire the lock on the object (kind of getting a license to use the object) and then calling either wait (in case the thread doesn't find the object in the state it would have wished it to be in and hence thought of waiting for some time to let the object become useful for it) or notify/notifyAll to alert other threads waiting on the object once it finishes using the object (of course in the case when the thread find the object useful in its current state).

Additionally, the communication among the interested threads becomes far too easier when the control is kept at the object's level - one common shared resource/medium and all interested threads communicating via it. Not that the communication won't be possible if these methods are kept in the Thread class, but the handling of the communication and usage of the objects in a multi-threaded environment will probably become more complex and less flexible in that case.

Annotations in Java

These are pieces of code which don't have any direct impact on the execution of the code, instead they provide additional data about the program (and not a part of the program) to either the compiler or the run-time system. This data is used by the compiler or the run time system to do a variety of things - generation of additional code, XML files, suppress warnings, errors, etc. Annotations are sometimes preferred on comments as they make the documentation of a program quite flexible. We can even define annotation types, the way we define classes. This encourages code re-usability and makes the code more readable and maintainable. Annotations can be applied to every element of a Java program including classes, fields, methods, code blocks, etc. For generation of auxiliary code, XML files, etc., We may write annotation processors, which will read annotations specified in a Java program and they will take corresponding actions based on the specified annotation values. Most of the annotations are processed atthe compile time only, but we may make annotation information available to the run time system if we want.

JDK 5.0 uses a tool called 'apt' for annotation processing whereas JDK 6.0 this feature is in-built in the Java Compiler itself.

Example: Sample Annotations in Java

@Author(
Name = "Geek"
Date = "6/16/2008")
class ClassA{
...

@SuppressWarnings("unchecked")
public int methodName(){
...
}
...

@Override
public void overridenMethod(){
...
}

}

Notice that an annotation may have named or unnamed elements and in case there are no elements, we may skip the parentheses as well.

Uses of Annotations in Java

* Providing information to the Compiler - an annotation used for conveying some information to the compiler may help the compiler to either suppress warnings, detect errors, etc. Example of such annotations are: @SuppressWarnings(value = "some value"), @Override, @Deprecated
* Providing information to the tools - an annotation used for this purpose may help various software tools to generate code, XML files, etc.
* Providing inforamtion to the Runtime System - certain annotations convey information to the run time system to either guide the direction of the execution or to just notify something. Annotation information is made available to the run time system by using another annotation type called '@Retention(RetentionPolicy.RUNTINE)'. We just need to precede the annotation which we want to make available at run time by this annotation.


Specification-defined Annotation Types

There are three annotation types, which have been defined by the Java Language Specification. These are:- @Deprecared, @Override, @SuppressWarnings. It's quite obvious to understand what these annotation types are used for.

Annotations in Java

These are pieces of code which don't have any direct impact on the execution of the code, instead they provide additional data about the program (and not a part of the program) to either the compiler or the run-time system. This data is used by the compiler or the run time system to do a variety of things - generation of additional code, XML files, suppress warnings, errors, etc. Annotations are sometimes preferred on comments as they make the documentation of a program quite flexible. We can even define annotation types, the way we define classes. This encourages code re-usability and makes the code more readable and maintainable. Annotations can be applied to every element of a Java program including classes, fields, methods, code blocks, etc. For generation of auxiliary code, XML files, etc., We may write annotation processors, which will read annotations specified in a Java program and they will take corresponding actions based on the specified annotation values. Most of the annotations are processed atthe compile time only, but we may make annotation information available to the run time system if we want.


JDK 5.0 uses a tool called 'apt' for annotation processing whereas JDK 6.0 this feature is in-built in the Java Compiler itself.

Example: Sample Annotations in Java

@Author(
Name = "Geek"
Date = "6/16/2008")
class ClassA{
...

@SuppressWarnings("unchecked")
public int methodName(){
...
}
...

@Override
public void overridenMethod(){
...
}

}

Notice that an annotation may have named or unnamed elements and in case there are no elements, we may skip the parentheses as well.

Uses of Annotations in Java

  • Providing information to the Compiler - an annotation used for conveying some information to the compiler may help the compiler to either suppress warnings, detect errors, etc. Example of such annotations are: @SuppressWarnings(value = "some value"), @Override, @Deprecated
  • Providing information to the tools - an annotation used for this purpose may help various software tools to generate code, XML files, etc.
  • Providing inforamtion to the Runtime System - certain annotations convey information to the run time system to either guide the direction of the execution or to just notify something. Annotation information is made available to the run time system by using another annotation type called '@Retention(RetentionPolicy.RUNTINE)'. We just need to precede the annotation which we want to make available at run time by this annotation.

Specification-defined Annotation Types

There are three annotation types, which have been defined by the Java Language Specification. These are:- @Deprecared, @Override, @SuppressWarnings. It's quite obvious to understand what these annotation types are used for

What are Marker Interfaces in Java?

An empty interface having no methods or fields/constants is called a marker interface or a tag interface. This of course means if the interface is extending other interfaces (directly or indirectly) then the super interfaces must not have any inheritable member (method or field/constant) as otherwise the definition of the marker interface (an entirely empty interface) would not be met. Since members of any interface are by default 'public' so all members will be inheritable and hence we can say for an interface to be a marker interface, all of its direct or indirect super interfaces should also be marker.

There are few Java supplied marker interfaces like Cloneable, Serializable, etc. One can create their own marker interfaces the same way as they create any other interface in Java.

Purpose of having marker interfaces in Java i.e., why to have marker interfaces?

The main purpose to have marker interfaces is to create special types in those cases where the types themselves have no behavior particular to them. If there is no behavior then why to have an interface? Because the implementor of the class might only need to flag that it belongs to that particular type and everything else is handled/done by some other unit - either internal to Java (as in the case of Java supplied standard marker interfaces) or an app specific external unit.

Let's understand this by two examples - one in which we will discuss the purpose of a standard Java interface (Cloneable) and then another user-created marker interface.

What purpose does the Cloneable interface serve?

When JVM sees a clone() method being invoked on an object, it first verifies if the underlying class has implemented the 'Cloneable' interface or not. If not, then it throws the exception CloneNotSupportedException. Assuming the underlying class has implemented the 'Cloneable' interface, JVM does some internal work (maybe by calling some method) to facilitate the cloning operation. Cloneable is a marker interface and having no behavior declared in it for the implementing class to define because the behavior is to be supported by JVM and not the implementing classes (maybe because it's too tricky, generic, or low-level at the implementing class level). So, effectively marker interfaces kind of send out a signal to the corresponding external/internal entity (JVM in case of Cloneable) for them to arrange for the necessary functionality.

How does JVM support the 'cloning' functionality - probably by using a native method call as cloning mechanism involves some low-level tasks which are probably not possible with using a direct Java method. So, a possible 'Object.clone' implementation would be something like this:-


public Object clone() throws CloneNotSupportedException {

if (this implements Cloneable)

return nativeCloneImpl();

else

throw new CloneNotSupportedException();

}


Anyone wondered as to why and when do we get 'CloneNotSupportedException' exception at compile-time itself? Well... that's no trick. If you see the signature of the 'Object.clone()' method carefully, you will see a throws clause associated with it. I'm sure how can you get rid of it: (i) by wrapping the clone-invocation code within appropriate try-catch (ii) throwing the CloneNotSupportedException from the calling method.

What purpose does a user-defined marker interface serve? It can well serve the same purpose as by any standard marker interface, but in that case the container (the module controlling the execution of the app) has to take the onus of making sure that whenever a class implements that interface it does the required work to support the underlying behavior - the way JVM does for Cloneable or any other standard marker interface for that matter.

Defining an user-defined marker interface in Java


Let's define a user-defined marker interface. Let's say there is an app suporting a medical store inventory and suppose you need a reporting showing the sale, revenue, profit, etc. of three types of medicines - allopathic, homeopathic, and ayurvedic separately. Now all you need is to define three marker interfaces and make your products (medicines) implement the corresponding ones.


public interface Allopathic{}
public interface Homeopathic{}
public interface Ayurvedic{}


In your reporting modules, you can probably get the segregation using something similar to below:-


for (Medicine medicine : allMedicines) {
if (medicine instanceof Allopathic) {
//... update stats accordingly
}
else if (medicine instanceof Homeopathic) {
//... update stats accordingly
}
else if (medicine instanceof Ayurvedic) {
//... update stats accordingly
}
else {
//... handle stats for general items
}
}


As you can see the medicines themselves don't need to implement any specific behavior based on whether they are allopathic, homeopathic, or ayurvedic. All they need is to have a way of reflecting which category they belong to, which will in turn help the reporting modules to prepare the stats accordingly.

Now this can be done by having a flag as well... yeah, sure it can be. But, don't you think tagging a class makes it more readable than having a flag indicating the same. You kind of make it an implementation-independent stuff for the consumers of your classes. If your class implements an interface, it becomes part of the class signature of the published API. Otherwise, you would probably handle the situation by having a public final field having the flag set up at the time of instantiation - final because you would not like others to change it. I guess going the marker interface way would probably make more sense in many such situations.

Another advantage of going via marker interface way is that at any point of time you can easily cast the objects of the implementing classes. Again it's not that if you go via public final approach, you can't do that. You can very well do, but casting might look a cleaner approach in many situations.

The bottom-line is there will hardly be any enforced need for a designer/developer to go via that way as there can be possible alternatives, but marker interfaces can surely be a preferred choice for some in some cases.