Java Interview Questions : Series 10


 

200. What is

CopyOnWriteArrayList? How it is

different from ArrayList in Java?

CopyOnWriteArrayList was introduced in Java 5 version. It is a

thread-safe collection. It is similar to an ArrayList.

In CopyOnWriteArrayList, all mutative operations (add, set etc.)

are implemented by making a fresh copy of the underlying array.

Iterator of CopyOnWriteArrayList is guaranteed to not throw

ConcurrentModificationException. But Iterator also does not reflect

any additions, removals that happened to list after the Iterator was

created.

All elements including null are permitted in CopyOnWriteArrayList.


201. How remove() method is

implemented in a HashMap?

Remove() method in HashMap uses logic similar to the one used in

get() method. First we locate the correct bucket in HashMap for an

entry. Then within that bucket we remove the element e. It is similar

to removing a node from a single-linked list.

If e is the first element in the bucket we set the corresponding

element of Hash to e.next. Else we set the next field of the element

just before e to e.next.


202. What is BlockingQueue in

Java Collections?

BlockingQueue was introduced in Java 1.5. It extends Queue

interface in Java.

BlockingQueue supports operations that wait for the queue to

become non-empty when retrieving an element. Also it supports the

operations that wait for space to become available in the queue

while storing an element.

Some of the features of BlockingQueue are:

It does not accept null elements.

Its main use is in producer-consumer problems.

BlockingQueue implementation is thread-safe.

It can be used in inter-thread communications.

It does not support any kind of "close" or "shutdown"

operation to indicate that no more items will be added.


203. How is TreeMap class

implemented in Java?

Internally, a TreeMap class in Java uses Red-Black tree.

It is a NavigableMap. The map sorts the keys in natural order or it

can use a Comparator supplied at the creation time.

The implementation of TreeMap is not synchronized in Java.


204. What is the difference between

Fail-fast and Fail-safe iterator in

Java?

Differences between Fail-fast and Fail-safe iterators are as

follows:

Fail-fast iterator throws ConcurrentModificationException. But

Fail-safe iterator does not throw this exception.

Fail-fast iterator does not clone the original collection. Fail-safe

iterator creates a copy of the original collection of objects.

A Fail-fast iterator tries to immediately throw Exception when it

encounters failure. A Fail-safe Iterator works on a copy of

collection instead of original collection.


205. How does

ConcurrentHashMap work in Java?

ConcurrentHashMap extends AbstractMap in Java. It was

introduced in Java 1.5. It provides concurrency in a collection

based on a HashMap.

All methods are thread-safe in ConcurrentHashMap.

Internally there is a Hashtable backing a ConcurrentHashMap. This

Hashtable supports the concurrent methods for retrieval of data as

well as updates on ConcurrentHashMap.

It has same functional specification as a Hashtable.

It also supports a set of sequential and bulk operations. These

operations accept parallelismThreshold argument.


206. What is the importance of

hashCode() and equals() methods?

In a HashMap collection it is very important for a key object to

implement hashCode() method and equals() method. If hashCode()

method returns same hashcode for all key objects then the hash

collision will be high in HashMap. Also with same hashcode, we

will get same equals method that will make our HashMap

inefficient.

The problem arises when HashMap treats both outputs same instead

of different. It will overwrite the most recent key-value pair with

the previous key-value pair.

So it is important to implement hashCode() and equals() methods

correctly for an efficient HashMap collection.


207. What is the contract of

hashCode() and equals() methods in

Java?

Contract of hashCode() and equals() methods is as follows in Java:

If object1.equals(object2), then object1.hashCode() ==

object2.hashCode() should always be true. It means if two objects

are equal then their hashCode should be same.

If object1.hashCode() == object2.hashCode() is true, it does not

guarantee that object1.equals(object2). It means if two objects have

same hashCode, then can still have different values so that may not

be equal objects.


208. What is an EnumSet in Java?

Set: EnumSet is a specialized implementation of Set.

1. Use: It is mainly used with enum types.

2. Single enum type: All the elements in an EnumSet must

come from a single enum type when the set is created.

3. Bit vector: Internally, EnumSet is represented as bit

vector.

4. Iterator: The iterator of EnumSet traverses the elements in

their natural order. (It is the order in which the enum

constants are declared).

5. Null: In an EnumSet, null elements are not permitted. If we

try to insert a null element it throws NullPointerException.

6. Thread-safe: EnumSet is not a synchronized collection.

For use in multi-threading scenarios, EnumSet should be

synchronized.

7. Bit flags: EnumSet is a very good alternative to int based

“bit flags” implementation.


209. What are the main Concurrent

Collection classes in Java?

Java 1.5 has provided new package java.util.concurrent. This

package contains thread-safe collection classed. These collection

classes can be modified while iterating. The iterator of these

classes is fail-safe.

Main Concurrent Collection classes in Java 8 are:

ArrayBlockingQueue

CopyOnWriteArrayList

CopyOnWriteArraySet

ConcurrentHashMap

ConcurrentLinkedDeque

ConcurrentLinkedQueue

LinkedBlockingQueue

LinkedBlockingDeque

PriorityBlockingQueue


210. How will you convert a Collection

to SynchronizedCollection in Java?

Java provides an easy method in java.utils.Collections class to

create a ThreadSafe collection from a regular collection.

We can use the method synchronizedCollection() for this purpose.

For any class of type T we can use following method:

static <T> Collection<T> synchronizedCollection(Collection<T> c)


211. How IdentityHashMap is

different from a regular Map in Java?

IndentityHashMap in Java implements Map interface. But it is not a

general purpose implementation. It violates the general contract of

Map interface by a different implementation of equals() method.

In an IdentityHashMap, two keys k1 and k2 are equal if and only if

(k1==k2). (In a normal Map implementation (like HashMap) two

keys k1 and k2 are considered equal if and only if (k1==null ?

k2==null : k1.equals(k2)).)

It implements the Map interface with a hash table, using referenceequality

in place of object-equality when comparing keys (and

values).


212. What is the main use of

IdentityHashMap?

Main uses of IdentityHashMap are:

1. Topology Preservation: The typical use of

IdentityHashMap class is topology-preserving object

graph transformations, such as serialization or deepcopying.

In such a scenario, a program must maintain a

"node table" to keep track of all the object references that

have already been processed.

2. The node table should not considered distinct objects as

equal even if they happen to be equal.

3. Proxy objects: Another use of this class is to maintain

proxy objects. A debugging program has to maintain a

proxy object for each object in the program being

debugged.


213. How can we improve the

performance of IdentityHashMap?

IdentityHashMap class has one tuning parameter for performance

improvement: expectedMaxSize.

This parameter is the maximum number of key-value mappings that

the map is expected to hold.

We can use this parameter is used to determine the number of

buckets initially in the hash table. The precise relationship between

the expected maximum size and the number of buckets is

unspecified.

If the number of key-value mappings exceeds the expected maximum

size, the number of buckets is increased.

Increasing the number of buckets is also known as rehashing.

Rehashing may be fairly expensive. So it is better to create identity

hash maps with a sufficiently large expected maximum size.

But iteration over a Map collection requires time proportional to

the number of buckets in the hash table. So iteration may take extra

time due to large number of buckets.

Therefore the value of expectedMaxSize should be set in

consideration with both of these aspects.


214. Is IdentityHashMap threadsafe?

The implementation of IdentityHashMap is not thread-safe, since its

methods are not synchronized.

The iterators returned by the iterator method of IdentityHashMap

are fail-fast. But the fail-fast behavior of an iterator cannot be

guaranteed.

Since the Iterator is fail-fast, it throws

ConcurrentModificationException.


215. What is a WeakHashMap in

Java?

WeakHashMap is a class similar to IdentityHashMap.

Internally, it is represented by a Hashtable.

It is not a synchronized class. We can make a WeakHashMap thread

safe by using Collections.synchronizedMap() method.

An entry in WeakHashMap is automatically removed when it is no

longer in ordinary use.

The presence of a mapping for a given key does not prevent the key

from being discarded by the garbage collector.

WeakHashMap also permits null keys and null values.


216. How can you make a Collection

class read Only in Java?

In Java, there are useful methods to make a Collection class read

Only. We can make the Collection read Only by using one of the

following methods:

Collections.unmodifiableMap(Map m)

Collections.unmodifiableList(List l)

Collections.unmodifiableSet(Set s)

Collections.unmodifiableCollection(Collection c)


217. When is

UnsupportedOperationException

thrown in Java?

In a Java collection UnsupportedOperationException is thrown

when the requested operation is not supported by the collection.

It is an unchecked exception that is thrown on optional operations.

If there is an optional add() or remove() methods in a read only

collection, then this exception can be thrown.


218. Let say there is a Customer

class. We add objects of Customer

class to an ArrayList. How can we

sort the Customer objects in

ArrayList by using customer

firstName attribute of Customer

class?

There are two ways to handle this scenario. We can use these

options:

Comparable: Implement the Comparable interface for Customer

class and compare customer objects by firstName attribute.

Comparator: Implement Comparator for comparing two Customer

objects on the basis of firstName attribute. Then use this comparator

object in sort method of Collections class.


219. What is the difference between

Synchronized Collection and

Concurrent Collection?

In Java 1.5 many Concurrent collection classes were added in SDK.

These are ConcurrentHashMap, CopyOnWriteArrayList,

BlockingQueue etc.

Java also provides utility methods to get a synchronized copy of

collection like ArrayList, HashMap etc. by using

Collections.synchronizedList(), Collections.synchronizedMap()

methods.

The main difference is in performance. Concurrent collection

classes have better performance than synchronized collection

classes because they lock only a portion of the class to achieve

concurrency and thread-safety.


220. What is the scenario to use

ConcurrentHashMap in Java?

ConcurrentHashMap is more suited for scenarios where we have

multiple reader threads and one writer thread. In this case map is

locked only during the write operation.

If we have an equal number of reader and writer threads then

ConcurrentHashMap performance is similar to a Hashtable or a

synchronized HashMap.


Comments

Popular posts from this blog

3 Lines of Code And You Can Download Your Favourite Youtube Video.

Leetcode Problem(Easy) Roman to Integer

Leetcode : (Find Minimum in Rotated Sorted Array)