In this post, we will see how to configure apache tomcat in eclipse.

As per wikipedia, Apache Tomcat, often referred to as Tomcat, is an open-source web server and servlet container developed by the Apache Software Foundation (ASF). Tomcat implements several Java EE specifications including Java Servlet, JavaServer Pages (JSP), Java EL, and WebSocket, and provides a "pure Java" HTTP web server environment for Java code to run in.

We generally deploy our web applications on apache tomcat server. When you download eclipse, you need to configure tomcat in it. We will see step by step configuration of apache tomact in eclipse.

Step 1:

Download apache tomcat server from tomcat 7 download. You need to download it based on your system operating system. (Windows or mac).I have provided link for tomcat 7. If you want different version, you need to download it. You need to extract it after downloading.

Step 2:

Open eclipse ide.
Step 2a: go to Java EE perpective.
Step 2b: Open Servers tab
Step 2c: click on "new server wizard" as shown in the below diagram.



Step 3:

Step 3a: Select "Tomcat v7.0 Server"
Step 3b: click on Next.


Step 4 :

Step 4a: Browse to  tomcat installation directory or if you have downloded zip then browse to extract folder.
Step 4b: click finish.


Step 5:

Step 5a : Double click on servers tab/
Step 5b : If Application deployment takes more than 45 secs then make changes to timeout.
Step 5c: If you want to change default http port.
Step 5d : If you want to take full control over apache tomcat installation.


Step 6:

Right click on the server and click on start.


Then you will see following text in console:


Step 7:

Open http://localhost:8080 and you will see following output:

Bingo!! We are done with the setup of apache tomcat in eclipse

You might have noticed Object class has three final method called wait, notify and notifyAll. These methods are used for inter thread communication.  Java 5 has introduced executor framework which takes care of inter thread communication for you and internally uses wait, notify and notifyAll but you still require basic understanding of these methods and how inter thread communication works in java using wait , notify and notifyAll.

What are wait , notify and notifyAll methods?

wait , notify and notifyAll method are used to allow threads to communicate to each other via accessing common object or in other terms, Object can be considered a medium for inter thread communication via these methods. These methods need to be called from synchronized context,otherwise it will throw java.lang.IllegalMonitorStateException.

Some background on synchronized block :
  • Only one thread can enter at a time in synchronized block
  • A thread required lock on the object to enter in synchronized block.
  • If Thread A want to enter in synchronized block then Thread A has to wait for Thread B to release it.

Lets have some brief understanding of these methods:

wait():

When you call wait method on the object then it tell threads to give up the lock and go to sleep state unless and until some other thread enters in same monitor and calls notify or notifyAll methods on it.

notify():

When you call notify method on the object, it wakes one of thread waiting for that object. So if multiple threads are waiting for an object, it will wake of one of them. Now you must be wondering which one it will wake up. It actually depends on OS implementation.

notifyAll() :

notifyAll will wake up all threads waiting on that object unlike notify which wakes up only one of them.Which one will wake up first depends on thread priority and OS implementation.

Lets understand it with the help of example:

1. Create a class named Book.java:

It is java bean class on which thread will act and call wait and notify method.

package org.arpit.java2blog.thread;

public class Book {
 
 String title;
 boolean isCompleted;
 
 public Book(String title) {
  super();
  this.title = title;
 }
 
 public String getTitle() {
  return title;
 }
 public void setTitle(String title) {
  this.title = title;
 }
 public boolean isCompleted() {
  return isCompleted;
 }
 public void setCompleted(boolean isCompleted) {
  this.isCompleted = isCompleted;
 }
 
}

2. Create a class named BookReader.java

This thread will wait until other thread call notify method, then after it will complete its processing. It will first take a lock on book object and will be called from synchronized block .So in this example, it will wait for BookWriter to complete the book.

package org.arpit.java2blog.thread;

public class BookReader implements Runnable{
 
 Book book;
 
 public BookReader(Book book) {
  super();
  this.book = book;
 }

 @Override
 public void run() {
  synchronized (book) {
   System.out.println(Thread.currentThread().getName()+" is waiting for the book to be completed: "+book.getTitle());
   try {
    book.wait();
   } catch (InterruptedException e) {    
    e.printStackTrace();
   }
   System.out.println(Thread.currentThread().getName()+": Book has been completed now!! you can read it");
  }
 } 

}

3. Create a class named BookWriter.java

This class will notify thread(in case of notify) which is waiting on book object. It will not give away lock as soon as notify is called, it first complete its synchronized block. So in this example, BookWriter will complete the book and notify it to BookReaders.

package org.arpit.java2blog.thread;
public class BookWriter implements Runnable{

 Book book;
 
 public BookWriter(Book book) {
  super();
  this.book = book;
 }

 @Override
 public void run() {
  synchronized (book) {
   System.out.println("Author is Starting book : " +book.getTitle() );
   try {
    Thread.sleep(1000);
   } catch (InterruptedException e) {
    e.printStackTrace();
   }
   book.setCompleted(true);
   System.out.println("Book has been completed now");
   
   book.notify();
   System.out.println("notify one reader");
  
  } 
 }
}

4. Create a class ThreadInterCommunicationMain,java.

This is our main class which will create object of above classes and run it.

package org.arpit.java2blog.thread;

public class ThreadInterCommunicationMain {
 
 public static void main(String args[])
 {
  // Book object on which wait and notify method will be called
  Book book=new Book("The Alchemist");
  BookReader johnReader=new BookReader(book);
  BookReader arpitReader=new BookReader(book);
  
  // BookReader threads which will wait for completion of book
  Thread johnThread=new Thread(johnReader,"John");
  Thread arpitThread=new Thread(arpitReader,"Arpit");
  
  arpitThread.start();
  johnThread.start();
  
  // To ensure both readers started waiting for the book
  try {
   Thread.sleep(3000);
  } catch (InterruptedException e) {
   
   e.printStackTrace();
  }
  // BookWriter thread which will notify once book get completed
  BookWriter bookWriter=new BookWriter(book);
  Thread bookWriterThread=new Thread(bookWriter);
  bookWriterThread.start();
  
 }
 
}


In case of notify():

When you run above program, you will get following outputs:
Arpit is waiting for the book to be completed: The Alchemist
John is waiting for the book to be completed: The Alchemist
Author is Starting book : The Alchemist
Book has been completed now
notify one reader
Arpit: Book has been completed now!! you can read it

So here,two BookReader threads(arpit and john) are waiting for book to be completed,so they called book.wait(). Once BookWriter completes it book, it called book.notify() and arpit thread gets up and completes its processing.

In case of notifyAll() :

Lets change BookWriter class to call book.notifyAll().
package org.arpit.java2blog.thread;

public class BookWriter implements Runnable{

 Book book;
 
 public BookWriter(Book book) {
  super();
  this.book = book;
 }

 @Override
 public void run() {
  synchronized (book) {
   System.out.println("Author is Starting book : " +book.getTitle() );
   try {
    Thread.sleep(1000);
   } catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
   book.setCompleted(true);
   System.out.println("Book has been completed now");
   
   book.notifyAll();
   System.out.println("notify readers");
  
  }
 }

}

When you run above program, you will get following output:

Arpit is waiting for the book to be completed: The Alchemist
John is waiting for the book to be completed: The Alchemist
Author is Starting book : The Alchemist
Book has been completed now
notify readers
John: Book has been completed now!! you can read it
Arpit: Book has been completed now!! you can read it

In case of notifyAll(), it notifies all threads waiting on that object.

Please go through  top 50 core java interview questions for more interview questions.

If you want to practice data structure and algorithm programs, you can go through data structure and algorithm interview questions.
In this post,we will see how to perform binary search in java using divide and conquer method.When you want to find a value in sorted array, we use binary search and we will also see how to compute complexity of binary search.
Lets say we have an sorted array.

Algorithm:

  1. Initialize first=0 and last=sortedArray.length-1
  2. compute mid and compare  sortedArray[mid]  with element to be searched
  3. If element to be searched is less than sortedArray[mid] then element lies in left part of the mid, so last=mid
  4. if element to be searched is greater than sortedArray[mid] then element lies in right part of the mid, so first=mid+1.
  5. if element to be searched is equal to sortedArray[mid] , then return index
  6. Repeat above process until first is less than last.

  
 public  static int binarySearch(int[] sortedArray, int elementToBeSearched) {
  int first = 0;
        int last = sortedArray.length - 1;
       
      while (first < last) {
       
          int mid = (first + last) / 2;  // Compute mid point.
         
          if (elementToBeSearched < sortedArray[mid]) {
           last = mid;     // repeat search in first half.
          } else if (elementToBeSearched > sortedArray[mid]) {
              first = mid + 1;  // Repeat sortedArray in last half.
          } else {
              return mid;     // Found it. return position
          }
      }
     
      return -1;    // Failed to find element
  }

Example:
Now lets assume our sorted array is:
  
int[] sortedArray={12,56,74,96,112,114,123,567};
and we want to search for 74 in above array. Below diagram will explain how binary search will work here.

When you observe closely, in each of the iteration you are cutting scope of array to the half. In every iteration, we are overriding value of first or last depending on sortedArray[mid].
So for
0th iteration : n
1th iteration: n/2
2nd iteration n/4
3rd iteration n/8.
Generalizing above equation:
For ith iteration : n/2i

So iteration will end , when we have 1 element left i.e. for any i, which will be our last iteration:
1=n/2i;
2i=n;
after taking log
i= log(n);
so it concludes that number of iteration requires to do binary search is log(n) so complexity of binary search is log(n)
It makes sense as in our example, we have n as 8 . It took 3 iterations(8->4->2->1) and 3 is log(8).
Code:

 
package org.arpit.java2blog.thread;

public class BinarySerarchMain {

 
 public  static int binarySearch(int[] sortedArray, int elementToBeSearched) {
  int first = 0;
        int last = sortedArray.length - 1;
       
      while (first < last) {
       
          int mid = (first + last) / 2;  // Compute mid point.
         
          if (elementToBeSearched < sortedArray[mid]) {
           last = mid;     // repeat search in first half.
          } else if (elementToBeSearched > sortedArray[mid]) {
              first = mid + 1;  // Repeat sortedArray in last half.
          } else {
              return mid;     // Found it. return position
          }
      }
     
      return -1;    // Failed to find element
  }
 
 public static void main(String[] args)
 {
    
  int[] sortedArray={12,56,74,96,112,114,123,567};
  int indexOfElementToBeSearched=binarySearch(sortedArray,74);
  System.out.println("Index of 74 in array is: " +indexOfElementToBeSearched);
  
  int indexOfElementToBeSearchedNotFound=binarySearch(sortedArray,7);
  System.out.println("Index of 7 in array is: " +indexOfElementToBeSearchedNotFound);
 }
 
}
when you run above program, you will get below output:
  
Index of 74 in array is: 2
Index of 7 in array is: -1
 

Java tutorial for beginners Copyright © 2012