Popular Posts

Friday, June 24, 2011

Java FAQ's

Q : What is type erasure in Java?
http://blog.adaptivesoftware.biz/2009/02/what-is-type-erasure-in-java.html


volatile
    Used in field declarations to specify that the variable is modified asynchronously by concurrently running threads. Methods, classes and interfaces thus cannot be declared volatile.

interface
    Used to declare a special type of class that only contains abstract methods, constant (static final) fields and static interfaces. It can later be implemented by classes that declare the interface with the implements keyword.

instanceof
    A binary operator that takes an object reference as its first operand and a class or interface as its second operand and produces a boolean result. The instanceof operator evaluates to true if and only if the runtime type of the object is assignment compatible with the class or interface.

Shallow Copy and Deep Copy :
  http://javapapers.com/core-java/java-clone-shallow-copy-and-deep-copy/
http://www.java-questions.com/Cloning_interview_questions.html
http://www.javaworld.com/javaworld/javatips/jw-javatip76.html?page=1

Difference b/w getClass and instanceof operators :

There are two substantially different ways of performing the check for type match in an implementation of equals() . A class can allow mixed-type comparison between super- and subclass objects by means of the instanceof operator, or a class can treat objects of different type as non-equal by means of the getClass() test. The examples above illustrated nicely that implementations of equals() using getClass() are generally more robust than those implementations using instanceof .

The instanceof test is correct only for final classes or if at least method equals() is final in a superclass. The latter essentially implies that no subclass must extend the superclass's state, but can only add functionality or fields that are irrelevant for the object's state and behavior, such as transient or static fields.

Implementations using the getClass() test on the other hand always comply to the equals() contract; they are correct and robust. They are, however, semantically very different from implementations that use the instanceof test. Implementations using getClass() do not allow comparison of sub- with superclass objects, not even when the subclass does not add any fields and would not even want to override equals() . Such a "trivial" class extension would for instance be the addition of a debug-print method in a subclass defined for exactly this "trivial" purpose. If the superclass prohibits mixed-type comparison via the getClass() check, then the trivial extension would not be comparable to its superclass. Whether or not this is a problem fully depends on the semantics of the class and the purpose of the extension.

getClass() == o.getClass() will be true only if both objects ( this and o ) belongs to exactly the same class.


Comparable vs Comparator : 
First, you say class is Comparable so for me it indicates that this class is self-comparable, or it is able-to-compare-it-self to some other object. It is self compared to or as it's method says compareTo(Object o).
Second, you say class is Comparator because it is comparing objects of other class. So what it do is to, as it's method says, compare(Object o1, Object o2). Remember that Comparator itself is not compared to anything, it just compare(...)-s two objects of some other class.
Comparable --> able-to-compares-itself compareTo(Object o)
Comparator --> compares two other objects compare(Object o1, Object o2)

-second Comparable is in lang package because it is kinda natural that classes have such a behavior by themselfs and lang package doesn't have to be imported(this is my opinion don't take it as something generally known), and Comparator is in util cause it is kinda part of everyday work which includes Collections Framework that are in the same package... 





Forcing garbage collection : 

Java runtime system performs the garbage collection asynchronously depending on the available resources. When there are no more references to an object, the object is finalized and when the Garbage Collections starts these finalized objects gets collected.
            Sometimes you need to run garbage collector explicitly just before some memory intensive task. You can run garbage collector by this statement.
   System.gc(); 
         Finalization process can also be invoked explicitly using the following statement. After the execution of this statement all the objects those are without reference, are finalized.
   System.runFinalization();



Runtime r = Runtime.getRuntime();
r.gc();
There is no guarantee that it will be invoked immediately


Why is the finalize() method in java.lang.Object “protected”?
Refer : http://stackoverflow.com/questions/2291470/why-is-the-finalize-method-in-java-lang-object-protected

Finalize :

Objects with finalizers (those that have a non-trivial finalize() method) have significant overhead compared to objects without finalizers, and should be used sparingly. Finalizeable objects are both slower to allocate and slower to collect. At allocation time, the JVM must register any finalizeable objects with the garbage collector, and (at least in the HotSpot JVM implementation) finalizeable objects must follow a slower allocation path than most other objects. Similarly, finalizeable objects are slower to collect, too. It takes at least two garbage collection cycles (in the best case) before a finalizeable object can be reclaimed, and the garbage collector has to do extra work to invoke the finalizer. The result is more time spent allocating and collecting objects and more pressure on the garbage collector, because the memory used by unreachable finalizeable objects is retained longer. Combine that with the fact that finalizers are not guaranteed to run in any predictable timeframe, or even at all, and you can see that there are relatively few situations for which finalization is the right tool to use.
If you must use finalizers, there are a few guidelines you can follow that will help contain the damage. Limit the number of finalizeable objects, which will minimize the number of objects that have to incur the allocation and collection costs of finalization. Organize your classes so that finalizeable objects hold no other data, which will minimize the amount of memory tied up in finalizeable objects after they become unreachable, as there can be a long delay before they are actually reclaimed. In particular, beware when extending finalizeable classes from standard libraries.


Fail-Fast behavior : The iterators of the Collection implementations of the Java runtime throw a ConcurrentModificationException when they detect that another thread has modified the Collection while a thread is iterating over it. Such iterators are generally called fail-fast iterators
Refer : http://java.dzone.com/articles/do-your-iterators-always-fail
Example : http://stackoverflow.com/questions/4479554/why-vector-methods-iterator-and-listiterator-are-fail-fast

CopyOnWriteArrayList : A thread-safe variant of ArrayList in which all mutative operations (addset, and so on) are implemented by making a fresh copy of the underlying array.
http://download.oracle.com/javase/6/docs/api/java/util/concurrent/CopyOnWriteArrayList.html

Iterator in the HashMap is fail-fast while the enumerator for the Hashtable isn't. So this could be a design consideration.

Good collection questions are here : http://www.fromdev.com/2008/05/java-collections-questions.html
Multi threading questions : http://www.fromdev.com/2008/05/java-threading-questions.html


Thread Local :This class provides thread-local variables. These variables differ from their normal counterparts in that each thread that accesses one (via itsget or set method) has its own, independently initialized copy of the variable. ThreadLocal instances are typically private static fields in classes that wish to associate state with a thread (e.g., a user ID or Transaction ID).

No comments:

Post a Comment