Multi Threading Java Interview Questions – Set 06

What can prevent the execution of the code in finally block ? and what are the rules for catching multiple exceptions?

The death of thread

– Use of system.exit()

– Turning off the power to CPU

– An exception arising in the finally block itself

Rules for catching multiple exceptions

– A more specific catch block must precede a more general one in the source, else it

gives compilation error

– Only one catch block, that is first applicable one, will be executed

What does synchronized means in Hashtable context

Synchronized means only one thread can modify a hash table at one point of time. Any thread before performing an update on a hashtable will have to acquire a lock on the object while others will wait for lock to be released

Why Java Vector class is considered obsolete or unofficially deprecated? or Why should I always use ArrayList over Vector

You should use ArrayList over Vector because you should default to non-synchronized access. Vector synchronizes each individual method. That’s almost never what you want to do. Generally you want to synchronize a whole sequence of operations. Synchronizing individual operations is both less safe (if you iterate over a Vector, for instance, you still need to take out a lock to avoid anyone else changing the collection at the same time) but also slower (why take out a lock repeatedly when once will be enough)? Of course, it also has the overhead of locking even when you don’t need to. It’s a very flawed approach to have synchronized access as default. You can always decorate a collection using Collections.synchronizedList – the fact that Vector combines both the “resized array” collection implementation with the “synchronize every operation” bit is another example of poor design; the decoration approach gives cleaner separation of concerns. Vector also has a few legacy methods around enumeration and element retrieval which are different than the List interface, and developers (especially those who learned Java before 1.2) can tend to use them if they are in the code. Although Enumerations are faster, they don’t check if the collection was modified during iteration, which can cause issues, and given that Vector might be chosen for its syncronization – with the attendant access from multiple threads, this makes it a particularly pernicious problem. Usage of these methods also couples a lot of code to Vector, such that it won’t be easy to replace it with a different List implementation. Despite all above reasons Sun may never officially deprecate Vector class.

What is fail-fast property

At high level – Fail-fast is a property of a system or software with respect to its response to failures. A fail-fast system is designed to immediately report any failure or condition that is likely to lead to failure. Fail-fast systems are usually designed to stop normal operation rather than attempt to continue a possibly-flawed process. When a problem occurs, a fail-fast system fails immediately and visibly. Failing fast is a non-intuitive technique: “failing immediately and visibly” sounds like it would make your software more fragile, but it actually makes it more robust. Bugs are easier to find and fix, so fewer go into production. In Java, Fail-fast term can be related to context of iterators. If an iterator has been created on a collection object and some other thread tries to modify the collection object “structurally”, a concurrent modification exception will be thrown. It is possible for other threads though to invoke “set” method since it doesn’t modify the collection “structurally”. However, if prior to calling “set”, the collection has been modified structurally, “IllegalArgumentException” will be thrown.

What is synchronized modifier used for

It is used to control access of critical code in multithreaded programs

Why doesn’t Collection extend Cloneable and Serializable

From Sun FAQ Page: Many Collection implementations (including all of the ones provided by the JDK) will have a public clone method, but it would be mistake to require it of all Collections. 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. If the client doesn’t know the actual type of a Collection, it’s much more flexible and less error prone to have the client decide what type of Collection is desired, create an empty Collection of this type, and use the addAll method to copy the elements of the original collection into the new one. Note on Some Important Terms

  • Synchronized means only one thread can modify a hash table at one point of time. Basically, it means that any thread before performing an update on a hashtable will have to acquire a lock on the object while others will wait for lock to be released.

Fail-fast is relevant from the context of iterators. If an iterator has been created on a collection object and some other thread tries to modify the collection object “structurally”, a concurrent modification exception will be thrown. It is possible for other threads though to invoke “set” method since it doesn’t modify the collection “structurally”. However, if prior to calling “set”, the collection has been modified structurally, “IllegalArgumentException” will be thrown

Difference between Vector and ArrayList

Vector & ArrayList both classes are implemented using dynamically resizable arrays, providing fast random access and fast traversal. ArrayList and Vector class both implement the List interface.

  • Synchronization – ArrayList is not thread-safe whereas Vector is thread-safe. In Vector class each method like add(), get(int i) is surrounded with a synchronized block and thus making Vector class thread-safe.
  • Data growth – Internally, both the ArrayList and Vector hold onto their contents using an Array. When an element is inserted into an ArrayList or a Vector, the object will need to expand its internal array if it runs out of room. A Vector defaults to doubling the size of its array, while the ArrayList increases its array size by 50 percent.

How to Add A Jar File To Java System Classpath At Run-time

This can be done by using a simple reflection API hack as demonstrated in below sample code. This example assumes you have a file “c:/Sample.txt” that is not already in class path and at run-time c:/ is added the System classpath and then Sample.txt is made available.

import java.io.File;

import java.io.InputStream;

import java.lang.reflect.Method;

import java.net.URL;

import java.net.URLClassLoader;

public class HackJavaClasspath {

public static void addURL(URL url) throws Exception {

URLClassLoader cl = (URLClassLoader) ClassLoader

.getSystemClassLoader();

Class clazz = URLClassLoader.class;

Method method = clazz.getDeclaredMethod(“addURL”,

new Class[] { URL.class });

method.setAccessible(true);

method.invoke(cl, new Object[] { url });

}

public static void main(String[] args) throws Exception {

//Add c: to the classpath

addURL(new File(“c:/”).toURI().toURL());

//Now load the file from new location

InputStream in = Thread.currentThread().getContextClassLoader()

.getResourceAsStream(“Sample.txt”);

System.out.println(in.available());

}

}

Running this java class prints the number of bytes available. This indicates the file is available for further processing.

How to Make a Map or List as Thread-Safe or Synchronized Collection

Collections.synchronizedMap(new HashMap());

Collections.synchronizedList(List<T> list)

What is a deadlock

Deadlock is a situation where two or more threads are blocked forever, waiting for each other. This may occur when two threads, each having a lock on one resource, attempt to acquire a lock on the other’s resource. Each thread would wait indefinitely for the other to release the lock, unless one of the user processes is terminated. In terms of Java API, thread deadlock can occur in following conditions:

  • When two threads call Thread.join() on each other.
  • When two threads use nested synchronized blocks to lock two objects and the blocks lock the same objects in different order.