Thursday, July 4, 2013

Threads: Producer and Consumer Problem

I was thinking to improve my threading fundamentals, so I planned to make few notes for myself that will assist me in future (Obviously at the time of Interviews). This post is a sticky notes post for me.

Problem Statement
The producer–consumer problem (also known as the bounded-buffer problem) is a classic example of a multi-process synchronization problem. The problem describes two processes, the producer and the consumer, who share a common, fixed-size buffer used as a queue. The producer's job is to generate a piece of data, put it into the buffer and start again. At the same time, the consumer is consuming the data (i.e., removing it from the buffer) one piece at a time. The problem is to make sure that the producer won't try to add data into the buffer if it's full and that the consumer won't try to remove data from an empty buffer.

Solution
Producer and consumer should produce and consume some resource. For the simplicity purpose I am taking minimalist object in the Information object.

package com.thread.problem;
public class Information {
                private String message;
                private boolean isAvailToWrite = false;
                public boolean isAvailable(){
                                return isAvailToWrite;
                }

                public boolean isUnavailable(){
                                return !isAvailToWrite;
                }

                public void put(String msg) throws InterruptedException{
                                synchronized (this) {
                                                while(isUnavailable()){
                                                                System.out.println("Producer will wait now.");
                                                                wait();
                                                }
                                                message = msg;
                                                isAvailToWrite = true;
                                                notify();
                                }
                }

                public String get() throws InterruptedException{
                                synchronized (this) {
                                                while(isAvailable()){
                                                                System.out.println("Consumer will wait now.");
                                                                wait();
                                                }
                                                isAvailToWrite = false;
                                                notify();
                                                return message;
                                }
                }

}

Information class has 4 methods.

isUnavailable and isAvailable are providing the information whether the Information class can accept more data or provide any data.

put and get are synchronized method, which are setting or retrieving data from the Information object.
In case of get request, if data is not available, then current running thread will go to wait state, and wait until put operation is not performed on the Information object. It holds true for put operation as well.

Now information object must be produced and consumed with different threads. So we will need producer thread to produce information object, and we will need consumer thread to consume the produced objects.

package com.thread.problem; 
public class Consumer implements Runnable {
                private Information pool;
                public Consumer(Information pool) {
                                this.pool = pool;
                }
               
                @Override         
                public void run() {
                                for(int i = 0; i < 20; i++){
                                                try {
                                                                System.out.println("Retrieved String:::: " + pool.get());
                                                } catch (InterruptedException e) {
                                                                e.printStackTrace();
                                                }
                                }
                }

}

package com.thread.problem; 
public class Producer implements Runnable {
                private Information pool;
                public Producer(Information pool) {
                                this.pool = pool;
                }
               
                @Override         
                public void run() {
                                for(int i = 0; i < 20; i++){
                                                try {
                                                                pool.put("String " + i );
                                                } catch (InterruptedException e) {
                                                                e.printStackTrace();
                                                }
                                }
                }

}

Constructors is created so that shared objects can be passed to Consumer and producer thread.
Once everything is set up, now we need to demonstrate whether our solution works. So let write main method within another class which will start both the threads.

package com.thread.problem; 
public class Demonstration {

                public static void main(String[] args) {
                                Information pool = new Information();
                                Thread c = new Thread(new Consumer(pool));
                                Thread p = new Thread(new Producer(pool));
                                p.start();                             
                                c.start();
                }
               
}

Output for the following program will be as following.
Producer will wait now.
Producer will wait now.
Retrieved String:::: String 0
Producer will wait now.
Retrieved String:::: String 1
Producer will wait now.
Retrieved String:::: String 2
Producer will wait now.
Retrieved String:::: String 3
Retrieved String:::: String 4
Consumer will wait now.
Producer will wait now.
Retrieved String:::: String 5
Consumer will wait now.
Producer will wait now.
Retrieved String:::: String 6
Consumer will wait now.
Producer will wait now.
Retrieved String:::: String 7
Consumer will wait now.
Producer will wait now.
Retrieved String:::: String 8
Consumer will wait now.
Producer will wait now.
Retrieved String:::: String 9
Producer will wait now.
Retrieved String:::: String 10
Consumer will wait now.
Producer will wait now.
Retrieved String:::: String 11
Producer will wait now.
Retrieved String:::: String 12
Consumer will wait now.
Producer will wait now.
Retrieved String:::: String 13
Producer will wait now.
Retrieved String:::: String 14
Consumer will wait now.
Producer will wait now.
Retrieved String:::: String 15
Consumer will wait now.
Producer will wait now.
Producer will wait now.
Retrieved String:::: String 16
Retrieved String:::: String 17
Consumer will wait now.
Producer will wait now.
Retrieved String:::: String 18
Consumer will wait now.
Retrieved String:::: String 19

This output may differ from compiler to compiler.

Its indeed a useful design pattern and used most commonly while writing multi-threaded or concurrent code. here is few of its benefit:
 1) Producer Consumer Pattern simple development. you can Code Producer and Consumer independently and Concurrently, they just need to know shared object.
 2) Producer doesn't need to know about who is consumer or how many consumers are there. Same is true with Consumer.
 3) Producer and Consumer can work with different speed. There is no risk of Consumer consuming half-baked item. In fact by monitoring consumer speed one can introduce more consumer for better utilization.

4) Separating producer and Consumer functionality result in more clean, readable and manageable code.

There are other multiple ways to solve this problem. This example is used to for naive users. Users who have started leaning java language very recently. It is helpful for them.

Wednesday, July 3, 2013

Threads: Difference between wait() and sleep()

I was thinking to improve my threading fundamentals, so I planned to make few notes for myself that will assist me in future (Obviously at the time of Interviews). Following questions and answers have been taken from stackoverflow.com. This post is a sticky notes post for me.

I never delve into the world of threading, so I could not ever make a much difference between wait and sleep but after understanding the wait method, I could make out something.

Java doc

public final void wait() throws InterruptedException

Causes current thread to wait until another thread invokes the notify() method or the  notifyAll() method for this object. In other words, this method behaves exactly as if it simply performs the call wait(0).
The current thread must own this object's monitor. The thread releases ownership of this monitor and waits until another thread notifies threads waiting on this object's monitor to wake up either through a call to the notify method or the notifyAllmethod. The thread then waits until it can re-obtain ownership of the monitor and resumes execution.
As in the one argument version, interrupts and spurious wakeups are possible, and this method should always be used in a loop:
     synchronized (obj) {
         while (<condition does not hold>)
             obj.wait();
         ... // Perform action appropriate to condition
     }

This method should only be called by a thread that is the owner of this object's monitor. See the notify method for a description of the ways in which a thread can become the owner of a monitor.

public static void sleep(long millis) throws InterruptedException

Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds. The thread does not lose ownership of any monitors.

What is sleep and wait
Thread.sleep() sends the current thread into the "Not Runnable" state for some amount of time. The thread keeps the monitors it has acquired - i.e. if the thread is currently in a synchronized block or method no other thread can enter this block or method. If another thread calls t.interrupt() it will wake up the sleeping thread.

object.wait() sends the current thread into the "Not Runnable" state, like sleep(). Wait is called on an object, not a thread; we call this object the "lock object." Beforelock.wait() is called, the current thread must synchronize on the lock object; wait() then releases this lock, and adds the thread to the "wait list" associated with the lock. Later, another thread can synchronize on the same lock object and call lock.notify(). This wakes up the original, waiting thread. Basically, wait()/notify() is like sleep()/interrupt(), only the active thread does not need a direct pointer to the sleeping thread, but only to the shared lock object.


Example

Wait Example
public class ConnectionPool {
   private List<Connection> connections = createConnections();

   private List<Connection> createConnections() {
     List<Connection> conns = new ArrayList<Connection>(5);
     for (int i = 0; i < 5; i++) {
       ... add a Connection to conns
     }
     return conns;
   }
}

public Connection getConnection() throws InterruptedException {
   synchronized (connections) {
     while (connections.isEmpty()) {
       connections.wait();
     }
     return connections.remove(0);
   }
}

public void returnConnection(Connection conn) {
   synchronized (connections) {
     connections.add(conn);
     connections.notify();
   }
}

Sleep Example: Requirement is to copy files existed at server to local machine. This activity should be repeated in every 5 minutes.
                public void CopyFilesFromServerToLocal() throws InterruptedException {
                                performCopy();
                                sleep(5*60*1000);
}

Difference between Thread.sleep and Object.wait method

Thread.sleep
Object.wait
It is a static method. On calling the method, it will send current running thread in sleep status. T.sleep(1000) and sleep(1000) both will send current running thread to sleep status. ( T is an instance of another thread)
It is an instance method.
Thread does not uses any CPU cycle while sleeping
Thread does not use any CPU cycle while waiting.
Thread does not releases any lock it possesses
Releases the lock of the object on which wait was called. Other locked monitors will not be released by the waiting thread.
This method can be called from non-synchronized block.
This method must be called from synchronized block. Because if block is not synchronized, then no objects are locked.
Sleep is used for Time Synchronization.
It is used in inter-thread communication.
In Lehman terms sleep tells JVM that I’m done with my time-slice, and please don’t give me another one for at least n milliseconds.
In Lehman terms wait tells JVM that I’m done with my time-slice. Don’t give me another timeslice until someone calls notify().

Tuesday, July 2, 2013

Threads: Why are Wait and notify declared in Object class?

I was thinking to improve my threading fundamentals, so I planned to make few notes for myself that will assist me in future (Obviously at the time of Interviews). Following questions and answers have been taken from stackoverflow.com. This post is a sticky notes post for me.

This question has haunted me for quite a long time, so it would be interesting to understand the reasons to segregate respective methods from other thread related operations.

Java docs say the following
public final void wait() throws InterruptedException

Causes current thread to wait until another thread invokes the notify() method or the notifyAll() method for this object. In other words, this method behaves exactly as if it simply performs the call wait(0).
The current thread must own this object's monitor. The thread releases ownership of this monitor and waits until another thread notifies threads waiting on this object's monitor to wake up either through a call to the notify method or the notifyAllmethod. The thread then waits until it can re-obtain ownership of the monitor and resumes execution.
As in the one argument version, interrupts and spurious wakeups are possible, and this method should always be used in a loop:
     synchronized (obj) {
         while (<condition does not hold>)
             obj.wait();
         ... // Perform action appropriate to condition
     }

This method should only be called by a thread that is the owner of this object's monitor. See the notify method for a description of the ways in which a thread can become the owner of a monitor.

public final void notify()
Wakes up a single thread that is waiting on this object's monitor. If any threads are waiting on this object, one of them is chosen to be awakened. The choice is arbitrary and occurs at the discretion of the implementation. A thread waits on an object's monitor by calling one of the wait methods.
The awakened thread will not be able to proceed until the current thread relinquishes the lock on this object. The awakened thread will compete in the usual manner with any other threads that might be actively competing to synchronize on this object; for example, the awakened thread enjoys no reliable privilege or disadvantage in being the next thread to lock this object.
This method should only be called by a thread that is the owner of this object's monitor. A thread becomes the owner of the object's monitor in one of three ways:
  • By executing a synchronized instance method of that object.
  • By executing the body of a synchronized statement that synchronizes on the object.
  • For objects of type Class, by executing a synchronized static method of that class.
Only one thread at a time can own an object's monitor.

Let’s try to understand it with one analogy.
One hotel has only one exclusive suite. It is quite popular. As only one couple can occupy one room, so other people enter their name in the wait list until person occupying the room does not check out of it.
So in this case, the room is a shared resource, and person occupying the room is a thread having a lock. Hotel management is JVM. Hotel management shares the key with first client and once he leaves the room, it picks up one client and notifies the chosen client.

Now let’s look at it with another prospective.
Let’s say hotel management does not want to handle this situation, so it provides client’s number, person who is occupying the room, to all the members. All these people call the client residing in hotel. So instead of enjoying the room, he will be busy in managing these calls, and he might probably sue hotel’s management.

There is one way around, hotel management provides client, having the key, the list of individuals who wanted to book the room next, but will any client accept to call other individuals? He will say that I do not care about calling anyone. You do your business and let me finish mine.

So what does about example signify?
It clearly indicates that none of the thread either cares about other threads or wants to be disturbed while performing its own operations. To avoid this scenario JVM tells every thread to wait on an object, instead talking to threads. This is why wait and notify are part of object instead thread.

Introducing new terms i.e. Monitors
The most simple and obvious reason is that any Object (not just a thread) can be the monitor for a thread. The wait and notify are called on the monitor. The running thread checks with the monitor. So the wait and notify methods are in Object and not Thread.

public class ConnectionPool {
 private List<Connection> connections = createConnections();

 private List<Connection> createConnections() {
   List<Connection> conns = new ArrayList<Connection>(5);
   for (int i = 0; i < 5; i++) {
     ... add a Connection to conns
   }
   return conns;
 }
}

public Connection getConnection() throws InterruptedException {
 synchronized (connections) {
   while (connections.isEmpty()) {
     connections.wait();
   }
   return connections.remove(0);
 }
}

public void returnConnection(Connection conn) {
 synchronized (connections) {
   connections.add(conn);
   connections.notify();
 }

}

This is a typical example of consumer producer problem. In this case we have a connection pool which has 5 connections. Now different thread can request for connections, so connection pool must check whether it has capacity to provide one connection or not. If it has one connection, it will provide it else other wise it will ask thread to wait for connections to release. So here thread will wait on connection. In other words it can be said thread is waiting for connections. Same applies in the case of notify. Once any thread releases the connection, that will added to pool and one of the threads will be notified to grab the newly released connection.

Thursday, June 27, 2013

Threads: How to Kill a thread?

I was thinking to improve my threading fundamentals, so I planned to make few notes for myself that will assist me in future (Obviously at the time of Interviews). Following questions and answers have been taken from stackoverflow.com. This post is a sticky notes post for me.

Java has provided a stop method to stop the thread gracefully, but with time java has deprecated the method. So what can be most convenient way to exit the thread gracefully?

In the link mentioned below Sun has provided the reason to deprecating few important methods.

Thread.stop deprecated???
On calling Thread.stop, thread unlocks all monitors locked. Basically Thread.stop throws ThreadDeath exception, which propagated up in the stack.)

Now monitor might leave objects in inconsistent state. These objects are called damaged objects.
Objects, with inconsistent state, can be viewed and grabbed by another threads, and it can result in program’s unprecedented behavior.

When unchecked exception is thrown, then user must be aware this exception and he must know about the inconsistency in the behavior. Why did this not happen?

Unlike other unchecked exception, ThreadDeath exception is designed to work silently without leaving much information. So it is not possible to know any inconsistent behavior of the application beforehand.

If not Thread.stop, then what?
In the same document two alternatives have been provided. We need to implement one among them for exit/stop/kill a thread gracefully.

Method 1: We must use a variable to identify when thread should be stopped. It is better to use a volatile variable which will maintain the fresh copy of the specific variable.
   
    private Thread blinker;
    public void stop() {
        blinker.stop();  // UNSAFE!
    }
    public void run() {
        Thread thisThread = Thread.currentThread();
        while (true) {
            try {
                thisThread.sleep(interval);
            } catch (InterruptedException e){
            }
            repaint();
        }
    }

This piece of code must be replaced with the following code.

    private volatile Thread blinker;

    public void stop() {
        blinker = null;// In the stop method, blinker object’s state has been changed.
    }

    public void run() {
        Thread thisThread = Thread.currentThread();
        while (blinker == thisThread) {//When application should be stopped, then blinker is null so it will exit gracefully.
            try {
                thisThread.sleep(interval);
            } catch (InterruptedException e){
            }
            repaint();
        }
    }

Method 2: This method is more convenient when thread waits for longer amount of time. In this case we need to interrupt the waiting thread. In this case stop method should be replaced with the following code.
   public void stop() {
        Thread moribund = blinker;
        blinker = null;//I have my own doubts about this method, I will test it and confirm it soon.
        moribund.interrupt();
    }
For this technique to work, it's critical that any method that catches an interrupt exception and is not prepared to deal with it immediately reasserts the exception. We say reasserts rather than rethrows, because it is not always possible to rethrow the exception. If the method that catches the InterruptedException is not declared to throw this (checked) exception, then it should "reinterrupt itself" with the following incantation:

    Thread.currentThread().interrupt();


This ensures that the Thread will reraise the InterruptedException as soon as it is able.

Why reassertion is required?
This is done to keep state.
When you catch the InterruptException and swallow it, you essentially prevent any higher level methods/thread groups from noticing the interrupt. Which may cause problems.

By calling Thread.currentThread.interrupt(), you set the interrupt flag of the thread, so higher level interrupt handlers will notice it and can handle it appropriately.

Here is one example.

import java.util.Calendar;

class RunnableImpl implements Runnable {
public void run() {
runSomeCode();
}

private void runSomeCode() {
while(!Thread.currentThread().isInterrupted()){
waitForSometime(1000);
System.out.println("Checking for interruption. " + Calendar.getInstance().getTimeInMillis());
}
}

private void waitForSometime(int i) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
Thread.currentThread().interrupt();
}
}
}

public class TestRunnable {
public static void main(String[] args) {
Thread instance = new Thread(new RunnableImpl());
instance.start();
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
instance.interrupt();
}
}

Output:
Checking for interruption. 1372386050062
Checking for interruption. 1372386051063
Checking for interruption. 1372386052063
Checking for interruption. 1372386053063
Checking for interruption. 1372386054063
Checking for interruption. 1372386055063
Checking for interruption. 1372386056063
Checking for interruption. 1372386057063
Checking for interruption. 1372386058064
java.lang.InterruptedException: sleep interrupted
Checking for interruption. 1372386058903
at java.lang.Thread.sleep(Native Method)
at RunnableImpl.waitForSometime(TestRunnable.java:20)
at RunnableImpl.runSomeCode(TestRunnable.java:13)
at RunnableImpl.run(TestRunnable.java:8)
at java.lang.Thread.run(Unknown Source)

Threads: Implementing Runnable or Extending Thread

I was thinking to improve my threading fundamentals, so I planned to make few notes for myself that will assist me in future (Obviously at the time of Interviews). Following questions and answers have been taken from stackoverflow.com. This post is a sticky notes post for me.

Thread can be instantiate with 2 different ways. You can create a class by either implementing Runnable interface or extending Thread class.

public class RunnableImpl implements Runnable {
                public void run() {                      
                                // TODO Write something here.
                }
}

public class SubThread extends Thread {
                public void run() {
                                //TODO  Write something here
                }
}

When java has provided various ways of implementation, then where these implementations should be used. Which is more commonly and beneficial implementation among two?

1.  One basic difference between these two approaches is when class is using an interface then it has the freedom to extend any other class. So RunnableImpl class may have multiple functionalities. Whereas when class extends thread class, then it is bound to function as Thread only.

      2. When class is implementing Runnable interface, then this class can act as a nonthreading instance.
At the start application used to perform in the manner mentioned below.

public class ExecuteRun{
                public static void main(String[] args) {
                                Thread runImpl = new Thread(new RunnableImpl());
                                runImpl.start();
                }
}

But for some strange reasons, it was decided to get rids of multithreading implementation. In this case the following code can be changed to the following.

public class ExecuteRun{
                public static void main(String[] args) {
                                new RunnableImpl().run();
                }
}

On forcing our mind to work, we will say it is possible to do with Thread implementation as well, then why we preferred it over other.
It was preferred because Java 1.4 caused a memory leak when Thread was started with Run method instead Start method.
Though this issue has been resolved in Java 5 and higher versions, but people still prefer other implementation practice.

3. Other important reason to use Runnable is the flexibility to use concurrency API introduced in Java 5. Runnable allows to keep work loosely coupled with desired concurrency.

Caveat: Around here, I strongly discourage the use of raw Threads. I much prefer the use of Callablesand FutureTasks (From the javadoc: "A cancellable asynchronous computation"). The integration of timeouts, proper cancelling and the thread pooling of the modern concurrency support are all much more useful to me than piles of raw Threads.

Follow-up: there is a FutureTask constructor that allows you to use Runnables (if that's what you are most comfortable with) and still get the benefit of the modern concurrency tools. To quote the javadoc: If you don't need a particular result, consider using constructions of the form:Future<?> f = new FutureTask<Object>(runnable, null)

So, if we replace their runnable with your threadA, we get the following:

new FutureTask<Object>(threadA, null)

Another option that allows you to stay closer to Runnables is a ThreadPoolExecutor. You can use theexecute method to pass in a Runnable to execute "the given task sometime in the future."
If you'd like to try using a thread pool, the code fragment above would become something like the following (using the Executors.newCachedThreadPool() factory method):

ExecutorService es = Executors.newCachedThreadPool();
es.execute(new ThreadA());

4. One significant difference between Thread and Runnable is the sharing of resources. In case of Runnable implementation, one resource can be shared with multiple instances whereas it is not possible with thread implementation. (I will try to find some appropriate example here soon)

Such a huge discussion boils down on the following point.

Subclass must extend a class only if it overrides methods other than Run method, otherwise it is beneficial to implement an interface in the class.

Wednesday, June 5, 2013

Difference between antcall and depends

Sometime we work without thinking much about the build script and other times we need to change the build scripts. At this time we start thinking about various functions in the language.

So today when I was modifying such build script, then I got stuck between the use of "depends" and "antcall". I did little bit of Googling and I got 2 nice articles.

It is not possible for me to elaborate all the uses of ‘depends’ and ‘antcall’ but I will try to provide little information on these targets.

Depends is an attribute of “target” target.

<target name=”runtarget” depends=”target1, target2, target3”  if="condition">

About specified line says before running “runtarget”, ant must execute target mentioned in the “depends” attributes. If condition is verified once all the targets mentioned in the “depends” attribute have already run.

So execution order will be as follows:
1.                   target1
2.                   target2
3.                   target3
                if(condition == true)
4.                   runtarget
                endif

Let’s take another example.
<target name="A"/>
<target name="B" depends="A"/>
<target name="C" depends="B"/>
<target name="D" depends="C,B,A"/>

In this case if target D is executed then it will run in the following order.
A -> B -> C -> D
In this case target will not be executed twice.

‘antcall’ is a target/task. It invokes another target which exists in the build xmls.

<antcall target=”target1”/>

In this case processing will switch to another target specified in the antcall. Let’s look at the an example to illustrate the functionality.
<target name=”target1” />
<target name=”target2” >
<antcall target=”target1”/>
</target>
<target name=”target3” >
<antcall target=”target1”/>
<antcall target=”target2”/>
</target>

Now on invoking target3, following will be sequence of run.
Target3 -> target1 -> target2-> target1

As you can see, target 1 is run twice as it will called by target 3 independently and target 2 also invoked target 1 internally. Whereas when such duplicity exists in target called by depends attribute, then ant resolves such duplicate target.

Uses of antcall and depends in one example
Requirement: I have to build a project and create a jar file. Building of this jar depends on already build 100+ jar files, which are at some remote location at the starting of the project. If these jar files do not exist locally, ftp these jar files from remote location.

Approach 1: We will copy the jar files irrespective of their existence.
Approach 2: We will check whether jar files exists, if not then we will copy them from server.

Solution:
Approach 1 is not only time consuming but also it involves the risk of copying the file from remote location, which may not exists at time.
Approach 2 is efficient and nice. So let’s write the code for this.

<target name=”CopyJarsFromServer”>
<!—code for copying the jar using ftp -->
</target>

<target name=”validatejars”>
<if condition>
<antcall target=”CopyJarsFromServer”/>
<!—these is not other way to do it without using ant call -->
<end if>
</target>

<!—We are using depends attribute as we want to make sure that jar exists before any actual processing starts -->
<target name=”build” depends=”validatejars”>
<!—relevant code to build the jar -->
</target>

Hurrey, Now I understand the difference between antcall and depends, and I hope you too. J

Misuse of antcall task may hamper efficiency of your build script as antcall task does allow you to control what properties and references are defined (which is why a new Ant environment is created--and why it's so slow) so it can be used to create variants of the same thing; e.g., maybe two jars, one with and one without debug symbols.

So use antcall task only if it is not possible to find a workaround using depends target.

If you didn’t like my explanation and wants to check actual links that I have used to understand the difference, then please visit the followings

Wednesday, May 22, 2013

Jboss Esb - Imported file can not be resolved


I was working on an application that was built in Jboss Esb. I changed my source code and uploaded the jar, which was built using ant files.

As soon as I uploaded the file, Jboss bombed while starting it. It threw the exception mentioned below
The import com.XYZ.adapter.abc cannot be resolved.

I am new to JBOSS Esb. It was an urgent requirement and I needed to fix it ASAP. I did not have any idea to solve the issue in JBOSS ESB. I was cusring JBOSS and developer who thought to use the application. So I had to depend on Mr Reliable Google.

I search on google, and most of the people said that I have not build the jar in the correct manner. Whereas I was sure that I have build it correctly. I researched more. When Google stopped responding to my queries with satisfactory answers, then I started searching the answers at my own, and finally I found the solution for the problem.

I found that my class file did not have corresponding import statement(Which I lost while merging the file with version control tool). But my question was then how I got jar file. So I troubleshooted the ant scripts and found following.

-> My ant script was not deleting old class files. So instead compiling java source file, it was zipping already compiled files.
-> My Eclipse project did not show error, because auto building was disabled.
-> My Eclipse project and Ant Script was building class file at the same location. I.e. Both were building at ${basedir}/bin.

Keep it in mind, whatever technology you are using, it is based on one specific language. Irrespective of technology, the language concepts will always hold true.

The import com.XYZ.adapter.abc cannot be resolved.

Error listed above shows that there are compilation problems with the jar, so rebuild the jar with additional care.