Choose.. X Home Exams Certifications
 

Java Concurrency Interview Questions

1 . What is Synchronized Methods ?

  • The Java programming language provides two basic synchronization idioms: synchronized methods and synchronized statements. To make a method synchronized, simply add the synchronized keyword to its declaration:
    public class SynchronizedCounter {
    private int c = 0;
    public synchronized void increment() {
    c++;
    }
    public void decrement() {
    synchronized(this){
    c--;
    }
    }
    public synchronized int value() {
    return c;
    }
    }

    If count is an instance of SynchronizedCounter, then making these methods synchronized has two effects:
    First, it is not possible for two invocations of synchronized methods on the same object to interleave. When one thread is executing a synchronized method for an object, all other threads that invoke synchronized methods for the same object block (suspend execution) until the first thread is done with the object.
    Second, when a synchronized method exits, it automatically establishes a happens-before relationship with any subsequent invocation of a synchronized method for the same object. This guarantees that changes to the state of the object are visible to all threads.
    Note that constructors cannot be synchronized using the synchronized keyword with a constructor is a syntax error. Synchronizing constructors doesn't make sense, because only the thread that creates an object should have access to it while it is being constructed.

2 . What is Intrinsic Locks and Synchronization ?

  •    Synchronization is built around an internal entity known as the intrinsic lock or monitor lock. (The API specification often refers to this entity simply as a "monitor.")
       Intrinsic locks play a role in both aspects of synchronization:enforcing exclusive access to an object's state and establishing happens-before relationships that are essential to visibility.
       Every object has an intrinsic lock associated with it. By convention, a thread that needs exclusive and consistent access to an object's fields has to acquire the object's intrinsic lock before accessing them, and then release the intrinsic lock when it's done with them.
       A thread is said to own the intrinsic lock between the time it has acquired the lock and released the lock. As long as a thread owns an intrinsic lock, no other thread can acquire the same lock. The other thread will block when it attempts to acquire the lock.
       When a thread releases an intrinsic lock, a happens-before relationship is established between that action and any subsequent acquistion of the same lock.

3 . What is Reentrant Synchronization ?

  •    Recall that a thread cannot acquire a lock owned by another thread. But a thread can acquire a lock that it already owns.
    Allowing a thread to acquire the same lock more than once enables reentrant synchronization.    
    This describes a situation where synchronized code, directly or indirectly, invokes a method that also contains synchronized code, and both sets of code use the same lock.    
    Without reentrant synchronization, synchronized code would have to take many additional precautions to avoid having a thread cause itself to block.

4 . What is Thread Contention?

  • Essentially thread contention is a condition where one thread is waiting for a lock/object that is currently being held by another thread. Therefore, this waiting thread cannot use that object until the other thread has unlocked that particular object.   A contention occurs when a thread is waiting for a resource that is not readily available; it slows the execution of your code, but can clear up over time.
        Serialization hurts scalability and thatcontext switches hurt performance. Contended locking causes both, so reducing lock contention can improve both performance and scalability. There are three ways to reduce lock contention:
    1. Reduce the duration for which locks are held;
    2. Reduce the frequency with which locks are requested; or
    3. Replace exclusive locks with coordination mechanisms that permit greater concurrency.

5 . What is Deadlock ?

  • Deadlock describes a situation where two or more threads are blocked forever, waiting for each other. Here's an example. Alphonse and Gaston are friends, and great believers in courtesy. A strict rule of courtesy is that when you bow to a friend, you must remain bowed until your friend has a chance to return the bow. Unfortunately, this rule does not account for the possibility that two friends might bow to each other at the same time. It will create deadlock between them.
    public class DeadlockS {
    static class Friend { private final String name;
    public Friend(String name) {
    this.name = name;
    }
    public String getName() {
    return this.name;
    }
    public synchronized void bow(Friend bower) {
    System.out.format("%s: %s"+ " has bowed to me!%n",
    this.name, bower.getName());
    bower.bowBack(this);
    }
    public synchronized void bowBack(Friend bower) {
    System.out.format("%s: %s" + " has bowed back to me!%n",
    this.name, bower.getName());
    }
    }
    public static void main(String[] args) {
    final Friend alphonse = new Friend("Alphonse");
    final Friend gaston = new Friend("Gaston");
    new Thread(new Runnable() {
    public void run() { alphonse.bow(gaston); }
    }).start();
    new Thread(new Runnable() {
    public void run() { gaston.bow(alphonse); }
    }).start();
    }
    }

6 . What is Starvation and Livelock ?

  • Starvation    Starvation describes a situation where a thread is unable to gain regular access to shared resources and is unable to make progress. This happens when shared resources are made unavailable for long periods by "greedy" threads.    For example, suppose an object provides a synchronized method that often takes a long time to return. If one thread invokes this method frequently, other threads that also need frequent synchronized access to the same object will often be blocked.

    Livelock    A thread often acts in response to the action of another thread. If the other thread's action is also a response to the action of another thread, then livelock may result.    As with deadlock, livelocked threads are unable to make further progress. However, the threads are not blocked they are simply too busy responding to each other to resume work.    This is comparable to two people attempting to pass each other in a corridor: Alphonse moves to his left to let Gaston pass, while Gaston moves to his right to let Alphonse pass. Seeing that they are still blocking each other, Alphone moves to his right, while Gaston moves to his left. They're still blocking each other, so

7 . What is Immutable Objects ?

  •    An object is considered immutable if its state cannot change after it is constructed. Maximum reliance on immutable objects is widely accepted as a sound strategy for creating simple, reliable code.    Immutable objects are particularly useful in concurrent applications. Since they cannot change state, they cannot be corrupted by thread interference or observed in an inconsistent state.    Programmers are often reluctant to employ immutable objects, because they worry about the cost of creating a new object as opposed to updating an object in place. The impact of object creation is often overestimated, and can be offset by some of the efficiencies associated with immutable objects.    These include decreased overhead due to garbage collection, and the elimination of code needed to protect mutable objects from corruption.

8 . What should be Strategy for Defining Immutable Objects ?

  •      The following rules define a simple strategy for creating immutable objects. Not all classes documented as "immutable" follow these rules. This does not necessarily mean the creators of these classes were sloppy they may have good reason for believing that instances of their classes never change after construction. However, such strategies require sophisticated analysis and are not for beginners.
    1. Don't provide "setter" methods methods that modify fields or objects referred to by fields.
    2. Make all fields final and private.
    3. Don't allow subclasses to override methods. The simplest way to do this is to declare the class as final. A more sophisticated approach is to make the constructor private and construct instances in factory methods.
    4. If the instance fields include references to mutable objects, don't allow those objects to be changed:
    5. Don't provide methods that modify the mutable objects.
    6. Don't share references to the mutable objects. Never store references to external, mutable objects passed to the constructor; if necessary, create copies, and store references to the copies. Similarly, create copies of your internal mutable objects when necessary to avoid returning the originals in your methods.

9 . What are High Level Concurrency Objects ?

  •    High-level concurrency features introduced with version 5.0 of the Java platform. Most of these features are implemented in the new java.util.concurrent packages. There are also new concurrent data structures in the Java Collections Framework.

    • Lock objects support locking idioms that simplify many concurrent applications.
    • Executors define a high-level API for launching and managing threads. Executor implementations provided by java.util.concurrent provide thread pool management suitable for large-scale applications.
    • Concurrent collections make it easier to manage large collections of data, and can greatly reduce the need for synchronization.
    • Atomic variables have features that minimize synchronization and help avoid memory consistency errors.
    • ThreadLocalRandom (in JDK 7) provides efficient generation of pseudorandom numbers from multiple threads

10 . What is Executors ?

  • In large-scale applications, it makes sense to separate thread management and creation from the rest of the application. Objects that encapsulate these functions are known as executors.

    Executor Interfaces define the three executor object types.
    Thread Pools are the most common kind of executor implementation.
    Fork/Join is a framework (new in JDK 7) for taking advantage of multiple processors.
    Executor Interfaces The java.util.concurrent package defines three executor interfaces:
    Executor, a simple interface that supports launching new tasks.
    ExecutorService, a subinterface of Executor, which adds features that help manage the lifecycle, both of the individual tasks and of the executor itself.
    ScheduledExecutorService, a subinterface of ExecutorService, supports future and/or periodic excution of tasks.
      Typically, variables that refer to executor objects are declared as one of these three interface types, not with an executor class type. Below is the example of ExecutorService using cachedThreadPool. This is using Callable instance, which does the task and return the result to calling programme.
    import java.util.concurrent.Callable;
    import java.util.concurrent.ExecutionException;
    import java.util.concurrent.ExecutorService;
    import java.util.concurrent.Executors;
    import java.util.concurrent.Future;

    public class ThreadWithResultExample {
    static ExecutorService exec = Executors.newCachedThreadPool();
    public static void main(String...strings){
    Future result = exec.submit(new Worker());
    try {
    System.out.println(result.get());
    } catch (InterruptedException e) {
    e.printStackTrace();
    } catch (ExecutionException e) {
    e.printStackTrace();
    }
    exec.shutdown();
    }
    }

    class Worker implements Callable {
    @Override
    public String call() throws Exception {
    return (String) "result";
    }

11 . What is Thread Confinement?

  •    Accessing shared, mutable data requires using synchronization; one way to avoid this requirement is to not share.    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.    When an object is confined to a thread,such usage is automatically thread safe even if the confined object itself is not

12 . What is Thread Pools ?

  •    A thread pool, as its name suggests, manages a homogeneous pool of worker threads.    A thread pool is tightly bound to a work queue holding tasks waiting to be executed. Worker threads have a simple life i.e request the next task from the work queue,execute it,and go back to waiting for another task Executing , Executing tasks in pool threads has a number of advantages over the threadpertask approach. Reusing an existing thread instead of creating a new one amortizes thread creation and tear down costs over multiple requests.    As an added bonus, since the worker thread often already exists at the time the request arrives, the latency associated with thread creation does not delay task execution, thus improving responsiveness. By properly tuning the size of the thread pool, you can have enough threads to keep the processors busy while not having so many that your application runs out of memory or thrashes due to competition among threads for resources.

    • fixed thread pool: This type of pool always has a specified number of threads running; if a thread is somehow terminated while it is still in use, it is automatically replaced with a new thread. Tasks are submitted to the pool via an internal queue, which holds extra tasks whenever there are more active tasks than threads.    An important advantage of the fixed thread pool is that applications using it degrade gracefully.    To understand this, consider a web server application where each HTTP request is handled by a separate thread. If the application simply creates a new thread for every new HTTP request, and the system receives more requests than it can handle immediately, the application will suddenly stop responding to all requests when the overhead of all those threads exceed the capacity of the system.    With a limit on the number of the threads that can be created, the application will not be servicing HTTP requests as quickly as they come in, but it will be servicing them as quickly as the system can sustain. A simple way to create an executor that uses a fixed thread pool is to invoke the newFixedThreadPool factory method in
    • The newCachedThreadPool method creates an executor with an expandable thread pool. This executor is suitable for applications that launch many short-lived tasks.
    • The newSingleThreadExecutor method creates an executor that executes a single task at a time.
    • ScheduledExecutorService If none of the executors provided by the above factory methods meet your needs, constructing instances of java.util.concurrent.ThreadPoolExecutor or java.util.concurrent.ScheduledThreadPoolExecutor will give you additional options.

13 . What is Fork/Join ?

  • New in the Java SE 7 release, the fork/join framework is an implementation of the ExecutorService interface that helps you take advantage of multiple processors.
    It is designed for work that can be broken into smaller pieces recursively. The goal is to use all the available processing power to make your application wicked fast. As with any ExecutorService, the fork/join framework distributes tasks to worker threads in a thread pool.
        The fork/join framework is distinct because it uses a work-stealing algorithm. Worker threads that run out of things to do can steal tasks from other threads that are still busy.

        The center of the fork/join framework is the ForkJoinPool class, an extension of AbstractExecutorService. ForkJoinPool implements the core work-stealing algorithm and can execute ForkJoinTasks.

    Basic Use: Using the fork/join framework is simple. The first step is to write some code that performs a segment of the work. Your code should look similar to this: if (my portion of the work is small enough) do the work directly else split my work into two pieces invoke the two pieces and wait for the results Wrap this code as a ForkJoinTask subclass, typically as one of its more specialised types RecursiveTask(which can return a result) or RecursiveAction.
        After your ForkJoinTask is ready, create one that represents all the work to be done and pass it to the invoke() method of a ForkJoinPool instance.

14 . What is Concurrent Collections ?

  • The java.util.concurrent package includes a number of additions to the Java Collections Framework. These are most easily categorized by the collection interfaces provided:

    BlockingQueue defines a first-in-first-out data structure that blocks or times out when you attempt to add to a full queue, or retrieve from an empty queue.

    ConcurrentMap is a subinterface of java.util.Map that defines useful atomic operations. These operations remove or replace a key-value pair only if the key is present, or add a key-value pair only if the key is absent. Making these operations atomic helps avoid synchronization. The standard general-purpose implementation of ConcurrentMap is

    ConcurrentHashMap, which is a concurrent analog of HashMap.

    ConcurrentNavigableMap is a subinterface of ConcurrentMap that supports approximate matches. The standard general-purpose implementation of ConcurrentNavigableMap is

    ConcurrentSkipListMap, which is a concurrent analog of TreeMap. All of these collections help avoid Memory Consistency Errors by defining a happens-before relationship between an operation that adds an object to the collection with subsequent operations that access or remove that object.
    package com.iexamonline.thread;
    import java.util.concurrent.ArrayBlockingQueue;
    public class MyArrayBlockingQueue {
    ArrayBlockingQueue abq = new ArrayBlockingQueue(10,true);/*Size 10 and fair policy */
    String getData(){
    return abq.poll();
    }
    void setData(String e){
    abq.add(e);
    }
    public static void main(String...strings){
    final MyArrayBlockingQueue queue = new MyArrayBlockingQueue();
    /* Iterate like collection*/
    for(String s: queue.abq){
    System.out.println(s);
    }
    /* Data producer*/
    new Thread(
    new Runnable(){
    @Override
    public void run() {
    for(int i = 0; i<10; i++){
    queue.setData( String.valueOf(i));
    }
    }
    }
    ).start();
    /* Consumer*/
    new Thread(
    new Runnable(){
    @Override
    public void run() {
    for(int i = 0; i<10; i++){
    System.out.println(queue.getData());
    }
    }
    }
    ).start();
    }
    }
    }

15 . Can you pass a Thread object to Executor.execute? Would such an invocation make sense? Why or why not ?

  • The Thread implements the Runnable interface, so you can pass an instance of Thread to Executor.execute. However it doesn't make sense to use Thread objects this way. If the object is directly instantiated from Thread, its run method doesn't do anything. You can define a subclass of Thread with a useful run method but such a class would implement features that the executor would not use.

16 . What is BlockingQueue ?

  •    A Queue that additionally supports operations that wait for the queue to become non-empty when retrieving an element, and wait for space to become available in the queue when storing an element.
       BlockingQueue methods come in four forms, with different ways of handling operations that cannot be satisfied immediately, but may be satisfied at some point in the future:
       One throws an exception, the second returns a special value (either null or false, depending on the operation), the third blocks the current thread indefinitely until the operation can succeed, and the fourth blocks for only a given maximum time limit before giving up

    • A BlockingQueue does not accept null elements. Implementations throw NullPointerException on attempts to add, put or offer a null. A null is used as a sentinel value to indicate failure of poll operations.
    • A BlockingQueue may be capacity bounded. At any given time it may have a remainingCapacity beyond which no additional elements can be put without blocking. A BlockingQueue without any intrinsic capacity constraints always reports a remaining capacity of Integer.MAX_VALUE.
    • BlockingQueue implementations are designed to be used primarily for producer-consumer queues, but additionally support the Collection interface. So, for example, it is possible to remove an arbitrary element from a queue using remove(x). However, such operations are in general not performed very efficiently, and are intended for only occasional use, such as when a queued message is cancelled.
    • BlockingQueue implementations are thread-safe. All queuing methods achieve their effects atomically using internal locks or other forms of concurrency control. However, the bulk Collection operations addAll, containsAll, retainAll and removeAll are not necessarily performed atomically unless specified otherwise in an implementation. So it is possible, for example, for addAll(c) to fail (throwing an exception) after adding only some of the elements in c.

17 . Describe ArrayBlockingQueue, DelayQueue and LinkedBlockingQueue ?

    • ArrayBlockingQueue extends AbstractQueue implements BlockingQueue,Serializable
         A bounded blocking queue backed by an array. This queue orders elements FIFO (first-in-first-out). The head of the queue is that element that has been on the queue the longest time. The tail of the queue is that element that has been on the queue the shortest time.
         New elements are inserted at the tail of the queue, and the queue retrieval operations obtain elements at the head of the queue. This is a classic "bounded buffer", in which a fixed-sized array holds elements    inserted by producers and extracted by consumers. Once created, the capacity cannot be changed. Attempts to put an element into a full queue will result in the operation blocking; attempts to take an element from an empty queue will similarly block.
         This class supports an optional fairness policy for ordering waiting producer and consumer threads. By default, this ordering is not guaranteed. However, a queue constructed with fairness set to true grants threads access in FIFO order. Fairness generally decreases throughput but reduces variability and avoids starvation.

    • DelayQueue extends Delayed extends AbstractQueue implements BlockingQueue    An unbounded blocking queue of Delayed elements, in which an element can only be taken when its delay has expired. The head of the queue is that Delayed element whose delay expired furthest in the past. If no delay has expired there is no head and poll will return null.
         Expiration occurs when an element's getDelay(TimeUnit.NANOSECONDS) method returns a value less than or equal to zero. Even though unexpired elements cannot be removed using take or poll, they are otherwise treated as normal elements.
         For example, the size method returns the count of both expired and unexpired elements. This queue does not permit null elements.
         This class and its iterator implement all of the optional methods of the Collection and Iterator interfaces.

    • LinkedBlockingQueue extends AbstractQueue implements BlockingQueue, Serializable    An optionally-bounded blocking queue based on linked nodes. This queue orders elements FIFO (first-in-first-out). The head of the queue is that element that has been on the queue the longest time. The tail of the queue is that element that has been on the queue the shortest time. New elements are inserted at the tail of the queue, and the queue retrieval operations obtain elements at the head of the queue.
         Linked queues typically have higher throughput than array-based queues but less predictable performance in most concurrent applications. The optional capacity bound constructor argument serves as a way to prevent excessive queue expansion. The capacity, if unspecified, is equal to Integer.MAX_VALUE. Linked nodes are dynamically created upon each insertion unless this would bring the queue above capacity.
         This class and its iterator implement all of the optional methods of the Collection and Iterator interfaces.

18 . What is BlockingDeque ?

  • BlockingDeque extends BlockingQueue, Deque Deque - A linear collection that supports element insertion and removal at both ends.
       The name deque is short for "double ended queue" and is usually pronounced "deck". Most Deque implementations place no fixed limits on the number of elements they may contain, but this interface supports capacity-restricted deques as well as those with no fixed size limit.
       This interface defines methods to access the elements at both ends of the deque.
       Methods are provided to insert, remove, and examine the element. Each of these methods exists in two forms: one throws an exception if the operation fails, the other returns a special value (either null or false, depending on the operation). The latter form of the insert operation is designed specifically for use with capacity-restricted Deque implementations; in most implementations, insert operations cannot fail.
       A BlockingDeque that additionally supports blocking operations that wait for the deque to become non-empty when retrieving an element, and wait for space to become available in the deque when storing an element.
       BlockingDeque methods come in four forms, with different ways of handling operations that cannot be satisfied immediately, but may be satisfied at some point in the future:
       one throws an exception, the second returns a special value (either null or false, depending on the operation), the third blocks the current thread indefinitely until the operation can succeed, and the fourth blocks for only a given maximum time limit before giving up.

19 . What is Semaphore ?

  • A counting semaphore. Conceptually, a semaphore maintains a set of permits. Each acquire() blocks if necessary until a permit is available, and then takes it. Each release() adds a permit, potentially releasing a blocking acquirer. However, no actual permit objects are used; the Semaphore just keeps a count of the number available and acts accordingly.Semaphores are often used to restrict the number of threads than can access some (physical or logical) resource.

20 . What is CountDownLatch ?

  • A synchronization aid that allows one or more threads to wait until a set of operations being performed in other threads completes. A CountDownLatch is initialized with a given count. The await methods block until the current count reaches zero due to invocations of the countDown() method, after which all waiting threads are released and any subsequent invocations of await return immediately. This is a one-shot phenomenon the count cannot be reset.(If you need a version that resets the count, consider using a CyclicBarrier). A CountDownLatch is a versatile synchronization tool and can be used for a number of purposes. A CountDownLatch initialized with a count of one serves as a simple on/off latch, or gate: all threads invoking await wait at the gate until it is opened by a thread invoking countDown(). A CountDownLatch initialized to N can be used to make one thread wait until N threads have completed some action, or some action has been completed N times. A useful property of a CountDownLatch is that it doesn't require that threads calling countDown wait for the count to reach zero before proceeding, it simply prevents any thread from proceeding past an await until all threads could pass. Sample usage: Here is a pair of classes in which a group of worker threads use two countdown latches: The first is a start signal that prevents any worker from proceeding until the driver is ready for them to proceed; The second is a completion signal that allows the driver to wait until all workers have completed.
    package com.learning.thread;

    import java.util.concurrent.CountDownLatch;

    public class LatchTest {
    private static final int COUNT = 10;

    private static class Worker implements Runnable {
    CountDownLatch startLatch;
    CountDownLatch stopLatch;
    String name;

    Worker(CountDownLatch startLatch, CountDownLatch stopLatch, String name) {
    this.startLatch = startLatch;
    this.stopLatch = stopLatch;
    this.name = name;
    }

    public void run() {
    try {
    startLatch.await(); /* wait until the latch has counted down to zero*/
    } catch (InterruptedException ex) {
    ex.printStackTrace();
    }
    System.out.println("Running: " + name);
    stopLatch.countDown();
    }
    }

    public static void main(String args[]) {
    /* CountDownLatch(int count)*/
    /* Constructs a CountDownLatch initialized with the given count.*/
    CountDownLatch startSignal = new CountDownLatch(1);
    CountDownLatch stopSignal = new CountDownLatch(COUNT);
    for (int i = 0; i < COUNT; i++) {
    new Thread(new Worker(startSignal, stopSignal, Integer.toString(i))) .start();
    }
    System.out.println("Go");
    startSignal.countDown();
    try {
    stopSignal.await();
    } catch (InterruptedException ex) {
    ex.printStackTrace();
    }
    System.out.println("Done");
    }
    }

21 . What is CyclicBarrier ?

  •    A synchronization aid that allows a set of threads to all wait for each other to reach a common barrier point.
       CyclicBarriers are useful in programs involving a fixed sized party of threads that must occasionally wait for each other. The barrier is called cyclic because it can be re-used after the waiting threads are released.
       A CyclicBarrier supports an optional Runnable command that is run once per barrier point, after the last thread in the party arrives, but before any threads are released. This barrier action is useful for updating shared-state before any of the parties continue.

22 . What is ConcurrentHashMap ?

  • ConcurrentHashMap extends AbstractMap implements ConcurrentMap, Serializable
        A hash table supporting full concurrency of retrievals and adjustable expected concurrency for updates.     This class obeys the same functional specification as Hashtable, and includes versions of methods corresponding to each method of Hashtable.
       However, even though all operations are thread-safe, retrieval operations do not entail locking, and there is not any support for locking the entire table in a way that prevents all access.     This class is fully interoperable with Hashtable in programs that rely on its thread safety but not on its synchronization details.
        Retrieval operations (including get) generally do not block, so may overlap with update operations (including put and remove). Retrievals reflect the results of the most recently completed update operations holding upon their onset. For aggregate operations such as putAll and clear, concurrent retrievals may reflect insertion or removal of only some entries.
       Similarly, Iterators and Enumerations return elements reflecting the state of the hash table at some point at or since the creation of the iterator/enumeration. They do not throw ConcurrentModificationException. However, iterators are designed to be used by only one thread at a time.
       The allowed concurrency among update operations is guided by the optional concurrencyLevel constructor argument (default 16), which is used as a hint for internal sizing. The table is internally partitioned to try to permit the indicated number of concurrent updates without contention.
       Because placement in hash tables is essentially random, the actual concurrency will vary. Ideally, you should choose a value to accommodate as many threads as will ever concurrently modify the table. Using a significantly higher value than you need can waste space and time, and a significantly lower value can lead to thread contention. But overestimates and underestimates with in an order of magnitude do not usually have much noticeable impact. A value of one is appropriate when it is known that only one thread will modify and all others will only read.
       Also, resizing this or any other kind of hash table is a relatively slow operation, so, when possible, it is a good idea to provide estimates of expected table sizes in constructors.
       This class and its views and iterators implement all of the optional methods of the Map and Iterator interfaces. Like Hash table but unlike HashMap, this class does not allow null to be used as a key or value.

23 . What is ThreadGroup and it's Use?

  •    A thread group represents a set of threads. In addition, a thread group can also include other thread groups. The thread groups form a tree in which every thread group except the initial thread group has a parent.
       A thread is allowed to access information about its own thread group, but not to access information about its thread group's parent thread group or any other thread groups.
       For Example Application servers maintains Thread Group for co-related similar type of threads.

24 . What is LocalThread and its use?

  • This class provides thread-local variables. These variables differ from their normal counterparts in that each thread that accesses one (via its get 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). For example, the class below generates unique identifiers local to each thread. A thread's id is assigned the first time it invokes UniqueThreadIdGenerator.getCurrentThreadId() and remains unchanged on subsequent calls.
    import java.util.concurrent.atomic.AtomicInteger;
    public class UniqueThreadIdGenerator {
    private static final AtomicInteger uniqueId = new AtomicInteger(0);
    private static final ThreadLocal < Integer > uniqueNum = new ThreadLocal < Integer > () {
    @Override
    protected Integer initialValue() {
    return uniqueId.getAndIncrement();
    }
    };
    public static int getCurrentThreadId() {
    return uniqueId.get();
    }
    } /* UniqueThreadIdGenerator*/

    Each thread holds an implicit reference to its copy of a thread-local variable as long as the thread is alive and the ThreadLocal instance is accessible; after a thread goes away, all of its copies of thread-local instances are subject to garbage collection (unless other references to these copies exist).

25 . Java memory model for double and long and what care we need to take to use these in multithreaded environment?

  •    Java Double and long are 64 bits characters and in 32 bit machines read and write of double and long is not atomic operation.
       This operation is two steps first reading first part [32 bit] and the reading the second part [32 bit] so we need to take extra care when we are reading and writing the double and long variable in multi threaded application.

26 . What is CompletionService or ExecutorCompletionService ?

  •    A service that decouples the production of new asynchronous tasks from the consumption of the results of completed tasks.
       Producers submit tasks for execution. Consumers take completed tasks and process their results in the order they complete.
       A CompletionService can for example be used to manage asynchronous IO, in which tasks that perform reads are submitted in one part of a program or system, and then acted upon in a different part of the program when the reads complete, possibly in a different order than they were requested.
       Typically, a CompletionService relies on a separate Executor to actually execute the tasks, in which case the CompletionService only manages an internal completion queue. The ExecutorCompletionService class provides an implementation of this approach.

27 . What is special about concurrent.atomic package?

  • In essence, the classes in this package extend the notion of volatile values, fields, and array elements to those that also provide an atomic conditional update operation of the form: boolean compareAndSet(expectedValue, updateValue); This method (which varies in argument types across different classes) atomically sets a variable to the updateValue if it currently holds the expectedValue, reporting true on success. The classes in this package also contain methods to get and unconditionally set values, as well as a weaker conditional atomic update operation weakCompareAndSet. The weak version may be more efficient in the normal case, but differs in that any given invocation of weakCompareAndSet method may fail, even spuriously (that is, for no apparent reason). A false return means only that the operation may be retried if desired, relying on the guarantee that repeated invocation when the variable holds expectedValue and no other thread is also attempting to set the variable will eventually succeed. The specifications of these methods enable implementations to employ efficient machine-level atomic instructions that are available on contemporary processors. However on some platforms, support may entail some form of internal locking.Thus the methods are not strictly guaranteed to be non-blocking a thread may block transiently before performing the operation. Instances of classes AtomicBoolean, AtomicInteger, AtomicLong, and AtomicReference each provide access and updates to a single variable of the corresponding type. Each class also provides appropriate utility methods for that type. For example, classes AtomicLong and AtomicInteger provide atomic increment methods. One application is to generate sequence numbers, as in:
    class Sequencer { 
    private AtomicLong sequenceNumber = new AtomicLong(0);
    public long next() { return sequenceNumber.getAndIncrement(); }
    }
    The memory effects for accesses and updates of atomics generally follow the rules for volatiles: - get has the memory effects of reading a volatile variable. - set has the memory effects of writing (assigning) a volatile variable. - weakCompareAndSet atomically reads and conditionally writes a variable, is ordered with respect to other memory operations on that variable, but otherwise acts as an ordinary non-volatile memory operation. - compareAndSet and all other read-and-update operations such as getAndIncrement have the memory effects of both reading and writing volatile variables.

28 . Explain ReentrantReadWriteLock ?

  • This is special Lock implementation which is having separate lock for reading and writing. The lock can be upgraded from ReadLock to WriteLock but reverse is not possible. This is very useful in case where you have more reads compare to write so read operation in not locked. This Lock implementation supports condition. ReentrantReadWriteLock.ReadLock The lock returned by method readLock() ReentrantReadWriteLock.WriteLock The lock returned by method writeLock()

29 . What are poison pills?

  •    A way to convince a produce consumer service to shut down is with a poison pill: a recognizable object placed on the queue that means "when you get this, stop."
       With a FIFO queue, poison pills ensure that consumersfinish the work on their queue before shutting down, since any work submitted prior to submitting the poison pill will be retrieved before the pill; producers should not submit any work after putting a poison pill on the queue.