Monday, October 7, 2013

Inter thread communication showing the usage of notifyAll() method.

Lets start with the methods that facilitates Inter Thread Communication in Java . All these methods are present in java.lang.Object class .

wait() method is used to instruct the current thread to release the object's lock and get suspended until some other thread invokes notify() or notifyAll() method for the same monitor.

notify() method is used to wake up a thread that is suspended by the wait() method.

notifyAll() method is used to wake up all the threads that are suspended by wait() method.

Lets come to our topic . notifyAll() method is important when several threads are waiting on one object. For example there is a class that performs a calculation and many readers are waiting to read the computed calculation.

class Calculator extends Thread {
    private int total;
    private boolean isCalcDone;

    public void run() {
        synchronized (this) {
            for (int i = 0; i < 10000; i++) {
                total += i;
            isCalcDone = true; // ------------ (3)
            notifyAll();       // ------------ (4)

    public int getTotal() {
        return total;

    public boolean isCalcDone() {
        return isCalcDone;

class CalcReader extends Thread {
    Calculator calculator;

    public CalcReader(Calculator calculator) {
        this.calculator = calculator;

    public void run() {
        synchronized (calculator) {
            //Reader threads waits for the Calculator to complete its calculation by calling wait().
            while (!calculator.isCalcDone()) {  // ------------ (1) 
                System.out.println("Waiting for calculator");
                try {
                    calculator.wait();          // ------------ (2)
                } catch (InterruptedException e) {
            System.out.println("Total is :" + calculator.getTotal());


public class NotifyAllExample {
    public static void main(String[] args) {
        Calculator calculator = new Calculator();
        new CalcReader(calculator).start();
        new CalcReader(calculator).start();
        new CalcReader(calculator).start();

In the above example :
1. We have created three CalcReader threads sharing a common Calculator instance.
2. At (1) , Threads checks if Calculator has completed the  calculation , if not , calls wait() at (2) , releases the lock and waits for the Calculator to complete its calculation.
3. When Calculator completes its calculation , sets isCalcDone to true at (3) and notifies all the waiting threads at (4). 

Saturday, October 5, 2013

Sending POST request using http components HttpClient

Hi . In my previous posts , we talked about the basics of HttpClient ( Click here ) and how to use it safely in a multithreaded environment ( Click here )  . In this post we will learn how we can send POST request to a server using HttpClient . 

Get Ready :
Download HttpClient dependencies and put them in the classpath of your application or if you are a maven user , add dependency in pom :


Lets take an example of form submission . HttpClient provides an entity class named UrlEncodedFormEntity  to encode the form parameters that needs to be send as a part of POST request. 
List<NameValuePair> formData = new ArrayList<NameValuePair>();
formData.add(new BasicNameValuePair("param1", "value1"));
formData.add(new BasicNameValuePair("param2", "value2"));

// Creating UrlEncodedFormEntity that will use the URL encoding to encode form parameters 
// in a form like param1=value1&param2=value2
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formData , Consts.UTF_8);

HttpPost httpPost= new HttpPost("Some URI");


Example :
This example below demonstrate the use of  HttpClient to make a POST request .
package in.tutorialhub.httpclient;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;

public class PostExample {
 public static void main(String[] args) throws Exception {
  // Creating an instance of HttpClient.
  CloseableHttpClient httpclient = HttpClients.createDefault();
  try {

   // Creating an instance of HttpPost.
   HttpPost httpost = new HttpPost("http://SomeRandomURI");

   // Adding all form parameters in a List of type NameValuePair

   List<NameValuePair> nvps = new ArrayList<NameValuePair>();
   nvps.add(new BasicNameValuePair("param1", "value1"));
   nvps.add(new BasicNameValuePair("param2", "value2"));

    * UrlEncodedFormEntity encodes form parameters and produce an
    * output like param1=value1&param2=value2
   httpost.setEntity(new UrlEncodedFormEntity(nvps, Consts.UTF_8));

   // Executing the request.
   CloseableHttpResponse response = httpclient.execute(httpost);
   System.out.println("Response Status line :" + response.getStatusLine());
   try {
    // Do the needful with entity.
    HttpEntity entity = response.getEntity();
   } finally {
    // Closing the response
  } finally {