Friday, January 25, 2013

Java Serialization Questions

How Serialization works ?

Suppose following example.

C extends B extends A.

Case 1:

if Class A implements Serializable interface. B and C need not to do it explicitly. If I create an object of class C, serialize it and deserialize, all the attributes of A, B and C will be populated.

Because while de-serialization none of the class's constructor will be called.

If any of this class have an attribute of class which don't implement Serializable Interface, while serialization exception will be thrown.

Case 2:

A and C don't implements Serializable interface but B implements.

Now in this case all the attributes of B and C will be serialized and deserialized but A's attributes will not.

Only class A's Constructor will be called during deserialization.

Other than A, if any class have an attribute of class which don't implement Serializalbe interface exception will be thrown.

Case 3:

A and B don't implements Serializable interface only C implements.

Now in this case all the attributes of A and B will not be serialized and deserialized only C's attributes will.

Only class A's and B's Constructor will be called during deserialization.

Both than A and B can have an attribute of class which don't implement Serializalbe interface.
  

Summary: If super class implements Serializable interface, child class will inherit it. 
If superclass don't implements Serializable interface and chlid class does, and if you try to serialize object of child class, only child class's attributes will be serialized.
Super class's attributes will be ignored.



Q- Example of Extenalization


class Employee implements Externalizable {
      String name;
      double salary;
      int age;
      long cardNo;

      public void writeExternal(ObjectOutput out) throws IOException {
             out.writeUTF(name);
             out.writeInt(age);
             out.writeDouble(salary);

      }

      public void readExternal(ObjectInput in) throws IOException,
                    ClassNotFoundException {
             name = in.readUTF();
             age = in.readInt();
             salary = in.readDouble();

      }
}


For more questions Refer Click here

Java I/O Questions




ByteStrems
FileInputStream     - FileOutputStream
Chracter Stream
FileReader          - FileWriter  (Char by char access)
BufferedReader      - PrintWriter (pass FileWriter obj, and get line by line access)
DataStream
         DataInputStream     -      DataOutputStream
Object Stream
         ObjectInputStream   -      ObjectOutputStream.



Q- If the input is a stream of bytes. Why FileInputStream.read() method return int value instead of byte ?

Ans: Using a int as a return type allows read() to use -1 to indicate that it has reached the end of the stream.

Q- Diff between Buffered and UnBuffered I/O ?

UnBuffered : each read or write request is handled directly by the underlying OS. This can make a program much less efficient, since each such request often triggers disk access, network activity, or some other operation that is relatively expensive.

Buffered : Buffered input streams read data from a memory area known as a buffer; the native input API is called only when the buffer is empty. Similarly, buffered output streams write data to a buffer, and the native output API is called only when the buffer is full.

Q- What are the Buffered Stream classes used to wrap unbuffered streams ?
There are following four classes 

BufferedInputStream  -    BufferedOutputStream
BufferedReader       -    BufferedWriter

Q- What is purpose of Scanner class ?
Ans -  Scanner are useful for breaking down formatted input into tokens and translating individual tokens according to their data type.
By default, a scanner uses white space to separate tokens. (White space characters include blanks, tabs, and line terminators).
http://docs.oracle.com/javase/tutorial/essential/io/scanning.html

Q- What is purpose of Console class ?
Ans- Console class is an advanced alternative to Standard Streams. It provides most of the features provided by Standard Streams and others besides.
For ex. Console object supports secure password entry.
http://docs.oracle.com/javase/tutorial/essential/io/cl.html

Q- What are Data Streams ?
Data streams support binary I/O of primitive data type values (boolean, char, byte, short, int, long, float, and double) as well as String values. All data streams implement either the DataInput interface or the DataOutput interface.

it provide you methods like,
DataInputStream.readDouble - DataOutputStream.writeDouble
DataInputStream.readInt - DataOutputStream.writeInt

etc.

Q-  What are Object Streams ?
Just as data streams support I/O of primitive data types, object streams support I/O of objects. Most, but not all, standard classes support serialization of their objects. Those that do implement the marker interface Serializable.

The object stream classes are ObjectInputStream and ObjectOutputStream.
writeObject and readObject methods used to read and write objects.

Q- What is the difference between the Reader/Writer class hierarchy and the InputStream/OutputStream class hierarchy?
The Reader/Writer class hierarchy is character-oriented and the InputStream/OutputStream class hierarchy is byte-oriented.

Q- What's the difference between a file's path, absolute path, and canonical path?
Refer Here


Wednesday, January 23, 2013

Java Threading Questions

1. Diff between Green Thread and Native Thread ?

Green Thread is a thread machanism of JVM itself and Native thread is OS's thread machanism.

2. What is CountDownLatch in java concurrency ?
Ans: CountDownLatch

3. What is CyclicBarrier in java concurrency ?
Ans: CyclicBarrier  and  example 2


4. Diff between Lock, Intrinsic lock and Reentrant Sync ?


5. Executors vs Thread pool

6. Daemon Thread 

7. How we can get all active threads from Thread class ?
   




http://www.journaldev.com/1162/java-multi-threading-concurrency-interview-questions-with-answers


Java Threads Important points

A class invariant is a type of internal invariant that applies to every instance of a class at all times, except when an instance is in transition from one consistent state to another. A class invariant can specify the relationships among multiple attributes, and should be true before and after any method completes. For example, suppose you implement a balanced tree data structure of some sort. A class invariant might be that the tree is balanced and properly ordered.

A class is threadsafe if it behaves correctly when accessed from multiple threads, regardless of the scheduling or interleaving of the execution of those threads by the runtime environment

To avoid race conditions, there must be a way to prevent other threads from using a variable while we're in the middle of modifying it

CHECKTHENACT RACE CONDITION: you observe something to be true (file X doesn't exist) and then take action based on that observation (create X); but in fact the observation could have become invalid between the time you observed it and the time you acted on it (someone else created X in the meantime), causing a problem (unexpected exception, overwritten data, file corruption).

Every Java object can implicitly act as a lock for purposes of synchronization; these builtin locks are called intrinsic locks or monitor locks

When a thread requests a lock that is already held by another thread, the requesting thread blocks. But because intrinsic locks are reentrant, if a thread tries to acquire a lock that it already holds, the request succeeds. Reentrancy means that locks are acquired on a perthread rather than perinvocation basis.

For each mutable state variable that may be accessed by more than one thread, all accesses to that variable must be performed with the same lock held. In this case, we say that the variable is guarded by that lock. For every invariant that involves more than one variable, all the variables involved in that invariant must be guarded by the same lock .

Acquiring the lock associated with an object does not prevent other threads from accessing that object the only thing that acquiring a lock prevents any other thread from doing is acquiring that same lock

While synchronized methods can make individual operations atomic, additional locking is required when multiple operations are combined into a compound action.

Any access (get or set) to Global/state variables should be done within the synchronized methods or same lock.This will ensure the visibility of state variables across the threads i.e. To ensure that all threads see the most uptodate values of shared mutable variables, the reading and writing threads must synchronize on a common lock.

There is no guarantee that operations in one thread will be performed in the order given by the program, as long as the reordering is not detectable from within that thread even if the reordering is apparent to other threads.

When a field is declared volatile, the compiler and runtime are put on notice that this variable is shared and that operations on it should not be reordered with other memory operation


You can use volatile variables only when all the following criteria are met:

• Writes to the variable do not depend on its current value, or you can ensure that only a single thread  ever updates the value;

• The variable does not participate in invariants with other state variables; and

 • Locking is not required for any other reason while the variable is being accessed

Publishing an object means making it available to code outside of its current scope, such as by storing a reference to it where other code can find it, returning it from a nonprivate method, or passing it to a method in another class.

To publish an object safely, both the reference to the object and the object's state must be made visible to other threads at the same time. A properly constructed object can be safely published by:

 • Initializing an object reference from a static initializer;

• Storing a reference to it into a volatile field or AtomicReference;

• Storing a reference to it into a final field of a properly constructed object; or  • Storing a reference to it into a field that is properly guarded by a lock

The publication requirements for an object depend on its mutability:

 • Immutable objects can be published through any mechanism;

• Effectively immutable objects must be safely published; 

• Mutable objects must be safely published, and must be either threadsafe or guarded by a lock.

An object that is published when it should not have been is said to have escaped.

If data is only accessed from a single thread, no synchronization is needed. This technique, thread confinement, is one of the simplest ways to achieve thread safety

Stack confinement is a special case of thread confinement in which an object can only be reached through local variables

Immutable objects are always threadsafe. An object is immutable if:

Its state cannot be modified after construction;

• All its fields are final; and

 • It is properly constructed (the this reference does not escape during construction).

Race conditions in accessing or updating multiple related variables can be eliminated by using an immutable object to hold all the variables.  With a mutable holder object, you would have to use locking to ensure atomicity; with an immutable one, once a thread acquires a reference to it, it need never worry about another thread modifying its state. If the variables are to be updated, a new holder object is created, but any threads working with the previous holder still see it in a consistent state

The most useful policies for using and sharing objects in a concurrent program are: 

Thread-confined. A threadconfined object is owned exclusively by and confined to one thread, and can be modified by its owning thread.

Shared read-only. A shared readonly object can be accessed concurrently by multiple threads without additional synchronization, but cannot be modified by any thread. Shared readonly objects include immutable and effectively immutable objects.

Shared thread-safe. A threadsafe object performs synchronization internally, so multiple threads can freely access it through its public interface without further synchronization

Guarded. A guarded object can be accessed only with a specific lock held. Guarded objects include those that are encapsulated within other threadsafe objects and published objects that are known to be guarded by a specific lock.

When an object is encapsulated within another object, all code paths that have access to the encapsulated object are known and can be therefore be analyzed more easily than if that object were accessible to the entire program. Combining confinement with an appropriate locking discipline can ensure that otherwise nonthreadsafe objects are used in a threadsafe manner.

An object following the Java monitor pattern encapsulates all its mutable state and guards it with the object's own intrinsic lock. The Java monitor pattern is useful when building classes from scratch or composing classes out of objects that are not threadsafe.

The safest way to add a new atomic operation is to modify the original class to support the desired     operation, but this is not always possible because you may not have access to the source code or may not be free to modify it. 2. Another approach is to extend the class, assuming it was designed for extension. E.g:-BetterVector in extends Vector to add a putIfAbsent method





Friday, January 18, 2013

Java Collection Questions.




1.   Diff between Iterator and ListIterator ?
a. Iterator can only traverse forward, but ListIterator can traverse forward and backward both. 
b. Iterator can traverse both List and Set, but ListIterator can traverse only List.

2.  Diff between HashMap and HashTable ?
a.  HashTable is Sync, and HashMap is not.
b.  Iterator in the HashMap is fail-safe while the enumerator for the Hashtable isn't.
c.  difference is that HashMap permits null values in it, while Hashtable doesn't.

3.  What is fail fast property ?
Any Java collection which implements Iterable interface to loop through it create an iterator.

The iterator returned by this class's iterator method is named fail-fast if: the set is modified at any time after the iterator is created (except through the iterator's own remove method) the Iterator throws a ConcurrentModificationException.

So, in case of concurrent modification, the iterator fails quickly and cleanly, rather than risking arbitrary, non-deterministic behavior at an undetermined time in the future.

4.  Why doesn't Collection extend Cloneable and Serializable?
This is a design related questions. 
Many Collection implementations (including all of the ones provided by the JDK) will have a public clone method, but not for all. Because of giving a choice to developer to use appropriate collection. For example, what does it mean to clone a Collection that's backed by a terabyte SQL database? Should the method call cause the company to requisition a new disk farm? Similar arguments hold for serializable.


5.  How we can make HashMap sync ?
Collections.synchronizedMap

6.  Where to use HashTable over HashMap ?

a. When you want to run on Java 1.1 
b. When you want each operation to be synchronized (getting you a form of thread safety, so long as you never iterate over it) - and for some reason don't want to use Collections.synchronizedMap over a HashMap
c. When you don't want to be able to store null values


7.  Diff between Vector and ArrayList ?
a. Vector is Sync, ArrayList is not
b. Vector doubles the size of its array when its size is increased. But, ArrayList increases by half of its size when its size is increased.

8.  Diff between Enumeration and Iterator ?
Both are used to traverse Collections. Enumeration is old class present from JDK 1.0, and Iterator introduced later.

a. Iterator have one extra method remove().
b. Iterator are fail-safe and Enumeration is not.
9.  Why Java Vector class is considered obsolete or unofficially deprecated? 
it is preferred by most developers that ArrayList is used in preference to Vector, and that HashMap is used in preference to Hashtable.
The main reason developers have this preference is because of speed. When it comes to Sync, it can be achieved by Collections.synchronizedXXX methods.
http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6201870


10. What is the difference between Sorting performance of Arrays.sort() vs Collections.sort() ? Which one is faster? Which one to use and when?
On implementation point there is no differance, as they both use the same algo. But you should use Array.sort to sort Array, becuase it will directly work on Arrays.

11. What is the difference between ArrayList and LinkedList?
Basic diff is in data structure used for both.

a. ArrayList use index based data-structure, LinkedList use node based data structure.
b. Reterival is fast in ArrayList than Linked List.
c. Addition, updtation and removal of elements are fast in LinkedList.
d. LinkedList has more memory overhead than ArrayList because in ArrayList each index only holds actual object (data) but in case of 
   LinkedList each node holds both data and address of next  and previous node.

12. What is ConcurrentModificationException ?
Read answer or question 3.

13. Why Map doesn't extends Collection Interface ?
Because Maps are not truly collections, as collection means bundle of elements. But in case of Map we have key-pair values.
Now what you will consider as element ? key or value ?

This is the reason Map does not extends Collection Interface.

14. What is the Wrapper classes in collections ?
When we call Collections class static methods for getting Sync or immutable collections, it return wrapper classes(i.e with some extra functionality).


15. How to convert a collection to unmodifiable collection ?
By calling Collections.unmodifiableXXX methods.

16. How to sort list in natural reverse order?
Arrays.sort(a, Collections.reverseOrder());

17. What is WeakHashMap ?
Weak References are cleared aggressively by GC and Soft References are not. Using a Soft Reference tells the garbage collector that you would like it to keep the object around for a while, until memory considerations cause it to reclaim the object. By contrast, using a Weak References tells the garbage collector that there's no reason to keep the object around any longer than necessary.

Soft References are primarily for implementing memory sensitive caches. Weak References are primarily for associating extra information with an.

WeakHashMap is not for caching. The idea is, suppose you have a bunch of objects of a certain class that you can't extend, but you want to associate some other piece of information with each object. You can use a Map, with the main object as the key and the extra info as the value. Using a WeakHashMap for this will make sure that your Map won't cause a memory leak, because it won't hold a strong reference to the main (key) object; this will allow the object to be garbage collected when it's no longer needed. I believe that when the key is garbage collected, the value will soon be garbage collected too, though not immediately.


18. Diff between HashTable, Collections.synchronizedMap, ConcurrentHashMap ?
 HashTable is thread safe Collection. And Thread lock on complete collection. 
Collection.synchronizedMap is conditionaly thread safe implementation of Map.
ConcurrentHashMap only locked certain portion of Map while Hashtable lock full map while doing iteration

19. How HashMap works in Java

Refer how hash map works


20. What is identityHashMap?
Ans) The IdentityHashMap uses == for equality checking instead of equals(). This can be used for both performance reasons, if you know that two different elements will never be equals and for preventing spoofing, where an object tries to imitate another.

21. How Get method of HashMap works?

Refer How get method of hashmap works?