Showing posts with label Multi-threading. Show all posts
Showing posts with label Multi-threading. Show all posts

Spring Hibernate Article: Scenarios and solutions for better concurrency and thread safety part-3 Semaphores and mutexes

Scenario 1: A web service receives http requests for data, places the request into an internal queue, and a separate worker thread pulls the work item from the queue and performs the work. For example, a trading system creates a buy order and places it in a queue, and a separate consumer thread picks up the order and sends it to the stock exchange. A typical producer and consumer scenario.

Scenario 2: Semaphore can be used to create worker threads even when the number of worker threads to be created is not known upfront. This is because a semaphore can be created with 0 permits, and wait until a number of releases have been made. For example, if you want to recursively traverse through nested folders and spawn a number of worker threads to move the html files found to a destination folder and increment the semaphore permits with a release() method call. A separate thread will wait with the acquire(numberofpermits) to acquire all the released permits before start archiving (i.e. zipping up) those files.

Scenario 3: Reference counting where a shared resource is incremented or decremented. The increment/decrement/test operations must be thread safe. For example, a counter that keeps track of the nummber of active logged in users by incrementing the count when users log in and decrementing the count when the users log out.



Solution: In general, a sem-a-phore means sending messages by holding the arms or two flags or poles in certain positions according to an alphabetic code. In programming, especially in Unix systems, semaphores are a technique for coordinating or synchronizing activities in which multiple processes compete for the same operating system resources. Semaphores are commonly use for two purposes: to share a common memory space and to share access to files. In Java, a semaphore is used for coordinating multiple threads.

Q. What is the difference between a mutex and a semaphore?
A. 

Mutex: is a single key to a toilet. One person can have the key and occupy the toilet  at the time. When finished, the person gives (or releases) the key to the next person in the queue. In Java, every object has a mutex and only a single thread can get hold of a mutex.

Semaphore: Is a number of free identical toilet keys. For example, having 3 toilets with identical locks and keys. The semaphore count is set to 3 at beginning and then the count is decremented as people are acquiring the key to the toilets. If all toilets are full, ie. there are no free keys left, the semaphore count is 0. Now, when one person leaves the toilet, semaphore is increased to 1 (one free key), and given to the next person in the queue.

Here is an example of producer and consumer using a mutex.

public class ProducerConsumer {

private int count; //shared resource, i.e. accessed by multiple threads

public synchronized void consume() {
while (count == 0) {
try {
wait(); //wait till notified
} catch (InterruptedException e) {
e.printStackTrace();
}
}

//gets here if count is > 0
count--; //consume the count by decrementing it by 1
System.out.println("Consumed:" + count);
notify(); //notify waiting threads to resume

}

public synchronized void produce() {
while(count > 0) {
try {
wait(); //wait till notified
} catch (InterruptedException e) {
e.printStackTrace();
}
}

//gets here if count == 0;
count++;
System.out.println("Produced: " + count);
notify(); //notify waiting threads to resume
}

public static void main(String[] args) {
//inner classes can only access final variables
final ProducerConsumer pc = new ProducerConsumer();

//anonymous inner class for a new producer worker thread
Runnable producer = new Runnable() {
@Override
public void run() {
for (int i = 0; i < 3; i++) {
pc.produce();
}
}
};


//anonymous inner class for a new consumer worker thread
Runnable consumer = new Runnable() {
@Override
public void run() {
for (int i = 0; i < 3; i++) {
pc.consume();
}
}
};

Thread producerThread = new Thread(producer); //creates a new worker thread from the main thread
Thread consumerThread = new Thread(consumer); //creates a new worker thread from the main thread

producerThread.start(); // executes the run() method in producer
consumerThread.start(); // executes the run() method in consumer

}
}


Now, let us look at the similar example with a Semaphore in Java 5. You can create a Semaphore with relevant number of permits, and the permits can be acquired or released.

import java.util.concurrent.Semaphore;

public class ProducerConsumer2 {

private int count;

/**
* call to release will increment the permit(s) and
* call to acquire will decrement the permit(s)
*/
static Semaphore semCon = new Semaphore(0);
static Semaphore semProd = new Semaphore(1); //start with 1 permit

public void consume() {
try {
//acquire a permit from this semaphore before continuing
semCon.acquire();
} catch (InterruptedException e) {
e.printStackTrace();
}

count--;
System.out.println("Consumed:" + count);
//releases a permit, returning it to the semaphore.
semProd.release();

}

public void produce() {
try {
//acquire a permit from this semaphore before continuing
semProd.acquire();
} catch (InterruptedException e) {
e.printStackTrace();
}
count++;
System.out.println("Produced: " + count);
//releases a permit, returning it to the semaphore.
semCon.release();
}

public static void main(String[] args) {

final ProducerConsumer2 pc = new ProducerConsumer2();

//anonymous inner class for a new producer worker thread
Runnable producer = new Runnable() {
@Override
public void run() {
for (int i = 0; i < 3; i++) {
pc.produce();
}
}
};

//anonymous inner class for a new consumer worker thread
Runnable consumer = new Runnable() {
@Override
public void run() {
for (int i = 0; i < 3; i++) {
pc.consume();
}
}
};

Thread producerThread = new Thread(producer); //creates a new worker thread from the main thread
Thread consumerThread = new Thread(consumer); //creates a new worker thread from the main thread

producerThread.start(); // executes the run() method in producer
consumerThread.start(); // executes the run() method in consumer

}
}


The output for both the above code:

Produced: 1
Consumed:0
Produced: 1
Consumed:0
Produced: 1
Consumed:0

Spring Hibernate Java 5 Executor Framework - why use thread pools?

Q. What is a thread pool, and how will you create them in Java? Why do you need an Executor framework?
A. A thread pool is a collection of runnables with a work queue. The threads in the pool constantly run and  check the work queue for new work. If there is new work to be done they execute this Runnable.

In Java 5, Executor framework was introduced with the java.util.concurrent.Executor interface. This was introduced to fix some of the shortcomings discussed below.


1. The Executor framework is a framework for standardizing invocation, scheduling, execution, and control of asynchronous tasks according to a set of execution policies.


2. Even though the threads are light-weighted than creating a process, creating them utilizes a lot of resources. Also, creating a new thread for each task will consume more stack memory as each thread will have its own stack and also the CPU will spend more time in context switching. Creating a lot many threads with no bounds to the maximum threshold can cause application to run out of heap memory. So, creating a ThreadPool is a better solution as a finite number of threads can be pooled and reused. The runnable or callable tasks will be placed in a queue, and the finite number of threads in the pool will take turns to process the tasks in the queue.


Here is the sample code:


import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Sum implements Runnable {

private static final int NO_OF_THREADS= 3;

int maxNumber;

public Sum(int maxNumber) {
this.maxNumber = maxNumber;
}

/** method where the thread execution will start **/
public void run(){
int sum = 0;
for (int i = 0; i = maxNumber; i++) {
sum += maxNumber;
}

System.out.println("Thread " + Thread.currentThread().getName() + " count is " + sum);
}


/** main thread. Always there by default. **/
public static void main(String[] args) {
ExecutorService executor = Executors.newFixedThreadPool(NO_OF_THREADS); // create a pool of 3 threads
for (int i = 10000; i < 10100; i++) {
Runnable worker = new Sum(i); // create worker threads
executor.execute(worker); // add runnables to the work queue
}

// This will make the executor accept no new threads
// and finish all existing threads in the queue
executor.shutdown();

// Wait until all threads have completed
while (!executor.isTerminated()) {

}

System.out.println("Finished all threads");
}

}

3. The Runnable interface's void run( ) method has no way of returning any result back to the main thread. The executor framework introduced the Callable interface that returns a value from its call( ) method. This means the asynchronous task will be able to return a value once it is done executing.

import java.util.ArrayList;
import java.util.List;
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 Sum implements Callable<String> {

private static final int NO_OF_THREADS = 3;

int maxNumber;

public Sum(int maxNumber) {
this.maxNumber = maxNumber;
}

/** method where the thread execution will start
* this can return a value
*/
public String call(){
int sum = 0;
for (int i = 0; i <= maxNumber; i++) {
sum += maxNumber;
}

return Thread.currentThread().getName() + " count is " + sum;
}


/** main thread. Alwyas there by default. **/
public static void main(String[] args) {
ExecutorService executor = Executors.newFixedThreadPool(NO_OF_THREADS); // create a pool of 3 threads
List<Future<String>> list = new ArrayList<Future<String>>(10); // provides facility to return results asynchronously

for (int i = 10000; i < 10100; i++) {
Callable<String> worker = new Sum(i); // create worker threads
Future<String> submit = executor.submit(worker); // add callables to the work queue
list.add(submit); // provides facility to return results asynchronously
}

//process the results asynchronously when each thread completes its task
for (Future<String> future : list) {
try {
System.out.println("Thread " + future.get());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}


executor.shutdown();

System.out.println("Finished all threads");
}

}

The output is something like

Thread pool-1-thread-1 count is 100010000
Thread pool-1-thread-2 count is 100030002
Thread pool-1-thread-3 count is 100050006
Thread pool-1-thread-1 count is 100070012
Thread pool-1-thread-1 count is 100090020
...

4. The various Executor implementations provide different execution policies to be set while executing the tasks. For example, the ThreadPool supports the following policies:

  • newFixedThreadPool: Creates threads as tasks are submitted, up to the maximum pool size, and then attempts to keep the pool size constant.
  • newCachedThreadPool: Can add new threads when demand increases, no bounds on the size of the pool.
  • newSingleThreadExecutor: Single worker thread to process tasks, Guarantees order of execution based on the queue policy (FIFO, LIFO, priority order).
  • newScheduledThreadPool: Fixed-size, supports delayed and periodic task execution.
5. The ExecutorService provides facilities to shut down an application gracefully, abruptly, or somewhere in-between.

Q. What design pattern does the executor framework use?
A. The Executor is based on the producer-consumer design pattern, where threads that submit tasks are producers and the threads that execute tasks are consumers. In the above examples, the main thread is the producer as it loops through and submits tasks to the worker threads. The "Sum" (i.e. a worker thread) is the consumer that executes the tasks submitted by the main (i.e. consumer) thread. Check this blog to learn  more detailed explanation on the producer-consumer design pattern.


Spring Hibernate Java multi-threading interview questions and answers: atomic operations

Q. Can you give some examples of thread racing conditions you had experienced?
A.

1. Declaring variables in JSP pages are not thread-safe. The declared variables in JSP pages end-up as instance variables in the converted Servlets.

<%! Calendar c = Calendar.getInstance(); %>

2. Decalring instance variables in Servlets is not thread safe, as Servlets are inherently multi-threaded and gets accessed by multiple-threads. Same is true for the Action classes in the struts framework.

3. Some of the Java standard library classes like SimpleDateFormat is not thread-safe. Always check the API to see if a particular class is thread-safe. If a particular class or library is not therad-safe, you could do one of three things.


  • Provide your own wrapper class that decorates the third-party library with proper synchronization. This is a typical use of the decorator design pattern.
  • Use an alternative library, which is thread-safe if available. For example, Joda Time Library. 
  • Use it in a thread-safe manner. For example, you could use the SimpleDateFormat class as shown below within a ThreadLocal class. Each thread will have its own instance of the SimpleDateFormat object.


public class DateFormatTest {

//anonymous inner class. Each thread will have its own copy
private final static ThreadLocal<SimpleDateFormat> shortDateFormat = new ThreadLocal<SimpleDateFormat>() {
protected SimpleDateFormat initialValue() {
return new SimpleDateFormat("dd/MM/yyyy");
}
};


public Date convert(String strDate)
throws ParseException {

//get the SimpleDateFormat instance for this thread and parse the date string
Date d = shortDateFormat.get().parse(strDate);
return d;
}

}

4. The one that is very popular with the interviewers is writing the singleton classes that are not thread-safe.

Q. Can you have a true singleton class in Java? How would you write a thread-safe singleton class?
A. A singleton class is something for which only one instance exists per class loader. Single instance for a whole application cannot be guaranteed. That is just definition of what a singleton is. The one that is  popular with the interviewers is writing a thread-safe singleton class. For example, the following singleton class is not thread-safe because before a thread creates the Singleton instance, another thread can proceed to the instantiation part of the code -- instance = new Object( );  to create more than one instance of the Singleton object. Even though the code --> instance = new Object( ); appears to be single line, the JVM has to execute a number of internal steps like allocating memory, creating a new object and assigning the newly created object to the referenced variable. Only after the completion of these steps, the condition instance == null will return false.

//final so that cannot be subclassed
public final class Singleton {

private static Object instance = null;

//private so that it cannot be instantiated from outside this class
private Singleton() {}

public static Object getInstance() {
if (instance == null) {
instance = new Object();
}

return instance;
}
}


So, you can make the above code thread-safe in a number of ways.


Option 1: Synchronize the whole method or the block of code. This approach is not efficient as the use of synchronized keyword in a singleton class means that only one thread will be executing the synchronized block at a time and all other threads would be waiting.


Option 2: Eagerly initialize the singleton instance when the class is actually loaded as opposed to initializing it lazily at at run time only when it is accessed.


//final so that cannot be subclassed
public final class ThreadSafeSingleton {

//eager initialization and instantitiated as soon as the class is loaded by a classloader in the JVM
private static Object instance = new Object();

//private so that it cannot be instantiated from outside this class
private Singleton() {}

public static Object getInstance() {
return instance;
}
}

Option 3: You can use the "Initialize-On-Demand Holder Class" idiom proposed by Brian Goetz to create a thread-safe lazy-initialized Singleton as shown below by creating an inner class.


public final class ThreadSafeSingleton {
 
    //private so that it cannot be instantiated from outside this class
    private ThreadSafeSingleton() {}
   
    //static inner class, invoked only when ThreadSafeSingleton.getInstance() is called
    private static class ThreadSafeSingletonHolder {
        private static ThreadSafeSingleton instance = new ThreadSafeSingleton();
    }
 
    public static Object getInstance() {
        return ThreadSafeSingletonHolder.instance;
    }
}


Option 4: is to create a per thread singleton as discussed earlier with the ThreadLocal class for the SimpledateFormat.



Q. Explain how you would get thread-safety issues due to non-atomic operations with a code example?
A. The code snippets below demonstrates non-atomic operations producing incorrect results with code. The program below uses a shared Counter object, that is shared between three concurrent users (i.e. three threads). The Counter object is responsible for incrementing the counter.


Firstly, the Counter class. The counted values are stored in a HashMap by name (i.e. thread name) as the key for later retrieval


import java.util.HashMap;
import java.util.Map;

public class Counter {

//shared variable or resource
private Integer count = Integer.valueOf(0);

private Map<String, Integer> userToNumber = new HashMap<String, Integer>(10);

public void increment() {
try {
count = count + 1; //increment the counter
Thread.sleep(50); // to imitate other operations and to make the racing condion to occur more often for the demo
Thread thread = Thread.currentThread();
userToNumber.put(thread.getName(), count);
} catch (InterruptedException e) {
e.printStackTrace();
}

}


public Integer getCount(String name) {
return userToNumber.get(name);
}

}




Next, the Runnable task where each thread will be entering and executing concurrently.


public class CountingTask implements Runnable {


private Counter counter;

public CountingTask(Counter counter) {
super();
this.counter = counter;
}

@Override
public void run() {
counter.increment();
Thread thread = Thread.currentThread();
System.out.println(thread.getName() + " value is " + counter.getCount(thread.getName()));

}

}



Finally, the Manager class that creates 3 new threads from the main thread.


public class CountingManager {

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

Counter counter = new Counter(); // create an instance of the Counter
CountingTask task = new CountingTask(counter); // pass the counter to the runnable CountingTask


//Create 10 user threads (non-daemon) from the main thread that share the counter object
Thread thread1 = new Thread(task, "User-1");
Thread thread2 = new Thread(task, "User-2");
Thread thread3 = new Thread(task, "User-3");


//start the threads
thread1.start();
thread2.start();
thread3.start();


//observe the racing conditions in the output

}

}


To see the racing condition, inspect the output of the above code


User-3 value is 3
User-1 value is 3
User-2 value is 3


All three threads or users get assigned the same value of 3 due to racing conditions. We are expecting to see three different count values to be assigned from 1 to 3. What happened here is that when the first thread incremented the count from 0 to 1 and entered into the sleep(50) block, the second and third threads incremented the counts from 1 to 2 and 2 to 3 respectively. This shows that the 2 operations -- the operation that increments the thread and the operation that stores the incremented value in a HashMap are not atomic, and produces incorrect results due to racing conditions.


Q. How will you fix the above racing issue?
A. This can be fixed a number of ways.


Option 1: Method level synchronization. This is the simplest. As you can see, the increment() method is synchronized, so that the other threads must wait for the thread that already has the lock to execute that method.

import java.util.HashMap;
import java.util.Map;

public class Counter {

//shared variable or resource
private Integer count = Integer.valueOf(0);

private Map<String, Integer> userToNumber = new HashMap<String, Integer>(10);

public synchronized void increment() {
try {
count = count + 1;
Thread.sleep(50);
Thread thread = Thread.currentThread();
userToNumber.put(thread.getName(), count);
} catch (InterruptedException e) {
e.printStackTrace();
}

}


public Integer getCount(String name) {
return userToNumber.get(name);
}

}


Option 2: Even though the Option 1 is simple, it locks the entire method and can adversely impact performance for long running methods as each thread has to execute the entire method one at a time. So, the Option 1 can be improved by providing block level lock. Lock only those operations that are acting on the shared resource and making it non-atomic.


The code below uses an Object, which has its own lock to ensure that two threads cannot execute both the Operation 1 and 2 at the same time because there is only one lock.

import java.util.HashMap;
import java.util.Map;

public class Counter {

//shared variable or resource
private Integer count = Integer.valueOf(0);

private Map<String, Integer> userToNumber = new HashMap<String, Integer>(10);

private Object mutex = new Object(); // a lock

public void increment() {
try {
synchronized(mutex) {
count = count + 1; //operation 1
Thread.sleep(50);
Thread thread = Thread.currentThread();
userToNumber.put(thread.getName(), count); //operation 2
}
// there could be other operations here that uses the shared resource as read only

} catch (InterruptedException e) {
e.printStackTrace();
}

}

public Integer getCount(String name) {
return userToNumber.get(name);
}

}


Option 3: This is a very trivial, but practical example. The Java 5 introduced locks and locks are better than using just objects for more flexible locking scenarios where Locks can be used in place of synchronized blocks. Locks offer more flexibility than synchronized blocks in that a thread can unlock multiple locks it holds in a different order than the locks were obtained. Here is the code that replaces synchronized with a reentrant lock. Synchronized blocks in Java are reentrant, which means if a Java thread enters a synchronized block of code, and thereby take the lock on the object the block is synchronized on, the thread can enter other Java code blocks synchronized on the same lock object.

For example, here is the demo of reentrant lock.

public class Reentrant{

public synchronized method1(){
method2(); //calls another synchronized method on the same object
}

public synchronized method2(){
//do something
}
}



Here is the Option 3 example using a ReentrantLock.

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class Counter {

// shared variable or resource
private Integer count = Integer.valueOf(0);

private Map<String, Integer> userToNumber = new HashMap<String, Integer>(10);

private Lock mutex = new ReentrantLock(); // a lock

public void increment() {
try {
mutex.lock();
try {
count = count + 1;
Thread.sleep(50);
Thread thread = Thread.currentThread();
userToNumber.put(thread.getName(), count);
} finally {
mutex.unlock(); // finally block is executed even if an
// exception is thrown
}
} catch (InterruptedException e) {
e.printStackTrace();
} finally {

}

}

public Integer getCount(String name) {
return userToNumber.get(name);
}

}



Note that the locks are unlocked in a finally block as it is executed even if an exception is thrown.

The output for the above 3 options will be something like shown below. The order cannot be guaranteed. But you will get unique numbers assigned for each user.

User-1 value is 1
User-3 value is 2
User-2 value is 3



Q. The following code snippet changes the Counter class to maintain individual counting as in each user counter will be incremented starting from 1. So, the Counter will no longer be the shared resource. The CountingTask class is also modified to loop through each user 2 times as shown below. Is there anything wrong with the code shown below?



The Counter class with individual counts

import java.util.HashMap;
import java.util.Map;

public class Counter {

private Map<String, Integer> userToNumber = new HashMap<String, Integer>(10);

public void increment() {
Thread thread = Thread.currentThread();
if (!userToNumber.containsKey(thread.getName())) {
userToNumber.put(thread.getName(), Integer.valueOf(1)); //op1
} else {
Integer count = userToNumber.get(thread.getName());
if (count != null) {
++count; // op2: increment it
userToNumber.put(thread.getName(), count); //op3
}
}

}

public Integer getCount(String name) {
return userToNumber.get(name);
}
}


The counting task that repeats twice for each user

public class CountingTask implements Runnable {

private Counter counter;

public CountingTask(Counter counter) {
super();
this.counter = counter;
}

@Override
public void run() {

for (int i = 0; i < 2; i++) {
counter.increment();
Thread thread = Thread.currentThread();
System.out.println(thread.getName() + " value is "
+ counter.getCount(thread.getName()));
}
}

}


A. If each user will be accessed by only one thread, then the above code is thread-safe because each user will be operating on his/her data. So, only one thread will access the map entry for User-1, and so on. But, what happens if User-3 has two threads created as shown below.

The Thread 3 and 4 are User 3. In this scenario, the above code is not thread safe, and it needs to be made atomic with one of the three options discussed above. It can be quite dangerous to assume that one user will be accessed only by one thread. What if in the future, additional threads are added to improve performance per user?

public class CountingManager {

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

Counter counter = new Counter(); // create an instance of the Counter
CountingTask task = new CountingTask(counter); // pass the counter to the runnable CountingTask


//Create 10 user threads (non-daemon) from the main thread that share the counter object
Thread thread1 = new Thread(task, "User-1");
Thread thread2 = new Thread(task, "User-2");
Thread thread3 = new Thread(task, "User-3"); //user 3
Thread thread4 = new Thread(task, "User-3"); //User 3


//start the threads
thread1.start();
thread2.start();
thread3.start();
thread4.start();


//observe the racing conditions in the output

}

}


If you don't perform the operations 1 to 3 atomically (i.e. as a unit), you will get an out put like

User-1 value is 1
User-1 value is 2
User-3 value is 2
User-3 value is 3
User-3 value is 2
User-3 value is 4
User-2 value is 1
User-2 value is 2



As you can see, the User-3 has the value 2 repeated twice and value 1 is missing. If you apply the one of the options outlined above, you will get an output like

User-1 value is 1
User-1 value is 2
User-3 value is 1
User-3 value is 2
User-2 value is 1
User-2 value is 2
User-3 value is 3
User-3 value is 4


Hence, the operations 1-3 need to be made atomic if accessed concurrently by multiple threads. Those three operations are

1. storing the initial value
2. incrementing the counter
3. storing the incremented value

Spring Hibernate Java multi-threading interview questions and answers - continuation

This is the continuation from Java multi-threading questions and answers 

Q. Why synchronization is important? 
A. Without synchronization, it is possible for one thread to modify a shared object while another thread is in the process of using or updating that object’s value. This often causes dirty data and leads to significant errors. The disadvantage of synchronization is that it can cause deadlocks when two threads are waiting on each other to do something. Also synchronized code has the overhead of acquiring lock, which can adversely affect the performance. 



Q. What is a ThreadLocal class? 
A. ThreadLocal is a handy class for simplifying development of thread-safe concurrent programs by making the object stored in this class not sharable between threads. ThreadLocal class encapsulates non-thread-safe classes to be safely used in a multi-threaded environment and also allows you to create per-thread-singleton.


Q. What is a daemon thread? 
A. Daemon threads are sometimes called "service" or “background” threads. These are threads that normally run at a low priority and provide a basic service to a program when activity on a machine is reduced. An example of a daemon thread that is continuously running is the garbage collector thread. The JVM exits whenever all non-daemon threads have completed, which means that all daemon threads are automatically stopped. To make a thread  as a daemon thread in Java

myThread.setDaemon(true);

The JVM always has a main thread as default. The main thread is always non-daemon. The user threads are created from the main thread, and by default they are non-daemon. If you want to make a user created thread to be daemon (i.e. stops when the main thread stops), use the setDaemon(true) as shown above.

Q. How can threads communicate with each other? How would you implement a producer (one thread) and a consumer (another thread) passing data (via stack)?
A. The wait( ), notify (), and notifyAll( ) methods are used to provide an efficient way for threads to communicate with each other. This communication solves the ‘consumer-producer problem’. This problem occurs when the producer thread is completing work that the other thread (consumer thread) will use.

Example: If you imagine an application in which one thread (the producer) writes data to a file while a second thread (the consumer) reads data from the same file. In this example the concurrent threads share the same resource file. Because these threads share the common resource file they should be synchronized.  Also these two threads should communicate with each other because the consumer thread, which reads the file, should wait until the producer thread, which writes data to the file and notifies the consumer thread that it has completed its writing operation.

Let’s look at a sample code where count is a shared resource. The consumer thread will wait inside the consume( ) method on the producer thread, until the producer thread increments the count inside the produce( ) method and subsequently notifies the consumer thread. Once it has been notified, the consumer thread waiting inside the consume( ) method will give up its waiting state and completes its method by consuming the count (i.e. decrementing the count).





Here is a complete working code example on thread communication.

Note:  A method calls notify( )/notifyAll( ) as the last thing it does (besides return). Since the consume method was void, the notify( ) was the last statement. If it were to return some value, the notify( ) would have been placed just before the return statement.

Q. Why wait, notify, and notifyall methods are defined in the Object class, and not in the Thread class?
A. Every Java Object has a monitor associated with it. The threads using that object can lock or unlock the monitor associated with the object.Wait and notify/notifyAll methods are responsible for acquiring and relinquishing the lock associated with the particular object. Calling wait causes the current thread to wait to acquire the lock of the Object, and calling notify/notifyAll relinquishes the lock and notify the threads waiting for that lock.


Q. What does join( ) method do?
A. t.join( ) allows the current thread to wait indefinitely until thread “t” is finished.  t.join (5000) allows the current thread to wait  for thread “t” to finish but does not wait longer than 5 seconds.

try {
t.join(5000); //current thread waits for thread “t” to complete but does not wait more than 5 sec
if(t.isAlive()){
//timeout occurred. Thread “t” has not finished
}
else {
//thread “t” has finished
}
}


For example, say you need to spawn multiple threads to do the work, and continue to the next step only after all of them have completed, you will need to tell the main thread to wait. this is done with thread.join() method.




Here is the RunnableTask. The task here is nothing but sleeping for 10 seconds as if some task is being performed. It also prints the thread name and timestamp as to when this task had started

import java.util.Date;

public class RunnableTask implements Runnable {

@Override
public void run() {
Thread thread = Thread.currentThread();
System.out.println(thread.getName() + " at " + new Date());
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}

}



The taskmanager manages the tasks by spawing multiple user threads from the main thread. The main thread is always created by default. The user threads 1-3 are run sequentially, i.e. thread-2 starts only after thread-1 completes, and so on. The user threads 4-6 start and executes concurrently.



public class TaskManager {


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

RunnableTask task = new RunnableTask();


//threads 1-3 are run sequentially
Thread thread1 = new Thread(task, "Thread-1");
Thread thread2 = new Thread(task, "Thread-2");
Thread thread3 = new Thread(task, "Thread-3");


thread1.start(); //invokes run() on RunnableTask
thread1.join(); // main thread blocks (for 10 seconds)
thread2.start(); //invokes run() on RunnableTask
thread2.join(); // main thread blocks (for 10 seconds)
thread3.start(); //invokes run() on RunnableTask
thread3.join(); // main thread blocks (for 10 seconds)


Thread thread4 = new Thread(task, "Thread-4");
Thread thread5 = new Thread(task, "Thread-5");
Thread thread6 = new Thread(task, "Thread-6");


thread4.start(); //invokes run() on RunnableTask
thread5.start(); //invokes run() on RunnableTask
thread6.start(); //invokes run() on RunnableTask


}


}


Notice the times of the output. There is a 10 second difference bewteen threads 1-3. But Threads 4-6 started pretty much the same time.

Thread-1 at Fri Mar 02 16:59:22 EST 2012
Thread-2 at Fri Mar 02 16:59:32 EST 2012
Thread-3 at Fri Mar 02 16:59:42 EST 2012
Thread-4 at Fri Mar 02 16:59:47 EST 2012
Thread-6 at Fri Mar 02 16:59:47 EST 2012
Thread-5 at Fri Mar 02 16:59:47 EST 2012



Q. If 2 different threads hit 2 different synchronized methods in an object at the same time will they both continue? 
A. No. Only one thread can acquire the lock in a synchronized method of an object. Each object has a synchronization lock. No 2 synchronized methods within an object can run at the same time. One synchronized method should wait for the other synchronized method to release the lock.   This is demonstrated here with method level lock. Same concept is applicable for block level locks as well.





Q. Explain threads blocking on I/O?
A. Occasionally threads have to block on conditions other than object locks. I/O is the best example of this. Threads block on I/O (i.e. enters the waiting state) so that other threads may execute while the I/O operation is performed. When threads are blocked (say due to time consuming reads or writes) on an I/O call inside an object’s synchronized method and also if the other methods of the object are also synchronized then the object is essentially frozen while the thread is blocked.

Be sure to not synchronize code that makes blocking calls, or make sure that a non-synchronized method exists on an object with synchronized blocking code. Although this technique requires some care to ensure that the resulting code is still thread safe, it allows objects to be responsive to other threads when a thread holding its locks is blocked.



Q. If you have a circular reference of objects, but you no longer reference it from an execution thread, will this object be a potential candidate for garbage collection?
A. Yes. Refer diagram below.


Q. Which of the following is true?

a) wait( ), notify( ) ,notifyall( ) are defined as final & can be called only from within a synchronized method
b) Among wait( ), notify( ), notifyall( ) the wait() method only throws IOException
c) wait( ),notify( ),notifyall( ) & sleep () are methods of object class

A. a and b. The c is wrong because the sleep method is a member of the Thread class.The other methods are members of the Object class.

Q. What are some of the threads related problems and what causes those problems?
A. DeadLock, LiveLock, and Starvation.

Deadlock occurs when two or more threads are blocked forever, waiting for each other. This may occur when two threads, each having a lock on the same resource, attempt to acquire a lock on the other's resource. Each thread would wait indefinitely for the other resource to release the lock, unless one of the user processes is terminated. The thread deadlock can occur in conditions such as:

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

Starvation and livelock are much less common a problem than deadlock, and it occurs when all threads are blocked, or are otherwise unable to proceed due to unavailability of required resources, and the non-existence of any unblocked thread to make those resources available.

The thread livelock can occur in conditions such as:

  • all the threads in a program are stuck in infinite loops.
  • all the threads in a program execute Object.wait(0) on an object with zero parameter. The program is live-locked and cannot proceed until one or more threads call Object.notify( ) or Object.notifyAll() on the relevant objects.  Because all the threads are blocked, neither call can be made.

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. The thread starvation can occur in conditions such as:

  • one thread cannot access the CPU because one or more other threads are monopolizing the CPU.
  • setting thread priorities inappropriately. A lower-priority thread can be starved by higher-priority threads if the higher-priority threads do not yield control of the CPU from time to time.  

Q. What happens if you call the run( ) method directly instead of via the start method?
A. Calling run( ) method directly just executes the code synchronously (in the same thread), just like a normal method call. By calling the start( ) method, it starts the execution of the new thread and calls the run( ) method. The start( ) method returns immediately and the new thread normally continues until the run( ) method returns. So, don't make the mistake of calling the run( ) method directly.

Note:  These Java interview questions and answers are extracted from my book "Java/J2EE Job Interview Companion".

If you liked the above Java multi-threading questions and answers, you will like the following link, which has a little more advanced coding questions on multi-threading.



    If you work a lot with multi-threading, and want to really master multi-threading, then my favorite book is:



    Spring Hibernate Article: Scenarios and solutions for better concurrency and thread safety part-2 CountDownLatch and CyclicBarrier

    There are other real life scenarios where the java.util.concurrent package with the following classes can be put to great use.
    • CountDownLatch
    • CyclicBarrier
    Here are some real life scenarios discusssed below to make use of the above classes.

    Scenario: A main thread creates 3 database connections and assigns each of those connection to 3 different child threads that are spawned from the main thread. The main thread must wait while all the child threads are completed and then close all the database connections. So, how will you accomplish this?

    Solution: This where the CountDownLatch comes in handy as you already know that there are finite (i.e 3) number of threads.  CountDownLatch can be used by the main thread to wait on the child threads. A CountDownLatch will be created with 3 being the count.

    CountDownLatch countDownLatch = new CountDownLatch(MAX_THREADS);

    The main thread will spawn new threads and wait on the count to reach 0 with the awit( ) method.

    countDownLatch.await();

    As the each child thread process within the run( ) method, as the child thread completes processing, the count can be decremented with

    countDownLatch.countDown(); 





    Here is a simplified example where the worker threads wait for all the other worker threads to start with the startSignal and the main thread waits for all the worker threads to complete with a stopSignal as illustrated in the above diagram . Firstly, define a worker thread class.


    import java.util.concurrent.CountDownLatch;

    public class Worker implements Runnable {

    private CountDownLatch startLatch;
    private CountDownLatch stopLatch;

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

    @Override
    public void run() {
    try {
    startLatch.await(); // wait until the latch has counted down to zero
    System.out.println("Running: " + Thread.currentThread().getName());
    } catch (InterruptedException ex) {
    ex.printStackTrace();
    }
    finally {
    //count down to let the main thread to continue once the count reaches 0 from MAX_THREADS (i.e. 5)
    stopLatch.countDown();
    }
    }

    }


    Finally, define the WaitForAllThreadsToStart class that creates the worker thread.

    import java.util.concurrent.CountDownLatch;

    public class WaitForAllThreadsToStart {

    private static final int MAX_THREADS = 3;

    public static void main(String[] args) throws Exception {
    CountDownLatch startSignal = new CountDownLatch(1); //count down from 1 to 0
    CountDownLatch stopSignal = new CountDownLatch(MAX_THREADS); // count down from 3 to 0

    System.out.println("The main thread is going to spawn " + MAX_THREADS + " worker threads.....");
    for (int i = 1; i <= MAX_THREADS; i++) {
    Thread t = new Thread(new Worker(startSignal,stopSignal), "thread-" + i);
    Thread.sleep(300);
    t.start();
    System.out.println("Started: " + t.getName() + " but waits for other threads to start.");
    }

    //count down the start signal from 1 to 0, so that the waiting worker threads can start executing
    startSignal.countDown();
    System.out.println("worker threads can now start executing as all worker threads have started.....");
    try{
    stopSignal.await(); // wait for the worker threads to complete by counting down the stopLatch
    } catch (InterruptedException ex){
    ex.printStackTrace();
    }
    System.out.println("finished executing the worker threads and the main thread is continuing.");
    System.out.println("The main thread can execute any task here.");

    }
    }


    The output will like:

    The main thread is going to spawn 3 worker threads.....
    Started: thread-1 but waiting for other threads to start.
    Started: thread-2 but waiting for other threads to start.
    Started: thread-3 but waiting for other threads to start.
    worker threads can now start executing as all worker threads have started.....
    Running: thread-1
    Running: thread-3
    Running: thread-2
    finished executing the worker threads and the main thread is continuing.
    The main thread can execute any task here.


    Scenario: What if the above scenario has a specific requirement where the 3 children threads need to wait between each other? For example, if each of the 3 threads need to perform 2 tasks. Before the task 2 can be started by a thread, all the 3 child threads must finish task 1. The task 1 can be reading data from the database and task 2 could be performing some computation and finally these computations need to be consolidated and written back by a single thread.

    Solution:  A CyclicBarrier can be used if the number of children threads are know upfront and to implement waiting amongst child threads until all of them finish.  This is useful where parallel threads need to perform a job which requires sequential execution. It has methods like cyclicBarrier.await( ) and cyclicBarrier.reset( );




    Here is the simplified code to improve understanding. Firstly the WorkerTask thread.


    import java.util.concurrent.BrokenBarrierException;
    import java.util.concurrent.CyclicBarrier;

    public class WorkerTask implements Runnable {

    private CyclicBarrier barrier;

    public WorkerTask(CyclicBarrier barrier) {
    this.barrier = barrier;
    }

    @Override
    public void run() {
    String threadName = Thread.currentThread().getName();
    try {
    System.out.println(threadName + " is now performing Task-A");
    barrier.await(); //barrier point for all threads to finish Task-A

    System.out.println(threadName + " is now performing Task-B");
    barrier.await(); //barrier point for all threads to finish Task-B

    } catch (BrokenBarrierException ex) {
    ex.printStackTrace();
    } catch (InterruptedException e) {
    e.printStackTrace();
    }
    }
    }


    Now, the test class that creates the worker threads to perform Tasak-A and Task-B, and the barrier thread for consolidation work.

    import java.util.concurrent.CyclicBarrier;

    public class WaitForBarrierPoint {

    private static final int MAX_THREADS = 3;
    private static final int NO_OF_TASKS = 2; //Task-A and Task-B

    private static int taskCount = 0;

    //new worker thread that monitors the barrier condition, i.e.
    //MAX_THREADS that complete a task, and performs the consolidation task.
     //This is an anonymous inner class in action
    private static CyclicBarrier cb = new CyclicBarrier(MAX_THREADS, new Runnable() {

    @Override
    public void run() {
    System.out.println("All " + MAX_THREADS + " threads have reached the barrier point.");
    ++taskCount;

    //the consolidation job starts only after both tasks are completed.
    if(taskCount == NO_OF_TASKS) {
    System.out.println("The consolidation job can start now .... ");
    }
    }
    });


    public static void main(String[] args) {
    Thread t = null;
    //create 3 worker threads
    for (int i = 1; i <= MAX_THREADS; i++) {
    t = new Thread(new WorkerTask(cb), "Thread-" + i);
    t.start();
    }

    System.out.println("The main thread ends here.");
    }

    }


    Q. Why is it called a cyclic barrier?
    A. Because it acts as a barrier point for a number of worker threads to wait for each other to complete their tasks. The barrier is called cyclic because it can be re-used after all the waiting worker threads are released for the next barrier point.

    A barrier is constructed with the following arguments to a constructor.
    • the number of threads that will be participating in the parallel operation.
    • an optional, amalgamation or consolidation  routine to be run at the end of each step or iteration.
    At each step (or iteration) of the operation:
    • each thread carries out its portion of the work to complete that step.
    • after doing its portion of the work, each thread calls the barrier's await ( ) method.
    • the await( ) method returns only when 
              -- all 3 threads have called await( ).
              -- the amalgamation or consolidation  method has run (the barrier calls this on the last thread to call
                  await( ) before releasing the awaiting threads).

    if any of the 3 threads is interrupted or times out while waiting for the barrier, then the barrier is "broken" and all other waiting threads receive a BrokenBarrierException. This will  propagate to all threads and for the other steps to halt, or for the steps to be interrupted externally by interrupting just one of the threads.

    Q. So, when to use a CountDownLatch and when to use a  CyclicBarrier?
    A. A CountDownLatch is initialized with a counter. Threads can then either count down on the latch or wait for it to reach 0. When the latch reaches 0, all waiting threads can resume.

    If you want a set of threads to repeatedly meet at a common point, you are better served by using a CyclicBarrier. For example, start a bunch of threads, meet, do some stuff like data consolidation or amalgamation, meet again, validate some assertions, and do this repeatedly.

    A given CountDownLatch can only be used once, making it inconvenient for operations that occur in steps, with intermediate results from the different threads needing to be consolidated between steps. The CountDownLatch also doesn't explicitly allow one thread to tell the others to "stop waiting", which is sometimes useful, for example, if an error occurs in one of the threads.

    The CyclicBarrier is generally more useful than CountDownLatch in scenarios where:
    • a multithreaded operation occurs in steps or iterations, and
    • a single-threaded operation is required between steps/iterations, for example, to combine the results of the previous multithreaded steps.

    Stay tuned for Semaphores and Atomic classes in the next part.

    Spring Framework Handling Concurrent modifications in Java



    There are scenarios where you need to deal with concurrent modifications in Java. Here are 2 scenarios that I can currently think of.

    Scenario 1: Looping through a list of items and removing an item in the list could lead to "ConcurrentModificationException". Here is an example.

    Code that throws an Exception:


     private void removeDetailSummaryRecordsWithAllZeroAmounts(CashForecastSummaryVO cfVo)
    {
    List<cashforecastsummaryaccountvo> accounts = cfVo.getAccounts();
    for (CashForecastSummaryAccountVO cfAcctVO : accounts)
    {
    List<cashforecastsummaryrecordvo> summaryRecords = cfAcctVO.getSummaryRecords();

    for (CashForecastSummaryRecordVO recordVO:summaryRecords)
    {
    if (recordVO.getRecordtype() == RecordType.DETAILS)
    {
    List<bigdecimal> amounts = recordVO.getAmounts();
    boolean foundNonZero = false;
    for (BigDecimal amount : amounts)
    {
    if (BigDecimal.ZERO.compareTo(amount) != 0)
    {
    foundNonZero = true;
    }
    }

    if (!foundNonZero)
    {
    summaryRecords.remove(recordVO); // throws aoncurrentModificationException
    }
    }
    }
    }
    }


    Code that fixes the above issue: Using an iterator and remove from the iterator to prevent the exception.


     private void removeDetailSummaryRecordsWithAllZeroAmounts(CashForecastSummaryVO cfVo)
    {
    List<cashforecastsummaryaccountvo> accounts = cfVo.getAccounts();
    for (CashForecastSummaryAccountVO cfAcctVO : accounts)
    {
    List<cashforecastsummaryrecordvo> summaryRecords = cfAcctVO.getSummaryRecords();
    Iterator<cashforecastsummaryrecordvo> it = summaryRecords.iterator(); // get the iterator
    CashForecastSummaryRecordVO recordVO = null;
    while (it.hasNext())
    {
    recordVO = it.next();
    if (recordVO.getRecordtype() == RecordType.DETAILS)
    {
    List<bigdecimal> amounts = recordVO.getAmounts();
    boolean foundNonZero = false;
    for (BigDecimal amount : amounts)
    {
    if (BigDecimal.ZERO.compareTo(amount) != 0)
    {
    foundNonZero = true;
    }
    }

    if (!foundNonZero)
    {
    it.remove(); // an iterator is used
    }
    }
    }
    }
    }


    Scenario 2: Two users try to modify the same record in the database. In this scenario, you want one modification to go through and the other modification to notify the user as shown below.

    "This record was not updated as the record you are trying to update has been updated by another user. Try refreshing your data, and update again."

    This will require a number of steps.

    Step 1: You would require a "version number" or a "timestamp"  column in the database table to detect concurrent modifications.

    Step 2: When a record is initially read, the time stamp or version number also read.



    @Override
    public List<AdjustmentDetail> getAdjustmentRecords(final AdjustmentCriteria criteria)
    {
    String sql = "select a.detailid, a.portfolioCd, a.accountCd, a.PositionIndicator, a.cashValue, TmStamp = convert(int,substring(a.Timestamp,5,4))" +
    "from AdjustmentDetail a " +
    "Where a.portfoliocd = ? " +
    "and a.valuationDttm = ? " +
    "and a.inactiveFlag = 'N' ";

    List<Object> parametersList = new ArrayList<Object>();
    parametersList.add(criteria.getPortfolioCode());
    parametersList.add(criteria.getValuationDate());

    Object[] parameters = parametersList.toArray(new Object[parametersList.size()]);

    List<AdjustmentDetail> adjustments = jdbcTemplateSybase.query(sql, parameters,
    new RowMapper<AdjustmentDetail>()
    {
    public AdjustmentDetail mapRow(ResultSet rs, int rowNum) throws SQLException
    {
    AdjustmentDetail record = new AdjustmentDetail();
    record.setDetailId(BigInteger.valueOf(rs.getLong("DetailId")));
    record.setPortfolioCode(criteria.getPortfolioCode());
    record.setAccountcd(rs.getString("accountCd"));
    record.setAmount(rs.getBigDecimal("cashValue"));
    record.setPositionIndicator(rs.getString("PositionIndicator"));
    record.setTimestamp(rs.getInt("TmStamp")); // timestamp to detect any later modifications

    return record;

    }
    });

    return adjustments;

    }


    Step 3: After the record has been modified, when ready to update the record, do a select query first to read the time stamp or version number for the same record to ensure that it has not been modified. if the "timestamp" or the "version number" has changed, you need to throw the above exception and abort modifying the record as it had been modified by another user.



    @Override
    public AdjustmentDetail modifyAdjustment(AdjustmentDetail adjDetail)
    {
    if (adjDetail == null)
    {
    throw new RuntimeException("adjDetail is null");
    }

    int noOfRecords = 0;

    String inactiveFlag;



    try
    {
    //check if the record has been modified.
    Integer adjustmentModifiedTimestamp = getAdjustmentModifiedTimestamp(adjDetail.getDetailId());

    //logic to modify adjustments go here
    //every time the record is modified, the timestamp or version number is incremented.
    }
    catch (Exception e)
    {
    logger.error("Error updating adjustment detail: ", e);
    }

    if (noOfRecords == 0) throw new ValidationException("The adjustment was not updated. It may be the record you are trying to update has been updated by another user. Try refreshing your data and update again.");


    logger.info("No of adjustment details updated = " + noOfRecords);

    return adjDetail;
    }


    now the sample method that retrieves the timestamp.


    //retrieve the timestamp value for the given datialid to detect if it has been modified.
    private Integer getAdjustmentModifiedTimestamp(BigInteger adjustmentDetailId) {

    String sql = "SELECT TmStamp = convert(int,substring(Timestamp,5,4)) from AdjustmentDetail where DetailId = ?";

    List<Object> parametersList = new ArrayList<Object>();
    parametersList.add(cashForecastDetaillId.intValue());

    Object[] parameters = parametersList.toArray(new Object[parametersList.size()]);

    List<Integer> ts = jdbcTemplateSybase.query(sql, parameters, new RowMapper<Integer>() {
    public Integer mapRow(ResultSet rs, int rowNum) throws SQLException {
    Integer tsValue = rs.getInt("TmStamp");
    return tsValue;

    }
    });
    return ts.get(0);
    }

    Spring Hibernate Article: Scenarios and solutions for better concurrency and thread safety part-1 ReadWriteLocks

    Scenario: You need to load  stock exchange security codes from a database and cache them for performance. The security codes need to be refreshed say every 30 minutes. This cached data needs to be populated and refreshed by a single writer thread and read by several reader threads. How will you ensure that your read/write solution is scalable and thread safe?

    Solution:  The java.util.concurrent.locks package provides classes that implement read/write locks where the read lock can be executed in parallel by multiple threads and the write lock can be held by only a single thread. The ReadWriteLock interface maintains a pair of associated locks, one for read-only and one for writing. The readLock( ) may be held simultaneously by multiple reader threads, while the writeLock( ) is exclusive. In general, this implementation improves performance and scalability when compared to the mutex locks (i.e. via synchronized key word) when

    • there are more reads and read duration compared writes and write duration. 
    • It also depends on the system you are running on -- for example multi-core processors for better parallelism. 

    The ConcurrentHashmap is another example where improved performance can be achieved when you have more reads than writes. The ConcurrentHashmap allows concurrent reads and locks only the buckets that are used to modify or insert data.

    Here are a few terminlogies you need to be familiar with in implementing locks.

    Q. What is a reentrant lock?
    A. This can be considered as a replacement for the traditional “wait-notify” method. The basic concept is, every thread needs to acquire the lock before entering in to the critical section and should release it after finishing it. ReentrantLock eliminates the use of “synchronized” keyword to provide better concurrency

    The term reentrant means if a thread enters a second synchronized block protected by a monitor that the thread already owns from , the thread will be allowed to proceed, and the lock will not be released when the thread exits the second (or subsequent) synchronized block, but only will be released when it exits the first synchronized block it entered protected by that monitor. Similarly, when you use reentrant locks, there will be an acquisition count associated with the lock, and if a thread that holds the lock acquires it again, the acquisition count is incremented and the lock then needs to be released twice to truly release the lock.  A writer can acquire the read lock - but the reverse is not true. If a reader tries to acquire the write lock it will never succeed.

    Q. What do you need to watch out for in releasing a lock?
    A. The locks need to be released in a finally block, otherwise if an exception is thrown, the lock might never get released.

    Q. Why would you need a reentrant lock when there is synchronized keyword? How will you favor one over the other?
    A. The reentrant locks are more scalable as it allows concurrent reads. Having said this, the locking classes in java.util.concurrent.lock package are advanced tools for advanced users and specific situations like the scenario discussed above. In general, you should stick with synchronization unless you have a specific need  like
    • the number of reads are far more than the number of writes. 
    • demonstrated evidence through proper performance testing that synchronization in a specific situation is a scalability bottleneck. 
    • specif features like timed lock waits, interruptible lock waits, non-block-structured locks, multiple condition variables, or lock polling are required.

    Q. What are fair and unfair locks?
    A. One of the arguments to the constructor of ReentrantLock is a boolean value that lets you choose whether you want a fair or an unfair lock. A fair lock is one where the threads acquire the lock in the same order they asked for it. In another words, when the write lock is released either the longest-waiting single writer will be assigned the write lock, or if there is a reader waiting longer than any writer, the set of readers will be assigned the read lock. When constructed as non-fair, the order of entry to the lock are not necessarily in the arrival order.
    If the readers are active and a writer enters the lock then no subsequent readers will be granted the read lock until after that writer has acquired and released the write lock. Here is a simplified example of read/write locks.



    Firstly, define the SharedData that gets accessed by multiple reader and writer threads. So, provide proper locks.

    import java.util.ArrayList;
    import java.util.List;
    import java.util.concurrent.locks.ReentrantReadWriteLock;


    public class SharedData<T> {

    private List<Integer> numbers = new ArrayList<Integer>(20);
    private ReentrantReadWriteLock lock = new ReentrantReadWriteLock();

    public List<Integer> getTechnologies() {
    return numbers;
    }

    public void writeData(Integer number) {
    String threadName = Thread.currentThread().getName();
    lock.writeLock().lock(); //acquire a write lock if no other thread has acquired read/write lock
    //only a single thread can write

    System.out.println("threads waiting for read/write lock: " + lock.getQueueLength());
    // This should be always one
    System.out.println("writer locks held " + lock.getWriteHoldCount());
    try {
    numbers.add(number);
    System.out.println(">>>>>" + threadName + " writing: " + number);
    Thread.sleep(2000); // sleep for 2 seconds to demo read/write locks
    } catch (InterruptedException e) {
    e.printStackTrace();
    } finally {
    System.out.println(threadName + " releasing write lock");
    lock.writeLock().unlock(); //lock will be released
    }
    }

    public void readData() {
    String threadName = Thread.currentThread().getName();
    lock.readLock().lock();//acquire a read lock if no other thread has acquired a write lock.
    //concurrent reads allowed.

    System.out.println("threads waiting for read/write lock: " + lock.getQueueLength());
    System.out.println("reader locks held " + lock.getReadLockCount());
    try {
    for (Integer num: numbers) {
    System.out.println("<<<<<<<" + threadName + " reading: " + num);
    }
    Thread.sleep(1000);
    } catch (InterruptedException e) {
    e.printStackTrace();
    }
    finally{
    System.out.println(threadName + " releasing read lock");
    lock.readLock().unlock(); //lock will be released
    }

    }
    }


    Next, define the reader and writer threads.

    public class Reader<T> extends Thread {

    private SharedData<T> sharedData;

    public Reader(SharedData<T> sharedData) {
    this.sharedData = sharedData;
    }

    @Override
    public void run() {
    sharedData.readData();
    }
    }


    public class Writer<T> extends Thread {

    private boolean oddNumber = true;
    private SharedData<T> sharedData;

    public Writer(SharedData<T> sharedData, boolean oddNumber ) {
    this.sharedData = sharedData;
    this.oddNumber = oddNumber;
    }

    @Override
    public void run() {
    for(int i=1; i<=2; i++) {
    if(!oddNumber && i%2 == 0) {
    sharedData.writeData(i);
    }
    else if (oddNumber && !(i%2 == 0)){
    sharedData.writeData(i);
    }
    }
    }
    }


    Finally, the ReadWriteProcessor class that spawns thw worker read and write threads and pass the SharedData to the threads.

    public class ReadWriteProcessor {

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

    SharedData<Integer> data = new SharedData<Integer>();

    //create some writer worker threads
    Writer<Integer> oddWriter = new Writer<Integer>(data, true);
    oddWriter.setName("oddWriter");
    Writer<Integer> evenWriter = new Writer<Integer>(data, false);
    evenWriter.setName("evenWriter");

    //create some reader worker threads
    Reader<Integer> reader1 = new Reader<Integer>(data);
    reader1.setName("reader1");
    Reader<Integer> reader2 = new Reader<Integer>(data);
    reader2.setName("reader2");
    Reader<Integer> reader3 = new Reader<Integer>(data);
    reader3.setName("reader3");

    //start the writer threads
    oddWriter.start();
    Thread.sleep(100);
    evenWriter.start();

    //start the reader threads
    reader1.start();
    reader2.start();
    reader3.start();
    }
    }


    The output will be something like:

    threads waiting for read/write lock: 0
    writer locks held 1
    >>>>>oddWriter writing: 1
    oddWriter releasing write lock
    threads waiting for read/write lock: 3
    writer locks held 1
    >>>>>evenWriter writing: 2
    evenWriter releasing write lock
    threads waiting for read/write lock: 2
    threads waiting for read/write lock: 1
    reader locks held 3
    threads waiting for read/write lock: 0
    reader locks held 3
    reader locks held 2
    <<<<<<<reader1 reading: 1
    <<<<<<<reader2 reading: 1
    <<<<<<<reader3 reading: 1
    <<<<<<<reader2 reading: 2
    <<<<<<<reader1 reading: 2
    <<<<<<<reader3 reading: 2
    reader1 releasing read lock
    reader3 releasing read lock
    reader2 releasing read lock


    There are other real life scenarios where the java.util.concurrent package with the following classes can be put to great use.
    • CountDownLatch
    • CyclicBarrier
    • Semaphore
    • Atomic classes

    The real life scenarios with solution will be discussed in the ensuing parts.

    Java J2EE Spring Java multi-threading interview questions and answers - coding

    The Java multi-threading questions are very popular with the job interviewers as it can be not only hard to grasp, but also concurrency issues are very hard to debug and fix. So, it really pays to have people with the good understanding in this key area. We looked at some basic questions and answers at Java multi-threading questions and answers. Let's look at more coding based questions and answers to build up on what we had learned before.


    Q. Explain how you would get a Thread Deadlock with a code example?
    A. The example below causes a deadlock situation by thread-1 waiting for lock2 and thread-0 waiting for lock1.




    package deadlock;

    public class DeadlockTest extends Thread {

    public static Object lock1 = new Object();
    public static Object lock2 = new Object();

    public void method1() {
    synchronized (lock1) {
    delay(500); //some operation
    System.out.println("method1: " + Thread.currentThread().getName());
    synchronized (lock2) {
    System.out.println("method1 is executing .... ");
    }
    }
    }

    public void method2() {
    synchronized (lock2) {
    delay(500); //some operation
    System.out.println("method1: " + Thread.currentThread().getName());
    synchronized (lock1) {
    System.out.println("method2 is executing .... ");
    }
    }
    }

    @Override
    public void run() {
    method1();
    method2();
    }

    public static void main(String[] args) {
    DeadlockTest thread1 = new DeadlockTest();
    DeadlockTest thread2 = new DeadlockTest();

    thread1.start();
    thread2.start();
    }

    /**
    * The delay is to simulate some real operation happening.
    * @param timeInMillis
    */
    private void delay(long timeInMillis) {
    try {
    Thread.sleep(timeInMillis);
    } catch (InterruptedException e) {
    e.printStackTrace();
    }
    }

    }

    The output will be something like:

    method1: Thread-0
    method1 is executing ....
    method2: Thread-0
    method1: Thread-1
    ---deadlock ----- can't proceed further



    Q. What happens if you restart a thread that has already started?
    A. You will get the following exception


    Exception in thread "main" java.lang.IllegalThreadStateException
    at java.lang.Thread.start(Thread.java:595)
    at deadlock.DeadlockTest.main(DeadlockTest.java:38)



    Q. Can you write a program with 2  threads, in which one prints odd numbers and the other prints even numbers up to 10?
    A. In Java, you can use wait(  ) and notifyAll(  ) to communicate between threads. The code below demonstrates that.




    Firstly, create the thread classes and the main method that creates the thread and run it.

    package multithreading;

    public class NumberGenerator extends Thread {

    private NumberUtility numberUtility;
    private int maxNumber;
    private boolean isEvenNumber;


    public NumberGenerator(NumberUtility numberUtility, int maxNumber, boolean isEvenNumber) {
    this.numberUtility = numberUtility;
    this.maxNumber = maxNumber;
    this.isEvenNumber = isEvenNumber;
    }

    public void run() {
    int i = isEvenNumber == true ? 2 : 1;
    while (i <= maxNumber) {
    if(isEvenNumber == true) {
    numberUtility.printEven(i);
    }
    else {
    numberUtility.printOdd(i);
    }

    i = i + 2;
    }
    }


    public static void main(String[] args) {
    NumberUtility numUtility = new NumberUtility(); //single instance shared by oddGen and evenGen threads
    final int MAX_NUM = 10; 

    //create 2 threads, one to generate odd numbers and the other to generate even numbers
    NumberGenerator oddGen = new NumberGenerator(numUtility, MAX_NUM, false);
    NumberGenerator evenGen = new NumberGenerator(numUtility, MAX_NUM, true);

    oddGen.start(); //start the thread - invokes the run() method on NumberGenerator
    evenGen.start(); //start the thread - invokes the run() method on NumberGenerator

    }

    }

    Next, create the utility class that is used for communicating between the two threads with wait() and notifyAll() methods via synchronized methods.


    package multithreading;

    import static java.lang.System.out;

    public class NumberUtility {

    boolean oddPrinted = false;

    public synchronized void printOdd(int number) {

    while (oddPrinted == true) {
    try {
    wait(); // waits until notified by even thread

    } catch (InterruptedException e) {
    e.printStackTrace();
    }
    }

    out.println("printOdd() " + number);
    oddPrinted = true;
    notifyAll(); //notify all waiting threads

    }

    public synchronized void printEven(int number) {
    while (oddPrinted == false) {
    try {
    wait(); //waits until notified by the odd thread

    } catch (InterruptedException e) {

    }
    }

    oddPrinted = false;
    out.println("printEven() " + number);
    notifyAll(); //notify all waiting threads
    }
    }


    The output will be something like

    printOdd() 1
    printEven() 2
    printOdd() 3
    printEven() 4
    printOdd() 5
    printEven() 6
    printOdd() 7
    printEven() 8
    printOdd() 9
    printEven() 10 


    Note: This a typical example of splitting tasks among threads. A method calls notify/notifyAll( ) as the last thing it does (besides return). Since the printOdd( ) and printEven( ) methods were void, the notifyAll( ) was the last statement. If it were to return some value, the notifyAll( ) would have been placed just before the return statement.

    Q. Write a multi-threaded Java program in which, one thread generates odd numbers and write to a pipe and the second thread generates even numbers and write to another pipe, and a third thread receives the numbers from both the pipes and evaluates if the sum is multiples of 5?

    A. In Unix, a pipe (“|”) operator helps you to redirect output from one command to another. PipedReader and PipedWriter classes in java.io package helps you to do the same. It helps you to redirect the read input into writer seamlessly. In Unix, two different processes on different address spaces can communicate using pipe, but in java two threads on the JVM can communicate using Piped ByteStream/CharacterStream within the same process (i.e same address space)



    Here is the code snippet. The Writer threads responsible for writing odd and even numbers to the respective pipes.

    package multithreading;

    import java.io.IOException;
    import java.io.PipedWriter;

    public class NumberWriter extends Thread {

    private PipedWriter writer;
    private int maxNumber;
    private boolean isEvenNumber;

    public NumberWriter(PipedWriter writer, int maxNumber, boolean isEvenNumber) {
    this.writer = writer;
    this.maxNumber = maxNumber;
    this.isEvenNumber = isEvenNumber;
    }

    public void run() {
    int i = 1;
    while (i <= maxNumber) {
    try {
    if (isEvenNumber && (i % 2) == 0) {
    writer.write(i);
    } else if (!isEvenNumber && i%2 != 0) {
    writer.write(i);
    }
    ++i;
    } catch (IOException e) {
    e.printStackTrace();
    }
    }
    }

    public static void main(String[] args) {
    final int MAX_NUM = 10;

    PipedWriter oddNumberWriter = new PipedWriter();
    PipedWriter evenNumberWriter = new PipedWriter();

    NumberWriter oddGen = new NumberWriter(oddNumberWriter, MAX_NUM, false);
    NumberWriter evenGen = new NumberWriter(evenNumberWriter, MAX_NUM, true);
    NumberReceiver receiver = new NumberReceiver(oddNumberWriter, evenNumberWriter);

    oddGen.start();
    evenGen.start();
    receiver.start();

    }

    }


    The receiver thread that listens to both odd and even number pipes and computes the sum. If the sum is a multiple of 5, it prints the numbers and the sum.

    package multithreading;

    import java.io.IOException;
    import java.io.PipedReader;
    import java.io.PipedWriter;

    public class NumberReceiver extends Thread {

    private PipedReader oddReader;
    private PipedReader evenReader;

    public NumberReceiver(PipedWriter oddWriter, PipedWriter evenWriter) {
    try {
    this.oddReader = new PipedReader(oddWriter);
    this.evenReader = new PipedReader(evenWriter);
    } catch (IOException e) {
    e.printStackTrace();
    }
    }

    public void run() {
    int odd =0, even=0;

    try {
    while (odd != -1) {
    odd = oddReader.read();
    even = evenReader.read();

    if ((odd + even) % 5 == 0) {
    System.out.println("match found " + odd + " + " + even + " = " + (odd + even));
    }
    }

    } catch (IOException e) {
    System.exit(1);
    }


    }
    }


    The output will be something like

    match found 7 + 8 = 15


    Note: The above problem can also be solved with a blocking queue as described in multi-threading with blocking queues questions and answers.

    Java multi-threading interview questions and answers: overview 
    Java multi-threading questions and answers with blocking queue 

    Labels

    .equals = operator abstract class abstract method abstract window toolkit Access Modifiers accessing java beans accessing javabeans action events actionperformed active addition Advanced Advanced Overloading AdvJavaBooks Agile development ajax alive AMQP and Android anonymous class anonymous inner class Ant ant tutorials anti patterns antipatterns Apache Camel api for jsp api for servlet api for servlets api jsp application context application scope application session Apps Architecture are you eligible for the ocmjd certificaiton are you eligible for the scjd certification arithmetic operator arpanet array construction array declaration array initialization array list array to list conversion arraylist arraylist of strings arraylist of types arraylist questions arraylists Arrays arrays in java ask for help assert assert in java assertions assertions in java assignment assignment operator Atlassian attribute visibility authentication authorization autoboxing autounboxing awt AWT Event Handling awt interview questions AWT Layouts awt questions awt questions and answers backed collection backed collections Basic Basics of event handling bean attributes bean properties bean scope Beginner best practices BigData blocked books boxing buffer size bufferedreader bufferedwriter business delegate business delegate pattern calendar case statement casting in java casting interview questions chapter review choosing a java locking mechanism choosing a locking mechanism choosing a thread locking mechanism class inside a method class questions class with no name class without a name classes interview questions Clipboard closing jsp tags code snap coding cohesion collection generics collection interview questions collection methods collection of types collection questions collection searching collection types Collections Collections Framework collections interview questions collections sorting colors in java swings colors in swing command line arguments communication between threads comparable comparator comparison operators compiling java classes computers concurrency example and tutorial config Configuration ConnectionPooling constructor creation constructor interview questions constructor overloading constructors in java containers contents of deployment descriptor contents of web.xml context context scope converting array to list converting list to array core java core java interview core java interview question core java interview questions core java questions core java; core java; object oriented programming CoreJava CoreJavaBooks CORS coupling create threads creating 2 dimensional shapes creating 2D shapes creating a frame creating a jframe creating a thread creating an arraylist creating an inner class creating an interface creating java beans creating java threads creating javabeans creating threads creating threads in java CSS cURL currency current thread determination custom tag library custom taglib custom taglibs custom tags CVS dao dao design pattern dao factory pattern dao pattern data access object data access object pattern data structure and algorithm database date and time tutorial date format dateformat dates deadlock deadlocks debugging Declarations decorator pattern decrement default deleting sessions deploy web app deployment deployment descriptor deployment descriptor contents deployment of web application deserialization deserialize design pattern design pattern interview questions design patterns Designpatterns destory method destroy destroying sessions determining current thread determining the current thread Developer Differences different types of collections display stuff in a frame displaying images displaying images in java swings displaying images in swings displaying text in a component division do while loop doget dohead dopost doput DOS Downloads drawing a line drawing an ellipse drawing circles drawing ellipses drawing lines Drools tutorial eBooks Eclipse Eclipse Tutorial Encapsulation encapsulation in java enhanced for loop entity facade pattern enumerations enumerations in java enums equal to equals equals comparison error and exception error codes error handling in servlets error page event handling in swings event listeners exam prep tips example servlet Examples exception exception handling exception handling in servlets exception handling interview questions exception handling questions Exceptions exceptions in java exceptions in web applications explicit locking explicit locking of objects file file navigation filereader filewriter final class final method FireBug first servlet FIX protocol FIX Protocol interview questions FIX protocol tutorial font fonts for each loop for loop form parameters form values formatting forwarding requests frame frame creation frame positioning frame swings front controller front controller design pattern front controller pattern fundamental.Java FXML Games garbage collection garbage collection interview questions garbage collection questions garbage collector gc gc questions general generic Generics generics collections Geo get get set methods getattribute getting bean property getting form values getting form values in servlet getting scwcd certified getting servlet initialization parameters getting sun certified Google Graphics2D gregorian calendar handling strings in java hash hash map hash table hashcode hashmap hashset hashtable head head request HeadFirst heap heaps hibernate hibernate interview questions hibernate interview questions and answers hibernate questions hibernate questions and answers Hibernate Tutorial HibernateBooks homework How To HTML HTML and JavaScript html form http request http request handling http request header http request methods http request servlet http request type http session httprequest httprequest methods httpservlet httpservlet interview questions httpservlet interview questions with answers httpsession httpsession interview questions httpsession questions HttpSessionActivationListener HttpSessionAttributeListener HttpSessionBindingListener if if else if else block if else statement Image IO implementing an interface Implicit objects increment info inheritance inheritance in java init init method Initialization Blocks inner class inner class inside a method inner classes innerclass installation instanceof instanceof operator IntelliJ interaction between threads interface interface interview interface questions interfaces interfaces in java interfaces interview questions internet history interrupting a thread interrupting threads Interview interview questions interview questions on design patterns interview questions on exception handling interview questions on java collections interview questions on serialization introduction to java threads introduction to jsps introduction to threading introduction to threads invalidating session Investment Banking IO Package iscurrentthread iterator J2EE j2ee api j2ee design pattern j2ee design pattern interview questions j2ee design patterns j2ee hibernate interview questions j2ee history j2ee interview j2ee interview questions j2ee mvc j2ee mvc pattern j2ee programmer j2ee questions j2ee servlet api j2ee session j2ee struts interview questions java java 5 tutorial Java 8 java arrays java assertions java assignments java awt questions java bean java bean scope java beans java beginners tutorial Java career java certification Java Class java collection interview questions and answers java collection tutorial java collections java collections interview questions java constructors java currency Java CV java data base connectivity java database connectivity java database connectivity interview questions and answers java dates java design pattern java design patterns java developer certification Java EE java encapsulation java enums java event listeners java exceptions java formatting java garbage collection java garbage collector java gc java heap Java I/O java inheritance java input output Java Interface Java Interview Java Interview Answers Java Interview Questions Java Introduction java io java IO tutorial java iterator java jdbc Java JSON tutorial Java Key Areas java lists java literals java locks nested Java Media Framework java methods java multithreading Java multithreading Tutorials java nested locks java networking tutorial java numbers Java Objects java operators java overloading java parsing Java Programming Tutorials java race conditions java regex java regular expressions Java resume java scjp java searching java serialization java server pages java server pages api java server pages questions java spring interview questions. j2ee spring interview questions java stack java strings java swing java swing event listeners java swing frame java swing images java swings java swings images java thread explicit locking java thread lock scope java thread locking java thread locking mechanism java thread locking objects java threads java threads race condition java tips java tokenizing Java Tools Java Tutorial java ui questions Java Utilities java variables java wrappers Java xml tutorial java.lang java8 javabean javabean accessing javabean scope JavaBeans javac JavaEE JavaFX JavaFX 3D JavaFX 8 JavaOne JavaScript JavaTips JDBC jdbc driver jdbc example jdbc interview questions jdbc interview questions and answers jdbc interview questions with answers jdbc sample code JDBC Tutorial jdbc type 1 driver jdbc type 2 driver jdbc type 3 driver jdbc type 4 driver Jdeveloper JDK JDK8 JEE Tutorial jframe jframe creation jframe position jframe positioning JIRA JMeter JMS JMX join() joining threads JPA JQuery JS JSF JSF Tutorial JSONP JSP jsp and java beans jsp and servlets jsp and xml jsp api jsp code jsp compilation jsp conversion jsp directives jsp error page jsp error page directive jsp implicit objects jsp interview jsp interview questions jsp introduction jsp intvw questions jsp life jsp life cycle jsp life-cycle jsp lifecycle jsp page directive jsp questions jsp sample jsp scripting jsp scriptlets jsp servlets jsp summary jsp synopsis jsp tag libraries jsp tag library jsp taglib jsp tags jsp technology jsp to servlet jsp to servlet conversion jsp translation jsp usage jsp usebean jsp xml tags jsp xml tags usage jsp-servlet jsp:getProperty jsp:setProperty jsp:usebean jsps JSTL JUnit testing keyword synchronized keyword volatile Keywords Lambda Expressions Learning libraries life cycle life cycle of a jsp life cycle of a servlet life cycle of a thread life cycle of jsp life cycle of threads lifecycle of a thread linked list linkedhashmap linkedhashset linkedlist linux List listeners lists Literals locale lock manager pattern lock scope locking objects using threads log Logging logging errors logical and logical operators logical or loops loosely coupled making an arraylist making threads sleep making threads sleep for time MapReduce maps maps usage Maven Maven Tutorial max priority member access method arguments method local inner class method overloading method overriding method return types methods creating classes min priority Miscellaneous mobile mock exam model view controller model view controller design pattern model view controller pattern Multi Threading Multi-threading multiple threads multiplication multithreading multithreading in java multithreading interview questions multithreading questions mvc mvc design pattern mvc pattern MyEclipse mysql nested java lock nested java locks nested java thread locks nested locks nested thread locks NetBeans Networking new news nio NonAccess Modifiers norm priority normal inner class Normalization not equal to Notepad notify notifyall number format numberformat numbers object comparison object notify object orientation object oriented object oriented programming Object Oriented Programming in java objects interview questions ocmjd certification ocmjd certification eligibility OO OO Java oops OpenCSV OpenCV opening jsp tags OpenJDK OpenJFX Operators or Oracle Oracle ADF Mobile Oracle Certified Exams oracle certified master java developer oracle database ORM other topics out overloading overloading constructors overloading in java overriding page page directive page scope parsing passing variables passing variables to methods performance Platform Playing with Numbers points to remember polymorphism positioning a frame post practice exam Primitive Casting primitive variables printwriter priority queue priority queues priorityqueue priorityqueues private processing form values Products programming Projects protected public put questions questions on garbage collection questions on java strings queue quick recap quick review race conditions read objects from stream reading http request header RealTime_Tips redirecting to another servlet redirection reference reference variable casting reference variables Refreshing Java regex Regular Expressions regular inner class relational operators reminder request request dispatcher request forwarding request header request object. httpservletrequest request scope requestdispatcher response RESTClient RESTful retrieving values from session return error codes return types returning values runnable runnable interface running running java programs RUP sample jsp sample questions sample questions scwcd sample servlet scanner Scene Builder scjd certification scjd certification eligibility requirements scjp SCJP Certification scjp exam scjp exam questions scjp exam sample questions scjp questions scjp test scjp test questions scope scope of java locks scope of java thread locks scope of locks scripting in jsp scriptlet tags scriptlets scriptlets in jsp pages scwcd scwcd certification scwcd certification practice exam scwcd exam scwcd exam questions scwcd jsp summary scwcd mock exam scwcd mock exam answers scwcd practice exam scwcd practice test scwcd questions scwcd test SDLC searching searching arrays searching collections searching in java searching treemap searching treesets security self assement self assement scwcd self assessment scjp self test self test scjp self test scwcd send error method senderror method sending error code to browser serialization serialization in java serialization interview questions Serialization on Swing serialization questions service service method servlet servlet and forms servlet and jsp servlet api servlet attributes servlet code servlet container servlet context servlet error handling servlet exception handling servlet handling http request servlet initialization servlet initialization parameters servlet interview servlet interview questions servlet interview questions with answers servlet intvw questions servlet life cycle servlet lifecycle servlet questions servlet questions with answers servlet request servlet request dispatcher servlet request type servlet skeleton servletcontext servletcontextevent servletrequest Servlets servlets and jsps servlets api servlets details servlets request handling session session clean up session event listeners session facade pattern session interview questions session invalidation session listeners session management session questions session scope session timeout session tracking through url rewriting set collections set status method setattribute sets setstatus method setting bean property setting request type short circuit operators Singleton sleep sleeping threads soapUI Software Installation sorting sorting arraylist sorting arrays sorting collections special collections special inner classes split spring spring and hibernate interview questions spring batch Spring Core Spring Framework Spring Integration spring interview questions Spring JDBC Spring MVC Spring security Spring tutorial SQL SQL and database tutorial examples SQL Tutorial SSL stack stacks stacks and heaps static static class static declaration static imports static inner static inner class static method Static variable stopped stopping a thread stopping thread stopping threads Stored Procedure storing values in session Streams strictfp StrictMath string string buffer string builder string class string formatting String Handling string interview questions string manupulation string questions string tokenizer stringbuffer stringbuffer questions stringbuilder Strings strings in java struts Struts 1 Struts 1.2 Struts 2 struts framework interview questions struts interview questions struts interview questions with answers struts mvc interview questions struts questions Struts2 StrutsBooks submitting request subtraction Sun Certification sun certified java developer Sun Certified Java Programmer swing swing action performed swing and colors Swing Components swing event handling swing event listeners swing events Swing Hacks swing images Swing Look And Feels swings swings frame switch block switch case block switch case statement Sybase Sybase and SQL Server synchronization synchronized code synchronized keyword synchronized method System Properties tag lib tag library tag-lib taglibs tags TDD Technical Blogging ternary operator Test Driven Development test scjp Testing the context the session the volatile keyword thread thread class thread deadlocks thread interaction thread interruption thread life cycle thread lifecycle thread lock scope thread locks thread notify thread priorities thread race conditions race conditions in threads thread sleep thread states thread stoppage thread stopping thread synchronization thread syncing thread yield Threads threads in java threads interview questions threads life cycle threads questions tibco tightly coupled tips tips and tricks tips.FXML tokenizing Tomcat Tools toString transitions treemap treeset tricks Tricks Bag try catch try catch finally. finally block Tutorial type casting in java ui programming with java swings UML unboxing unit testing unix url rewriting use bean usebean using a arraylist using collections using colors using colours using command line arguments using different fonts using expressions using font using fonts using fonts in swings using hashmap using http session using httpsession using iterator using java beans in jsp using javabean in jsp using javabeans in jsp using javac using lists using maps using request dispatcher using scriptlets using session persistense using sets using special fonts using system properties using the jsp use bean using treeset using use bean Using Variables using volatile Using Wrappers using xml in jsp Util pack value object value object design pattern value object pattern var-args varargs Variable Arguments Variables vector vector questions vectors visibility vo pattern volatile volatile keyword volatile variables wait method waiting web app exception handling web app interview web application deployment web application exceptions web application scope web application security web component developer web component developer certification web context web context interfaces web context listeners web interview questions web security web server web servers Web services web.xml web.xml deployment webapp log weblogic website hacking website security what are threads what is a java thread what is a thread what is thread while loop windows windows 8 wrapper classes wrappers write objects to stream WSAD xml xml and jsp xml tags xslt yield()