Interview Questions

Thread & Schedulers

Java Program - ThreadSafe Circular Queue

The following is a basic thread safe implementation of a circular queue of user-specified size using a simple array. It contains routines to initialize(), enqueue() and dequeue() the queue.

/**
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS''
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS
 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR

Java Executor Service

The following code illustrates the usage of handling multiple threads using ExecutorService and Callable Interface.
The Callable Interface is similar to Runnable interface, except that it has following call() method instead of run().

 V call() throws Exception;

The major difference is call() method returns an object as a result of executing the thread and run() ( in Runnable Interface) method doesn't return.

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;

Java Thread Synchronization

/**
 *  Print even/odd numbers sequentially using two different threads
 */

public class ThreadSequence {

        public static ThreadSequence tdSeq = new ThreadSequence();

        boolean avail = true;

        public ThreadSequence() {
       
        }

       
        public static void main(String[] args) {
               

                Thread one = new Thread(new MyThreadOdd());
                Thread two = new Thread(new MyThreadEven());
                two.start();
                one.start();

        }

}

class MyThreadOdd implements Runnable {

        public void run() {
                for (int i = 1; i <= 20; i += 2)

                {

Java Producer Consumer Model using Threads

Here is a simple example to illustrate Producer - Consumer Model using Java Threads.

public class Producer implements Runnable
{

        private static int      count   = 0;

        @Override
        public void run()
        {
                while (true)
                {
                        synchronized (Market.productList)
                        {

                                while (!(Market.productList.size() >= 0))
                                {
                                        System.out.println("entered while" + Market.productList.size());
                                        try
                                        {
                                                Market.productList.wait();
                                        }
                                        catch (InterruptedException e)
                                        {
                                                e.printStackTrace();
                                        }
                                }

Java - Thread scheduling using Scheduled Thread Pool Executor

The below Java class demonstrates the periodic scheduling of Threads using Scheduled Thread Pool Executor.

/**
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS''
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE IS DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS
 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF

Java Timer

In this section lets discuss about how to use Timer Api in java.

In many scenarios there may be a need to run a task in repeated time interval. Java
provides a simple api to handle this case using Timer api. The code for executing a Timer task is very simple as follows

Timer t = new Timer();
t.schedule(TimerTask task,long delay,long period);

Java ThreadPool Executor

In this section , lets discuss about how to run multiple threads and manage the same using java threadpoolexecutor.

First of all lets see how to run a simple thread in java

Simple Thread

package in.techdive.java.examples;

public class MyThread implements Runnable
{
    public void run()
    {
        System.out.println("Thread execution is completed....");
    }
}

public class MainThread
{
    public MainThread()
    {
    }

    public static void main(String[] args)
    {
        Thread tD = new Thread(new MyThread());
        tD.start();
    }
}