Monday, September 9, 2013

Understanding commons HttpClient with example.

What is HttpClient :
HttpClient is a client side  HTTP transport library whose purpose is to transmit and receive HTTP messages. The HTTP (Hyper Text Transfer Protocol ) is the most significant protocol used on the internet today. HttpClient can be used by anyone building HTTP-aware client applications such as Web Browsers , Web services clients or any system that uses HTTP protocol for distributed communication. 


HttpClient is not a browser :
Though it seems that HttpClient is simulating the functionality of a web browser , but that's not true . HttpClient is not a browser. HttpClient will not attempt to cache content, execute javascript embedded in HTML pages, try to guess content type, or reformat request / redirect location URIs.


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 :

<dependency>
<groupId>commons-httpclient</groupId>
<artifactId>commons-httpclient</artifactId>
<version>3.0</version>
</dependency>

Steps to create HttpClient :

1. Create an instance of HttpClient.
2. Create an instance of HttpMethod.
3. Tell HttpClient to execute method.
4. Read the respose.
5. Release connection.
6. Deal with the respone. 


Example : This code demonstrates how HttpClient makes a GET request to Google Server and bring back the results.
public class GoogleSearch {
     private static String searchUrl = "https://www.google.com/search?hl=en&q=httpclient&btnG=Google+Search";

     public static void main(String[] args) {

         // Create an instance of HttpClient.
         HttpClient client = new HttpClient();

         // Create a method instance.
         GetMethod method = new GetMethod(searchUrl);

         // Provide custom retry handler.
         method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,new DefaultHttpMethodRetryHandler(3, false));

         try {
             // Execute the method.
             int statusCode = client.executeMethod(method);

             if (statusCode != HttpStatus.SC_OK) {
                 System.err.println("Method failed: " + method.getStatusLine());
             }

             // Read the response body.
             String responseBody = method.getResponseBodyAsString();

             // Deal with the response.
             System.out.println(responseBody);

         } catch (HttpException e) {
             System.err.println("Fatal protocol violation: " + e.getMessage());
         } catch (IOException e) {
             System.err.println("Fatal transport error: " + e.getMessage());
         } finally {
             // Release the connection.
             method.releaseConnection();
         }
     }
}

Tuesday, September 3, 2013

Thread interference and Memory consistency errors.

Generally threads communicates by sharing member variables and the Object references members refer to. Well this type of communication is extremely efficient but can cause two kind of problems :

1. Thread Interference 
2. Memory Consistency Errors 

Interference occurs when two operations , running in different threads , but acting on the same data , interleave.

See the Counter class  ( example taken from docs.oracle.com ).

class Counter {
    private int c = 0;

    public void increment() {
        c++;
    }

    public void decrement() {
        c--;
    }

    public int value() {
        return c;
    }

}
Suppose there are two threads Thread-A and Thread-B working on the same counter instance  . Say Thread-A invokes increment() , and at the same time Thread-B invokes decrement() . Thread-A reads the value c and  increment it by 1 . At the same time Thread-B reads the value ( which is 0 because the incremented value is not yet set by Thread-A) , decrements it and set it to -1 . Now Thread-A sets the value to 1 .

Oops what went wrong ? The result of Thread-B is lost. It might be the other case as well or there could be no error at all . This uncertainty makes it difficult to identify bugs .

Memory Consistency Errors occurs when different threads have inconsistent views of the shared data. 

In the above class counter , Lets say there are two threads working on the same counter instance ,  calls the increment method to increase the counter's value by 1 . Here it is no guarantee that the changes made by one thread is visible to the other .

Avoiding Memory Consistency Errors
This can be avoided by establishing a happens-before relationship . This relationship guarantees that memory write by one thread is visible to a read by other thread if the write operation happens-before the read operation. There are various actions that can form a happens-before relationship.

  • Synchronization
  • volatile keyword
  • Thread.start()
  • Thread.join()


Thursday, August 15, 2013

Understanding Threads in Java

A Thread is an independent sequential path of execution within a process / program. Multiple threads can run concurrently in a program . Threads are lightweight as compared to the process as at runtime , they exist in a common memory space and can share process's resources like  data and code.

Threads make the runtime environment asynchronous , allowing different tasks to be performed concurrently . In Java , a thread is represented and controlled by an object of class java.lang.Thread.

main() method is executed as a Thread.
When an application ( or a program ) is run, a user thread is created to execute the main() method of the application. This thread is called main thread.

Thread Creation :
A thread in java is represented by an object of class java.lang.Thread and can be created in two ways :

1. Implementing java.lang.Runnable interface.
The Runnable interface defines a method run() that contains the code that is to be executed in a thread. Lets create a thread that says " Hello User ".

public class MyRunnable implements Runnable {

 // Statements defined in run() methods are executed as a thread.
 public void run(){
  System.out.println("Hello User");
 }

 public static void main(String[] args) {             
  // Creating an object of Thread class and passing a Runnable in its constructor.
  Thread thread = new Thread(new MyRunnable());

  // Starting a thread.
  thread.start();
 }
}
 
    
2. Extending java.lang.Thread class.
Another way to create a thread is by extending Thread class  and override the run() method .The Thread class itself implements Runnable but its run() method does nothing.

public class MyThread extends Thread {

 public void run() {
  System.out.println("Hello User");
 }

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

What is Multitasking ?

Multitasking is the ability to perform more than one activity concurrently on a computer. We can further break multitasking into process based and thread based .

Process-based Multitasking 
Process-based multitasking allows processes ( or programs ) to run concurrently on a computer. For example , running different applications at the same time like downloading a file and printing a file .

A process has a self-contained execution environment. A process has a complete , private set of basic resources . Each process has its own memory space.

Thread-based Multitasking
Thread-based multitasking allows different parts of the same process ( program ) to run concurrently .
A good example is printing and formatting text in a word processor at the same time.
Thread-based multitasking is only feasible if the two parts are independent of each other or more precisely they are independent paths of execution at run time.

Threads are also referred as lightweight processes and they also provide an execution environment . Threads exists within a processes and share its resources like memory and open files.

We have several advantages of Thread-based multitasking over Process-based multitasking .

1. Threads shares the same address space.

2. Context switching between the threads is less expensive than in Processes.



Sunday, June 16, 2013

Tomcat throwing Java.Lang.OutOfMemoryError: PermGen Space

Your Tomcat might have thrown such kind of exception while running : 


java.lang.OutOfMemoryError: PermGen space
Java heap is structured into regions called generations. The permanent generation is the area of the heap where class and method objects are stored. 
If an application loads a very large number of classes, then the permanent generation can get out of space.In that case , we  might need  increase the perm gen size in Tomcat using the files catalina.bat or catalina.sh .

Assign the following values to JAVA_OPTS and add this in catalina.bat or catalina.sh file.


JAVA_OPTS="-Djava.awt.headless=true -Dfile.encoding=UTF-8 -server -Xms1536m 
-Xmx1536m -XX:NewSize=256m -XX:MaxNewSize=256m -XX:PermSize=256m 
-XX:MaxPermSize=256m -XX:+DisableExplicitGC"
Snippet from catalina.sh file





Sunday, April 21, 2013

Install MongoDB as windows service

We can also configure MongoDB to run as a windows service .  
mongod.exe added support for running as a Windows service in version 2.0, and mongos.exe added support for running as a Windows Service in version 2.1.1.

Step 1 : Create configuration file mongod.cfg .

echo logpath=C:\mongodb\log\mongo.log > C:\mongodb\mongod.cfg

A new file mongod.cfg will be created at location C:\mongodb. This file contains an entry logpath which tells mongodb to save all logging information in the specified file mongo.log


Step 2 :  Install MongoDB as a service .
Execute following command in command prompt :

mongod --config C:\mongodb\mongod.cfg --install



A new windows service will be created .


Step 3 : Start Mongo Service 
Execute following command in command prompt :

net start MongoDB




Other Options :

1 . Stopping MongoDB Service :
     net stop MongoDB


2 . Removing MongoDb service :
     mongod.exe --remove





Thursday, April 18, 2013

How to delete a tag in Github.

Following commands can be used to delete a tag in git.

1. Delete tag from local
     git tag -d [tag];

2. Push changes to remote
     git push origin :[tag]

Example :
    
Let say you have created a tag by name v6.37.1 . Now to delete the tag from git :

1.  git tag -d v6.37.1

2.  git push origin :v6.37.1

NOTE :
If your tag has the same name as one of your branches then ,

1. git tag -d [tag]

2. git push origin :refs/tags/[tag]