Multi Threading Java Interview Questions – Set 05

What method is invoked to cause an object to begin executing as a separate thread?

The start() method of the Thread class is invoked to cause an object to begin executing as a separate thread.

Why do threads block on I/O?

Threads block on I/O (that is enters the waiting state) so that other threads may execute while the I/O Operation is performed.

What are applets ?

Applets are small applications that are accessed from web server automatically installed, and run from the browser. Once an applet arrives on the client it has limited access to resources thus ensuring security for the end user. An applet is controlled by the software that runs it. Usually, the underlying software is a browser, but it can also be applet viewer. If you run the applet source code from eclipse it runs inside an applet viewer. All applets should inherit from applet class.

Below are sequences of events which occur in applet:

  • The init Method: The init method is called when the applet is first loaded. Init method can be used to initialize color, fonts or any type of one type operation needed for the applet.
  • The start Method: The start method is called when user visits a browser with an applet on it. In start method applet spawns a thread in which it runs the paint method.
  • paint() is called every time when applet has to re-display everything.

What is the difference between process and thread?-

Process is a program in execution whereas thread is a separate path of execution in a program

What are some of the best practices relating to the Java Collection framework

Best practices relating to Java Collection framework are as follow:

  • Choose the right type of data structure based on usage patterns like fixed size or required to grow, duplicates allowed or not, ordering is required to be maintained or not, traversal is forward only or bi-directional, inserts at the end only or any arbitrary position, more inserts or more reads, concurrently accessed or not, modification is allowed or not, homogeneous or heterogeneous collection, etc. Also, keep multi-threading, atomicity, memory usage and performance considerations discussed earlier in mind.
  • Don’t assume that your collection is always going to be small as it can potentially grow bigger with time. So your collection should scale well.
  • Program in terms of interface not implementation: For example, you might decide a LinkedList is the best choice for some application, but then later decide ArrayList might be a better choice for performance reason.
    • Bad:
      • ArrayList list = new ArrayList(100);
    • Good:

// program to interface so that the implementation can change

  • List list = new ArrayList(100);
  • List list2 = new LinkedList(100);
  • Return zero length collections or arrays as opposed to returning a null in the context of the fetched list is actually empty. Returning a null instead of a zero length collection is more error prone, since the programmer writing the calling method might forget to handle a return value of null.
    • List emptyList = Collections.emptyList( );
    • Set emptySet = Collections.emptySet( );
  • Use generics for type safety, readability, and robustness.
  • Encapsulate collections: In general, collections are not immutable objects. So care should be taken not to unintentionally expose the collection fields to the caller. The caller may not perform any necessary validation.

Where will you use Vector and where will you use ArrayList

The basic difference between a Vector and an ArrayList is that, vector is synchronized while ArrayList is not. Thus whenever there is a possibility of multiple threads accessing the same instance, one should use Vector. While if not multiple threads are going to access the same instance then use ArrayList. Non synchronized data structure will give better performance than the synchronized one.

Difference between Vector and ArrayList? What is the Vector classDifference between Vector and ArrayList? What is the Vector class

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. Both the classes are member of Java collection framework, therefore from an API perspective, these two classes are very similar. However, there are still some major differences between the two. Below are some key differences

  • Vector is a legacy class which has been retrofitted to implement the List interface since Java 2 platform v1.2

Vector is synchronized whereas ArrayList is not. Even though Vector class is synchronized, still when you want programs to run in multithreading There are multiple aspects to this decision:

  • The basic difference between a Hashtable and an HashMap is that, Hashtable is synchronized while HashMap is not. Thus whenever there is a possibility of multiple threads accessing the same instance, one should use Hashtable. While if not multiple threads are going to access the same instance then use HashMap. Non synchronized data structure will give better performance than the synchronized one.
  • If there is a possibility in future that – there can be a scenario when you may require to retain the order of objects in the Collection with key-value pair then HashMap can be a good choice. As one of HashMap’s subclasses is LinkedHashMap, so in the event that you’d want predictable iteration order (which is insertion order by default), you can easily swap out the HashMap for a LinkedHashMap. This wouldn’t be as easy if you were using Hashtable. Also if you have multiple thread accessing you HashMap then Collections.synchronizedMap() method can be leveraged. Overall HashMap gives you more flexibility in termsenvironment using ArrayList with Collections.synchronizedList() is recommended over Vector.
  • ArrayList has no default size while vector has a default size of 10.
  • The Enumerations returned by Vector’s elements method are not fail-fast. Whereas ArraayList does not have any method returning Enumerations.

What is difference between Iterator and Enumeration

Both Iterator and Enumeration are used to traverse Collection objects, in a sequential fashion. Enumeration can be applied to Vector and HashTable. Iterator can be used with most of the Collection objects. The main difference between the two is that Iterator is fail-safe. i.e,  If you are using an iterator to go through a collection you can be sure of no concurrent modifications in the underlying collection which may happen in multi-threaded environments.

What is the difference between a HashMap and a Hashtable in Java

  • Hashtableis synchronized, whereas HashMap is not. This makes HashMap better for non-threaded applications, as unsynchronized Objects typically perform better than synchronized ones.
  • Hashtabledoes not allow null keys or values. HashMap allows one null key and any number of null values.

One of HashMap’s subclasses is LinkedHashMap, so in the event that you’d want predictable iteration order (which is insertion order by default), you could easily swap out the HashMap for aLinkedHashMap. This wouldn’t be as easy if you were using Hashtable

How will you go about creating a memory leak in Java

In Java, memory leaks are possible under a number of scenarios. Here is a typical example where hashCode( ) and equals( ) methods are not implemented for the Key class that is used to store key/value pairs in a HashMap.

This will end up creating a large number of duplicate objects. All memory leaks in Java end up with java.lang.OutOfMemoryError, and it is a matter of time. The following code agressively creates the OutOfMemoryError via an endless loop for demonstration purpose.

If you are not familiar with the significance of equals( ) and hashCode ( ) methods in Java, then learn with this example how to define proper key class in Java.

import java.util.HashMap;

import java.util.Map;

public class MemoryLeak {

public static void main(String[] args) {

Map<Key, String> map = new HashMap<Key, String>(1000);

int counter = 0;

while (true) {       // creates duplicate objects due to bad Key class

map.put(new Key(“dummyKey”), “value”);

counter++;

if (counter % 1000 == 0) {

System.out.println(“map size: ” + map.size());

System.out.println(“Free memory after count ” + counter + ” is ” + getFreeMemory() + “MB”);

sleep(1000);

}

}

}

// inner class key without hashcode() or equals() — bad implementation

static class Key {

private String key;

public Key(String key) {

this.key = key;

}

}

//delay for a given period in milli seconds

public static void sleep(long sleepFor) {

try {

Thread.sleep(sleepFor);

} catch (InterruptedException e) {

e.printStackTrace();

}

}

//get available memory in MB

public static long getFreeMemory() {

return Runtime.getRuntime().freeMemory() / (1024 * 1024);

}

}

If you run the above code, you will get the ouput as shown below

map size: 1000

Free memory after count 1000 is 4MB

map size: 2000

Free memory after count 2000 is 4MB

map size: 1396000

Free memory after count 1396000 is 2MB

map size: 1397000

Free memory after count 1397000 is 2MB

map size: 1398000

Free memory after count 1398000 is 2MB

map size: 1399000

Free memory after count 1399000 is 1MB

map size: 1400000

Free memory after count 1400000 is 1MB

map size: 1401000

Free memory after count 1401000 is 1MB

…..

…..

map size: 1452000

Free memory after count 1452000 is 0MB

map size: 1453000

Free memory after count 1453000 is 0MB

Exception in thread “main” java.lang.OutOfMemoryError: Java heap space

 at java.util.HashMap.addEntry(HashMap.java:753)

 at java.util.HashMap.put(HashMap.java:385)

 at MemoryLeak.main(MemoryLeak.java:10)

As you could see, the size of the map keeps growing with the same objects and the available memory keeps coming down from 4MB to 0MB. At the end, the program dies with an OutOfMemoryError.