Thursday, July 7, 2016

WeakHashMap in Java with Example. Differences and Similarities in HashMap and WeakHashMap in java

A HashMap maintains the key value pairs of any specific data type or custom classes. And as we know, if we want to have any custom class instances as a Key to our HashMap then the custom class must implement the hashcode() and equals() method as per the contract of these two methods. Hence, the key of a HashMap plays a vital role in creating a HashMap.

As we know the nature of Garbage Collection, if any object in the program is not having any live reference anywhere then it is available for the garbage collection. If in any HashMap we are using such a key that the reference of that key(instance of a class) does not exist anymore anywhere then the garbage collection should remove it from the map and should collect it's garbage but in case of HashMap it is not possible.

It is possible only when the keys of the map are stored in a WeakReference. WeakReference is a class in java.lang.ref package.Hence, a WeakHashMap is a special Map implementation where the keys of the map are stored in a java.lang.ref.WeakReference . By storing the keys in a weak reference, key-value pairs can dynamically be dropped from the map when the only reference to the key is from the weak reference. It means the key-value pair will be garbage collected if there is not other live reference of the key other than WeakReference class.

Program Example:

public class WeakHashMapExample {
    
    public static void main(String[] args) { 

           
        // Creating HashMap and WeakHashMap objects

        Map hashmapObject = new HashMap();
        Map weakhashmapObject = new WeakHashMap();
        
       // Created HashMap and WeakHashMap keys

        String hashmapKey = new String ("hashmapkey");
        String weakhashmapKey = new String ("weakhashmapkey");

      // Created HashMap and WeakHashMap values

        String hashmapValue = "hashmapvalue";
        String weakhashmapValue = "weakhashmapvalue";  

      // Putting key and value in HashMap and WeakHashMap Object

        hashmapObject.put(hashmapKey ,hashmapValue); 
        weakhashmapObject.put(weakhashmapKey ,weakhashmapValue); 

      // Print HashMap and WeakHashMap Object : Before Garbage Collection
       
        System.out.println("HashMap before Garbage Collected :"+ hashmapObject);
        System.out.println("WeakHashMap before Garbage Collected :"+
                            weakhashmapObject);

     // Set HashMap and WeakHashMap Object keys to null

        hashmapKey = null;  
        weakhashmapKey = null;

     // Calling Garbage Collection
        System.gc(); 

    // Print HashMap and WeakHashMap Object : After Garbage Collection
       
        System.out.println("HashMap after Garbage Collected :"+ hashmapObject);
        System.out.println("WeakHashMap after Garbage Collected :"+
                            weakhashmapObject); 
 }
}

Output:

HashMap before Garbage Collected :{hashmapkey=hashmapvalue}
WeakHashMap before Garbage Collected :{weakhashmapkey=weakhashmapvalue}
HashMap after Garbage Collected :{hashmapkey=hashmapvalue}
WeakHashMap after Garbage Collected :{}


From the above example it is clear that the entry of WeakHashMap is garbage collected if it does not find any strong reference of it but this is not there in HashMap implementation.

Differences in HashMap and WeakHashMap:

1) Entry object Garbage Collected in WeakHashMap but in HashMap Entry object is not Garbage Collected even if the references are set to null.
2) Automatic Size decrease happens in case of WeakHashMap when run the size() method repeateadly on the WeakHashMap as the garbage collection might decrease the count and remove silently the element which is not strongly referenced. But in case of HashMap size() returns the same value until we remove any element explicitly.
3) Clone and Searilize methods are not in WeakHashMap as this class does not implement Cloneable and Serializable interfaces. Rather these methods are present in HashMap as HashMap implements these interfaces.

Similiarities in HashMap and WeakHashMap:

1) Both can have Null Key and Null Value.
2) Performance is similar in both the classes.
3) Both are not synchronized and can be made synchronized by using Collections.synchronizedMap().
4) Iterators of both the classes are fail-fast.

Variable Argument Methods in Java with Example(Varargs)

In java we call a method with its signature by passing the suitable arguments it takes. So the calling function must know the number of arguments and the types of arguments the called function will take. But, in some scenarios we need to call a function and we are not sure about the number of arguments the method will take or in other words we can say that the called method is unpredictable in respect of the number of arguments and the type of the arguments. The second scenario is that sometimes we call a function in the class which just performs some kind of operation(let's say multiplication) on the number of arguments that we pass to that function. Hence, we need to pass the each number to that method but it is made easy by variable arguments that while catching those arguments we don't need to specify the type and name of each of those arguments. Rather we can catch all of them in a variable argument. Below is an example of simple code snippet which is not using varargs.

public int multiply(int a,int b,int c,int d){
 return (a*b)*(c*d);
}

Here, we need to declare the type and name of the argument for each variable. Instead of it we can do it using varargs like follows:

public int multiply(int... numbers){
int result = 1;

for(int number: numbers){
 result= result*number;
}

return result
}

Here , in this code each and every number is catched in the numbers argument and is fetched one by one using the fore loop.

So, the biggest benefit of using it is to avoid method overloading for some scenarios.

Another example:

class VarargsExample2{  
   
 static void display(String... values){  
  System.out.println("display method invoked ");  
  for(String s:values){  
   System.out.println(s);  
  }  
 }  
  
 public static void main(String args[]){  
  
 display();//zero argument   
 display("hello");//one argument   
 display("my","name","is","varargs");//four arguments  
 }   
}  

Output:
display method invoked
display method invoked
hello
display method invoked
my
name
is 
varargs

Some points to remember about varargs:

*There can be only one variable argument in the method.
*Variable argument (varargs) must be the last argument.

Note: public static void main(String args[]) is the biggest example of varargs as it takes a undefined number of runtime arguments.

Tuesday, July 5, 2016

Java : Step-By-Step process to secure your RESTful API using ResourceConfig and @RolesAllowed annotations.

It is a very good practice to secure your web services so that the user of that service can be given a limited access to the methods based on the roles they have. We are going to user @RolesAllowed annotations in this section along with ResoourceConfig class. We will go through step by step procedure for this:

1) Modify your web.xml with the below mentioned code:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
    <display-name>Archetype Created Web Application</display-name>
    <servlet>
        <servlet-name>jersey-serlvet</servlet-name>
        <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
         <init-param>
       <param-name>jersey.config.server.provider.packages</param-name>
       <param-value>com.vagalla.jersey.first</param-value>
    </init-param>
        <init-param>
            <param-name>javax.ws.rs.Application</param-name>
            <param-value>com.vagalla.jersey.first.MyApplication</param-value>
        </init-param>      
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>jersey-serlvet</servlet-name>
        <url-pattern>/rest/*</url-pattern>
    </servlet-mapping>
</web-app>


In this section we have mentioned that every request which will hit the /rest uri, will undergo the ServletContainer and MyAppication will be loaded as the initial parameters.

2) Create class MyApplication extending the ResourceConfig internal class like follows:


import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.server.filter.RolesAllowedDynamicFeature;

public class MyApplication extends ResourceConfig {
    public MyApplication() {
        super(Hello.class);
        //register(RolesAllowedDynamicFeature.class);
        register(AuthenticationFilter.class);
    }
}

Here, in this class we are registering a class named AuthenticationFilter.class, LoggingFilter is a deprecated one. We can also register RolesAllowedDynamicFeature.class if we want. But, here in our example, only AuthenticationFilter.class is needed for simple HTTP basic authentication.

3) Create public class AuthenticationFilter implements javax.ws.rs.container.ContainerRequestFilter.

import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.StringTokenizer;

import javax.annotation.security.DenyAll;
import javax.annotation.security.PermitAll;
import javax.annotation.security.RolesAllowed;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.PreMatching;
import javax.ws.rs.container.ResourceInfo;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.Provider;

import org.glassfish.jersey.internal.util.Base64;

/**
 * This filter verify the access permissions for a user
 * based on username and passowrd provided in request
 * */
@Provider
@PreMatching
public class AuthenticationFilter implements javax.ws.rs.container.ContainerRequestFilter
{
    
    @Context
    private ResourceInfo resourceInfo;
     
    private static final String AUTHORIZATION_PROPERTY = "Authorization";
    private static final String AUTHENTICATION_SCHEME = "Basic";
    private static final Response ACCESS_DENIED =       Response.status(Response.Status.UNAUTHORIZED)
                                                        .entity("You cannot access this resource").build();
    private static final Response ACCESS_FORBIDDEN = Response.status(Response.Status.FORBIDDEN)
                                                        .entity("Access blocked for all users !!").build();
    
      
    @Override
    public void filter(ContainerRequestContext requestContext)
    {
        Method method = resourceInfo.getResourceMethod();
        //Access allowed for all
        if( ! method.isAnnotationPresent(PermitAll.class))
        {
            //Access denied for all
            if(method.isAnnotationPresent(DenyAll.class))
            {
                requestContext.abortWith(ACCESS_FORBIDDEN);
                return;
            }
              
            //Get request headers
            final MultivaluedMap<String, String> headers = requestContext.getHeaders();
              
            //Fetch authorization header
            final List<String> authorization = headers.get(AUTHORIZATION_PROPERTY);
            //If no authorization information present; block access
            if(authorization == null || authorization.isEmpty())
            {
                requestContext.abortWith(ACCESS_DENIED);
                return;
            }
              
            //Get encoded username and password
            final String encodedUserPassword = authorization.get(0).replaceFirst(AUTHENTICATION_SCHEME + " ", "");
              
            //Decode username and password
            String usernameAndPassword = new String(Base64.decode(encodedUserPassword.getBytes()));;
  
            //Split username and password tokens
            final StringTokenizer tokenizer = new StringTokenizer(usernameAndPassword, ":");
            final String username = tokenizer.nextToken();
            final String password = tokenizer.nextToken();
              
            //Verify user access
            if(method.isAnnotationPresent(RolesAllowed.class))
            {
                RolesAllowed rolesAnnotation = method.getAnnotation(RolesAllowed.class);
                Set<String> rolesSet = new HashSet<String>(Arrays.asList(rolesAnnotation.value()));
                  
                //Is user valid?
                if( ! isUserAllowed(username, password, rolesSet))
                {
                    requestContext.abortWith(ACCESS_DENIED);
                    return;
                }
            }
        }
    }
    private boolean isUserAllowed(final String username, final String password, final Set<String> rolesSet)
    {
        boolean isAllowed = false;

        if(username.equals("julie") && password.equals("qwerty"))
        {
            String userRole = "member";
            //Step 2. Verify user role
            if(rolesSet.contains(userRole))
            {
                isAllowed = true;
            }
        }
        return isAllowed;
    }
}

Here, in this class we are simply fetching the header from the request and fetching the authentication instance from that to find out the username , password, roles etc inforamtion. In the method isUserAllowed, there can be code for the users authentication and we can go to the database to verify the username and password authenticity. isAnnotationPresent method can be used to find out the which annotation is applied over the said method.

4) Finally, create our service class where we have defined the resources with the specific URI's.

import javax.annotation.security.PermitAll;
import javax.annotation.security.RolesAllowed;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.SecurityContext;

// Plain old Java Object it does not extend as class or implements 
// an interface

// The class registers its methods for the HTTP GET request using the @GET annotation. 
// Using the @Produces annotation, it defines that it can deliver several MIME types,
// text, XML and HTML. 

// The browser requests per default the HTML MIME type.

//Sets the path to base URL + /test
@Path("test")
@PermitAll
public class Hello {

    @GET
    @Path("editor")
    @Produces(MediaType.TEXT_PLAIN)
    @RolesAllowed("editor")
    public String editorOnly() {
        return "Got to editor path!";
    }

    @GET
    @Path("member")
    @Produces(MediaType.TEXT_PLAIN)
    @RolesAllowed("member")
    public String memberOnly() {
        return "Got to member path!";
    }

    @GET 
    @Path("open")
    @Produces(MediaType.TEXT_PLAIN)
    public String open(@Context SecurityContext context) {
        return "Open to all! - " + context.getUserPrincipal().getName();
    }
}

Run the program on server and try to access the method with @RolesAllowed("member") and it won't go through the code if the username and password doesn't match with julie and qwert with role as member.

Monday, July 4, 2016

Java : Usage of Enums with Example

Enums are the set of some constants in java. In other words, if you want to define some constants in your program which you are going to use throughout and need not be changed, use Enums. For example, in an application you can represent the different statuses as a list of constants and take Enums type.

Example:
public enum Status{
APPROVED,DECLINED,IN-PROGRESS,PENDING,NEW
}

Hence, it is recommended to use the Enums every-time when a variable seems to take the value definitely from the set of defined values.

Full Java Example to Demonstrate it:

public class EnumExample {

public enum Status {
APPROVED,DECLINED,IN-PROGRESS,PENDING,NEW
}

Status statusVal;

public EnumExample(Status statusVal) {
this.statusVal = statusVal;
}

public void statusDetails() {
switch (statusVal) {
case APPROVED:
System.out.println("Application has been approved");
break;

case DECLINED:
System.out.println("Application has been declined");
break;

case PENDING:
System.out.println("Application is in pending status");
break;

default:
System.out.println("Application is in New status");
break;
}
}

public static void main(String[] args) {
EnumExample approved = new EnumExample(Status.APPROVED);
approved.statusDetails();
EnumExample declined = new EnumExample(Status.DECLINED);
declined.statusDetails();
EnumExample pending = new EnumExample(Status.PENDING);
pending.statusDetails();

}
}
Output would be like: 
Application has been approved
Application has been declined
Application is in pending status



Some points to note about Enums:

* Enums are truely type safe. Means once the value is assigned to an enum  can not be overridden.
* Enum constants are implicitly static and final .
* Enum constants can only be created inside Enums itself. These can not be created using new operator. That's the reason Enums are preferred over the Singleton class.
* Enums can not be declared in a method.
* Enum constructors can have arguments.
* Enum constructors can be overloaded.

Thursday, June 23, 2016

Race Condition in Java

Many of us might be aware of Synchronization in Multi-threading environments in java. 
Race condition in Java is a type of concurrency error which is introduced in your program because  parallel execution of your program by multiple threads at same time, Since Java is a multi-threaded programming language hence risk of Race condition is higher in Java which demands clear understanding of what causes a race condition and how to avoid that. 

To Find Race conditions is very difficult, though since readability of Java code is very good and synchronized constructs are well defined heaps to find race conditions by code review. One can not find the race condition at the time of unit testing. Because race condition is the situation that won't occur often.  You can find the race condition in your program by reviewing it manually or you can use best code review tools available in the marketplace(try to find one such tool and let me know if you found that :).


Mostly it is reviewed that the collections like HashMap must be used with very much care as this is non-synchronized and multiple threads can apply for the re-size operation at the same time. Hence, it is recommended for you that if you are working in the multi-threaded application then use ConcurrentHashMap or use the synchronized HashMap which is again not recommended because of low performance in the multi-threaded environment.



Thursday, June 16, 2016

Executor Framework in Java with Examples

Being a java developer, I strongly recommend to have a thorough knowledge of this topic. Let's start the journey.

Let's go through some basic terms before jumping into the pool so that the things will be clear when we will use them.

* Process -> A program in execution which takes its separate memory space.
* Task -> A task is a logical unit of work.
* Thread -> The mechanism by which the Tasks can be executed asynchroneously. Asynchroneously means on the independent paths by not interfering into other tasks.

We have two policies for executing tasks using threads as follows:-

1) Execution of tasks sequentially using single thread.
2) Execution of each task in it's own thread.

In the first approach, one thread is created at all and the tasks are assigned to it in the sequential manner so that one task can be picked up after completion of another.

In the second approach, a separate thread is created for each task so that each task can be performed independently without waiting.

Executor framework takes birth here because both of the upper approaches have limitations as follows:

Problem with First Approach : It suffers from poor responsiveness and poor throughput.
Problem with Second Approach : It suffers with poor resource management as thread needs to be created for each task (for example,one million threads needed if there are million tasks).

Now the curiosity is how Executor Framework helps out in these scenarios.....

Executor Framework says that:
(i) Create a fixed number of threads in the application, suppose 10. These will be called as Worker Threads.
(ii) Create the tasks and submit it to executor to execute.

Suppose, we have created 10 fixed threads and we have 100 tasks to execute. Then, these ten threads will serve ten tasks at a time and when any task will be completed, the thread which executed this task is free for another task to be assigned to it. Hence the basic idea is , these 10 worker threads will execute these 100 tasks non stop. As and when any thread will be free, it will pick up the next task from the queue.
 
Now, let's discuss about tasks, where are these stored and how they are passed to executor. BlockingQueue is used for the purpose to hold the tasks. When any thread is free, it needs to dequeue the task from the BlockingQueue and execute it.

Executor : Executor is an interface having "void execute(Runnable command)" method.
Executors : Executors is a class having multiple methods to create the pool of worker threads.
ExecutorService : ExecutorService is an interface which extends Executor interface with some extra methods of submitting the tasks,
ScheduledExecutorService : ScheduledExecutorService is another interface with extends ExecutorService interface and provides some extra methods of scheduling the tasks.

Now, let's have an example to explain this all.

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class ExecutorDemo {

    private static ExecutorService executor = null;
    private static volatile Future firstThread = null;
    private static volatile Future secondThread = null;

    public static void main(String[] args) {
        executor = Executors.newFixedThreadPool(2);
        while (true)
        {
            try
            {
                checkTasks();
                Thread.sleep(1000);
            } catch (Exception e) {
                System.err.println("Caught exception: " + e.getMessage());
            }
        }
    }

    private static void checkTasks() throws Exception {
        if (firstThread == null
                || firstThread.isDone()
                || firstThread.isCancelled())
        {
            firstThread = executor.submit(new ThreadOne());
        }

        if (secondThread == null
                || secondThread.isDone()
                || secondThread.isCancelled())
        {
            secondThread = executor.submit(new ThreadTwo());
        }
    }
}

class ThreadOne implements Runnable {
    public void run() {
        while (true)
        {
            System.out.println("Executing thread one");
            try
            {
                Thread.sleep(1000);
            } catch (Throwable e) {
                e.printStackTrace();
            }
        }

    }
}

class ThreadTwo implements Runnable {
    public void run() {
        while (true)
        {
            System.out.println("Executing thread two");
            try
            {
                Thread.sleep(1000);
            } catch (Throwable e) {
                e.printStackTrace();
            }
        }
    }
}

First of all we have created two tasks here as ThreadOne and ThreadTwo. We created the threadpool of worker threads of size 2 by the method newFixedThreadPool(2). then the checkTasks method get called to check if any thread has been done or cancelled. If any task has been done or cancelled then it is getting submitted again to the executor by executor.submit(new ThreadTwo());.

Hence, we have created two threads but are not starting them explicitly, we are just submitting them to executor and these will be executed as per the execution logic.

Friday, June 10, 2016

Java : Usage of ThreadPool in java with Example

Every concept is very big,troublesome and non-understandable if the developer thinks in mind that the concept is tough enough. Many of the java developers would be thinking same about ThreadPool and Executor Framework that it is a very tough topic in concurrency. Believe me , it is the easiest topic I have ever learned. Just follow me to prove that.

First of all let us see the Basics of a Thread : In any multi-threading application, if the developer is using the Thread is by following the below mentioned procedure:-

1) Create a Thread using Runnable or Thread class.
2) Call the start() method over the threads to execute the above created Thread.

Hence, the developer have to take care of creating thread and calling it explicitly. What if the developer doesn't need to create the Thread everytime he needs it? What if the developer doesn't need to call the thread everytime he needs it? That's what ThreadPool does.

ThreadPool is nothing but a good procedure to follow to separate this task of Thread Creation and Execution.

It means we don't need to worry about Thread creation . ThreadPool will handle this task . How ? will see in some moments.

Now, Basic Idea Behind Using ThreadPool:

Let's take an example before jumping in which will illustrate the difficulties if we don't use ThreadPool. Suppose we create Threads in our Multi-threaded application to handle the different tasks. Or , suppose we make the any type of connections per user when the user enters the application. Now, there might be two issues:

1) There might be the limitation to JVM as how number of threads can be created in the application.
2) There might occur OutOfMemory error as there might be limit of memory to hold the Threads and Execute them.

Hence, we need to limit the number of users can enter in the application at a time but it is a big bottleneck for the application to limit the number of users. Hence , we are in trouble . What to do. Thanks to java for ThreadPool implementation. Let's see how ThreadPool handles this:

ThreadPool creates a number of worker Threads at any point of time. You will decide at least how many threads you will need to handle the requests of your application. We have separate methods of the utility class "Executors" for that purpose. Executors is a class and Executor is an interface. For Ex:

ExecutorService service = Executors.newFixedThreadPool(10);    //ExecutorService is another interface which extends Executor interface

Below three can be used to create a ThreadPool:

ExecutorService executorService1 = Executors.newSingleThreadExecutor(); //To create single thread

ExecutorService executorService2 = Executors.newFixedThreadPool(10);

ExecutorService executorService3 = Executors.newScheduledThreadPool(10); // To create a number of threads with time scheduling

Now, the story come here like :- if you have passed 10 in the constructor then 10 worker threads would be created and the game starts.

We just need to submit our tasks to the Executor and it will pick any task from them and will execute it. Very clearly it means that these 10 threads would be called as worker threads. Suppose we have 100 tasks to be done and there are only 10 Threads created using ThreadPool. Now, all of these tasks would be busy executing those tasks one by one. Suppose one Thread has finished it's first task, then it will come in the idle state and will pick the another task from the Blocking Queue. What I mean by Blocking Queue is that to put the tasks in a collection , Blocking Queue is used. So the idle Thread would first Deblock the task from Blocking Queue and then would execute this. That's the magic of ThreadPool,using which we don't need to create hundred Thread at run time for processing hundred tasks. Rather 10 fix wroker threads done the work of hundred requests.

Hence, the work of Creation of Threads and work of Submission is separated by using ThreadPool.

Let's understand all this by the following Example:

public class ThreadPoolExample {

    public static void main(String args[]) {
       ExecutorService service = Executors.newFixedThreadPool(10);
       for (int i =0; i<100; i++){
           service.submit(new TaskToPerform(i));
       }
    }
  
}

In the above class, we have used the fixedThreadPool to create a ThreadPool of fixed size of 10. newFixedThreadPool is a static method of Executors class and the service reference is put in the ExecutorService interface. This class calls the submit method to submit 100 tasks (tasks here are the instances of TaskToPerform class). Hence, 10 threads are responsible to do 100 tasks. No new thread is getting created at run time and not .start() method is getting called from anywhere. All that is abstract to us. All that happends internally. Now, create the TaskToPerform thread.

final class TaskToPerform implements Runnable{
    private int taskId;
  
    public TaskToPerform(int id){
        this.taskId = id;
    }
  
    @Override
    public void run() {
        System.out.println("Task ID : " + this.taskId +" performed by " 
                           + Thread.currentThread().getName());
    }
  
}

Here, the Thread is created implementing Runnable interface. When we run this program produces the following output, Hence, it is proved that pool-1 is having multiple threads created and are being called one by one to perform the tasks.

Output:
Task ID : 0 performed by pool-1-thread-1
Task ID : 3 performed by pool-1-thread-4
Task ID : 2 performed by pool-1-thread-3
Task ID : 1 performed by pool-1-thread-2
Task ID : 5 performed by pool-1-thread-6
Task ID : 4 performed by pool-1-thread-5

Monday, June 6, 2016

Java : Usage of ThreadGroup with Example

All of you from java family must be aware about the packaging concept. Why we create a package in java? We create a package in java just for the categorization of the classes of similar types in separate groups. You might be thinking why I started the package concept under the ThreadGroup. Actually, if I talk in one line, ThreadGroup is nothing but the categorization of the similar threads in separate groups. I hope I am clear.

For better understanding let's take the following points as an example:

1) System Threads are the group of threads which system takes care of. like: Main thread is under the category of System Threads. So, main is a sub-group of System Threads and System Threads can be named as System Thread Group.

2) Suppose I created Thread1, Thread2 and Thread3 in the main method then These can be put in the Sub-Group1 which can be considered as a ThreadGroup. Although, there might be multiple groups of threads like Sub-Group1 hence all will be the ThreadGroups of different kinds. One group of Threads might be given the task of contacting to database. Another group of Threads might be given the task of calculating the business logic, one another group of Threads might be given the task of showing the result on UI. Hence, all of these will be under such Groups which will be called ThreadGroups. The main point to note here is that Main would be the parent ThreadGroup of these sub-groups.

Now, lets discuss about the constructors of ThreadGroup so that we can come to know how to create ThreadGroup in our java multi-threading application:

public static void main (String [] args){
   ThreadGroup group1 = new ThreadGroup ("Group1");         // constructor1
   ThreadGroup group2 = new ThreadGroup (group1, "Group2"); // constructor2
}

In the constructor1, a ThreadGroup is created by just giving the ThreadGroup name.
In the constructor2, a ThreadGroup is created by giving the ThreadGroup name plus the parent name of this ThreadGroup as the first argument.

In the constructor1, it will be considered that the parent of this ThreadGroup is main itself(if it is defined in main or any other context where it would be defined).


How to destory ThreadGroup created in the application:

Once you no longer need the ThreadGroup objects, you can call ThreadGroup's destroy() method like below:

group1.destroy();      // group1 is the reference of the ThreadGroup

Here is some twist in the story: If the top ThreadGroup reference calls destroy() then all the sub groups will be available for the garbage collection because if the parent is destroyed the child ThreadGroups will automatically be nullify and would be available for the garbage collection.Otherwise, destroy() throws an IllegalThreadStateException object.


Let us demonstrate the above story by the below example:

class ThreadGroupDemo
{
   public static void main (String [] args)
   {
      ThreadGroup group1 = new ThreadGroup ("sub-group1");
      Thread t1 = new Thread (group1, "thread 1");
      Thread t2 = new Thread (group1, "thread 2");
      Thread t3 = new Thread (group1, "thread 3");
      group1 = new ThreadGroup (group1,"sub-group2");
      Thread t4 = new Thread (group1, "my fourth thread");
      group1 = Thread.currentThread ().getThreadGroup ();
      int groupCount = group1.activeGroupCount ();
      System.out.println ("Active thread groups in " + group1.getName () + " thread group: " + groupCount);
      group1.list ();
   }
}

Output would be like:

Active thread groups in main thread group: 2
java.lang.ThreadGroup[name=main,maxpri=10]
    Thread[main,5,main]
    java.lang.ThreadGroup[name=subgroup 1,maxpri=10]
        java.lang.ThreadGroup[name=subgroup 2,maxpri=10]


In the example code above, sub-group1 is the sub ThreadGroups of main ThreadGroup. sub-group2 is the sub ThreadGroup of sub-group1.

Now let's talk something about the Priority of ThreadGroups:

Suppose a ThreadGroup is having five Threads and one of the thread can attain a maximum priority from these five threads, then that priority will be the ThreadGroup's maximum priority. Use ThreadGroup's void setMaxPriority(int priority) method to subsequently set the maximum priority.Any threads that you add to the group after setting its maximum priority cannot have a priority that exceeds the maximum. It means if the max priority of the ThreadGroup is set to 6 then any of the threads of this group can not have a priority 7. So, any thread with a higher priority automatically lowers when it joins the thread group. Although, vise-versa is not true i.e. However, if you use setMaxPriority(int priority) to lower a group's maximum priority, all threads added to the group prior to that method call keep their original priorities. For example, if you add a priority 8 thread to a maximum priority 9 group, and then lower that group's maximum priority to 7, the priority 8 thread remains at priority 8.

Let's have an example to demonstrate it:

class MaxPriorityDemo
{
   public static void main (String [] args)
   {
      ThreadGroup group1 = new ThreadGroup ("A Group");
      System.out.println ("group1 maximum priority = " + group1.getMaxPriority ());
      Thread thread1 = new Thread (group1, "X Thread");
      System.out.println ("thread1 priority = " + thread1.getPriority ());
      thread1.setPriority (Thread.NORM_PRIORITY + 1);
      System.out.println ("thread1 priority after setPriority() = " + thread1.getPriority ());
      group1.setMaxPriority (Thread.NORM_PRIORITY - 1);
      System.out.println ("group1 maximum priority after setMaxPriority() = " + group1.getMaxPriority ());
      System.out.println ("thread1 priority after setMaxPriority() = " +thread1.getPriority ());
      Thread thread2 = new Thread (group1, "Y Thread");
      System.out.println ("thread2 priority = " + thread2.getPriority ());
      thread2.setPriority (Thread.NORM_PRIORITY);
      System.out.println ("thread2 priority after setPriority() = " + thread2.getPriority ());
   }
}

Output would be like that:

group1 maximum priority = 10
thread1 priority = 5
thread1 priority after setPriority() = 6
group1 maximum priority after setMaxPriority() = 4
thread1 priority after setMaxPriority() = 6
thread2 priority = 4
thread2 priority after setPriority() = 4


Now, let's talk about the ThreadGroup Interuption:

In addition to using ThreadGroups to limit thread priority, you can accomplish other tasks by calling various ThreadGroup methods that apply to each group's thread. Methods include void suspend(), void resume(), void stop(), and void interrupt(). Because Sun Microsystems has deprecated the first three methods (they are unsafe), we examine only interrupt().

ThreadGroup's has an interrupt() method that allows a thread to interrupt a specific ThreadGroup's all threads and subgroups. Main thread creates multiple threads and each perform a unit of work. Because all threads must complete their work before any thread can examine the results, each thread waits after completing its work. The main thread monitors the working state. When all other threads are waiting, the main thread calls interrupt() to interrupt the other threads' waits. Then those threads can examine and process the results.




Sunday, June 5, 2016

Java : Usage of ThreadLocal with Example

ThreadLocal is a class in java.lang package. The instance of this class is used as a local variable of the Thread in which it is created. Means that ThreadLocal variable is the personal storage of any Thread. Means that ThreadLocal instance stores the values of the local variables of the Threads. Most important point to note here is that the value of the ThreadLocal variable is different for all the Threads. It means when the single Thread will be shared within multiple objects , each time the ThreadLocal variable's value will be differently stored for each Thread as per the user implementation.

Although, it seems that ThreadLocal is taking the place of Synchronization but is not purely true. Partially we can say that Synchronization and ThreadLocal seems to work similar because in Synchronization also the functionality is similar in the sense that one thread can access the safe area at a time and get or set the values freely without any fear. On the other hand ThreadLocal variable plays the same role for each thread having different values for each Thread . Hence, in some situations if we see in our application that the Synchronization costs too much , we can use ThreadLocal variable and perform our task smoothly because the value of the variables would be different for different thread as per hold in the ThreadLocal variable. Let's take an example to explain better this concept:

public class ThreadLocalExampleClass {

    public static class MyRunnable implements Runnable {

        private ThreadLocal<Integer> threadLocal = new ThreadLocal<Integer>();

        @Override
        public void run() {
            threadLocal.set( (int) (Math.random() * 100) );   
            System.out.println(threadLocal.get());
        }
    }

    public static void main(String[] args) throws InterruptedException {
        MyRunnable threadInstance = new MyRunnable();

        Thread thread1 = new Thread(threadInstance);
        Thread thread2 = new Thread(threadInstance);

        thread1.start();
        thread2.start();

    }
}

In the example above, we have created a Thread by implementing Runnable interface, and in the run method we are generating a random number and setting it to the theadLocal variable.

Then, we created the thread instance in the main method and started two threads on the same object. Now, when the first thread will enter the run method the random number generated will be set into this threads's threadLocal variable and when the second thread will enter the run method , again the instance of threadLocal will be created and the random value will be set into that. Hence, two threads on the same object will get and set the different values on the ThreadLocal variable. If we do the same without using ThreadLocal and Synchronization then we can have race condition problem when we are sharing some resource between multiple threads simultaneously. Other way out of this situation is Synchronization but it might be too costly sometimes because one thread will enter the shared object at a time.

Hence, we can conclude that using ThreadLocal variables in the Multi-Threading applications is very helpfull in maintaining the different values for differnt Threads without using Synchronization. This is very usefull in the product selling sites because there the same product can be viewed/update/ordered by multiple users at the same time. Hence, maintaining the history of each customer in the ThreadLocal variable will be very usefull. There we can not use Synchronization because if one user is placing the order, then the other will get blocked till the time. But in the case if we use ThreadLocal, we can easily trace the activities of each user separately. 

Thursday, June 2, 2016

Java : How to take Thread Dump in java OR usage of Jstack and VisualVM to take Thread Dump in Java

It is a very very important topic for a java developer who wants to prove to be a brilliant java developer with respect to multi-threading. It directly means that to become a multi-threading master mind you must know what is Thread Dump and how you can take Thread Dump in your project.

Suppose you are working with multi-threading and you are heavily using the synchronization in your code . Obviously, you will be using the wait(), notify() and notifyAll() methods. On the other you can also use concurrent API's for the same purpose. But while working with the synchronization in your project , it is highly recommended that your code should not cause any deadlock. Deadlock means when two threads are waiting for each other to release the lock they require.

And, if your project is using the synchronization so heavily that you are not able to find out the code which is causing the deadlock. Thread Dump is the relief for such situations. Thread Dump will give you the method and thread name which is causing the deadlock.

Thread Dump not only provides the information about the deadlock but tells the following information as well:

1) Performance Analysis: You can analyze where the application getting down and measure the performance by the help of Thread Dump.
2) Thread States: Can predict which thread is in which state(Start,Runnable,Dead etc.).
3) CPU consumption by the different different threads.
4) Garbage Collection information in detail.


Hence, this tool is very useful for the java family.

Now, we will proceed towards the procedure to take the Thread Dump. Let's move towards the cinema:

There are two ways to take the Thread Dump :
* By Using the jstack tool through command prompt (easiest way).
* By Using VisualVM tool through eclipse.

Let's go with jstack tool first:

1) Open task manager(alt+ctrl+del).
2) Go to processes tab.
3) Click on View menu and select "Select columns..." menu item.
4) Check the PID(Process Identifier) from the list and click on ok button.
5) PID would be added in the list of processes.
6) Copy the PID of javaw.exe process.
7) Open command prompt and go to the bin directory of jdk . like : C:\Program Files\Java\jdk1.7.0_79\bin
8) type the following command in command prompt:
jstack.exe -l PID     (PID is the copied PID from the task manager).
9) Press enter and Thread Dump is getting started.

You can analyse the Thread Dump generated in this way . You can also copy this Dump in any text file like with the following command:
jstack.exe -l PID > ThreadDump.txt
Where ThreadDump.txt is the file on the path : C:\Program Files\Java\jdk1.7.0_79\bin

Now, Let's go with VisualVM approach.

If we are following this approach then we need to install the VisualVM in the eclipse by using the following steps:

Download VisualVM Launcher(Eclipse 3.6+) depending on your eclipse version , extract downloaded zip file.
* Open eclipse and go to Help > Install new software
Click on Add
* Click on Local and browse the extracted launcher
* You may name it whatever you may like.Click Ok.
* Install this software like this way

Restart the Eclipse and follow these steps:

1) Go to windows > Preference > type VisualVM
2) Select visualVM executable location, Select Jdk available on your system and click OK.
3) Right click on class for which you want to run visualVm Launcher and want to analyse.
4) Go to Run As...and then select Run Configurations...
5) Select VisualVM Launcher.

Your full information about the threads causing deadlock and other information will be shown on the window opened in the eclipse. From here you can easily analyze the thread running process.

Happy Learning !!!

Tuesday, May 31, 2016

Java : Usage of SerialversionUID in Detail and How to generate serialversionUID manually

For the clear understanding of this concept you need to be aware of the Serialization and Deserialization concepts of Java.
What we have in Serialization as an overview is:

1)The class which needs to be traveled on network and to be saved anywhere ,must implement the java.io.Serializable interface.

2)All of the fields in that class must be Serializable. If a field is not Serializable, it must be marked transient so that compiler comes to know that this field need not to be saved.

3) The ObjectOutputStream class is responsible to serialize an Object.

4) A file named Engineer.ser is created after the serialization is completed (the class name is Engineer.java).

Following lines of code might be used as a summary:

 FileOutputStream fileOut = new FileOutputStream("/tmp/Engineer.ser");
         ObjectOutputStream out = new ObjectOutputStream(fileOut);
         out.writeObject(e);         // e is the instance of the class Engineer.java
         out.close();
         fileOut.close();

Hence , writeObject is responsible method to serialize the object.Here is magic of serialversionUID takes place. Keep going for the suspense.

On the other hand, when we Deserialize the object back and convert it to the object itself then the readObject method comes into ground.

The signatures of these two methods are as follows:

public final void writeObject(Object x) throws IOException

public final Object readObject() throws IOException, ClassNotFoundException


Now you might be clear about the usage of writeObject and readObject methods , lets proceed towards the concept of serialversionUID.

Every class which we are going to serialize must have a serialVersionUID . This is nothing but Universal Version Identifier. This is used when we Deserialize the class. It checks on the time of Deserialization that whether it is the same class or modified one. It matches up the serialversionUID which was created on the time of serialization. If it does not see the same serialVersionUID then it throws the InvalidClassException.


If you don't provide the serialversionUID to the class then it will create its own.

For example, if you serialize an object of Class Engineer version 1 (E1) which doesn't have a serialversionUID, then you modify it to version 2 (E2) and save it, you'll have two saved files, one with E1 and one with E2 objects. At this point no matter what serial version ID you put in the class, you will be unable to Deserialize one of the saved files.

Hence, if you will put the serialversionUID then there will not be any problem because Deserialization process will get the same serialversionUId all the times and would come to know that this is the same class which was serialized.


How to compute a serialVersionUID ?

There is a serialver tool available if we need to compute the serialVersionUID at any time. It is inbuilt with JDK.

In our case class is Engineer.java and suppose it is in the com.abc package then the computation of serialVersionUID would be like:

1) Open the console.
2) Put the following code and press enter.

serialver com.abc.Engineer

and you'll get output like this:

com.abc.Engineer:    static final long serialVersionUID = -8718469741124325816L;

You can take the code starting with "static" and place it inside your class with other static variables. Now the serial version ID is locked in your class.

Monday, May 30, 2016

Volatile Keyword In Java

We will cover the following about Volatile keyword in this section:

1) What is Volatile Keyword.
2) When to use it?
3) Some points to note about Volatile .
4) Why it is always compared with Synchronized ?
5) Comparison of Volatile and Synchronized :

Let's start the journey:

1) What is Volatile Keyword.
Although, it is rarely used keyword in java yet is the important concept to understand. We can understand this keyword in straight words by saying that the variables which are declared as volatile , the value of those variable will be stored into the main memory directly every time they are updated by the different threads. Hence, every thread will get an updated value of these variables. The volatile keyword can only be applied to a variable, it can not be applied to a class or a method. using volatile keyword along with class and method will result in a compiler error.

2) When to use it?
This variable should be used with the Multi-threading(for example). If we don't use volatile             keyword then the Thread X will not know that variable has been changed by Thread Y. Let's take    an example:

public class ABC extends Thread {
private volatile boolean takeAPause;

public void run() {
while (!takeAPause) {
//further code
}
}
public void commandForStop() {
takeAPause = true;
}
}

Here, If the variable is not declared as volatile, Then the current thread which is in loop will cache the value of the variable at the first round and will never read it again from the memory . By keeping this as volatile, it is guaranteed that the value will come directly from the memory in each round of the loop.

3) Some points to note about Volatile .
* The volatile in Java is only applicable to a variable and using volatile keyword with class and method is a compiler error.
* Volatile guarantees that value of the volatile variables will always be read from main memory directly and not from Thread's local cache.
* Reads and writes are atomic for all variables declared using volatile keyword.
* Changes to a volatile variable are always visible to other threads.
* An access to a volatile variable in never has a chance to block any functionality as this is

4) Why it is always compared with Synchronized?
It is always compared to the Synchronized because both the concepts are under the hood of multi-threading and are related to the variable access-ness throughout the multiple threads.

5) Comparison of Volatile and Synchronized :
Lock : Volatile takes the lock on the variable level globally while Synchronized takes the lock on the monitor level globally.
Null : Null is not allowed in Synchronized while null is allowed in Volatile.
Blocking : Blockage can occur due to Synchronized while blockage can not occur due to Volatile.
Performance : We should use volatile if we are really concerned about the performance other than Synchronized.

Friday, May 27, 2016

Java : Context Switching in Multithreading

When there are multiple threads running in the application, then the CPU cycles are pre-empted from one process and provided to another one based on the high priority or any other algorithm that is being used in that.
The pre-empting of CPU cycles from one process so that the CPU can be available to the second process is called as Context Switching.

Context Switching can be explained in a better way by an example of copy and paste that we use daily.

Let us copy a paragraph "Copied Paragraph" by using CTRL+C or copy command and delete this "Copied Paragraph" before pasting the copied content. The paragraph will be pasted wherever you want. That happens because when we copy the paragraph it is copied instantly and pasted in memory context on a common place which is accessible easily to each process. And when we use to paste it anywhere then the content is not coming from the copied address but is coming from that common place where CPU has pasted the content on the time of copy. Hence, a context is used in between the copy and paste processes. It seems that the pasted data is coming from directly the place from where we have copied that but in real the data is getting pasted in the context at the time of copy and is copied again from there and pasted to the location where we want it at the time of paste process. This is called the context switching.

Hence , in Multi-threading when the cycles of a thread are pre-empted then the state of the thread is saved to the context and is resumed from the context when the CPU comes back to this thread to execute its remaining part. So, its impossible to work with threads without context switching. Although its a basic discussion about this topic and one can dig into it much more. 

Thursday, May 26, 2016

this keyword in Java and How "this" holds the reference of the current object in Java

However, everybody who belongs to Java family knows that "this" holds the reference of current object. But, the original effort comes in ground when the question is asked from another corner and that is : How "this" holds the reference of current object. How come the reference of current object in "this" keyword.

Well, nothing to worry, here is the explanation.

Let's creat a class as follows:

public class ReferenceTest{
int a;
int b;

public ReferenceTest(int x,int y){
this.a=x;
this.b=y;
}

public static void main(String arg[]){

ReferenceTest rt = new ReferenceTest(10,20);
System.out.println("value of a is "+rt.a +" and the value of b is "+rt.b);

}
}

So, as we see the assignment of x in "this.a=x" goes to a which is a variable of this class.
It means this is containing the reference rt. But, how rt reaches to this keyword is the whole suspence.

Well, let's proceed a step ahead. If we dig into the details of the implementation and the java code written for constructors ,that is abstract from the end user, we will find the below story:

public class ReferenceTest{
int a;
int b;

public ReferenceTest(int x,int y,ReferenceTest this){
this.a=x;
this.b=y;
}

public static void main(String arg[]){

ReferenceTest rt = new ReferenceTest(10,20,rt);
System.out.println("value of a is "+rt.a +" and the value of b is "+rt.b);

}
}

It means when we are creating the object of this class and compiles it, compiler itself sends the reference of current object (rt in our case) to the constructor and "this" is just the variable name which is containing the current object reference in this way. Hence, whatever the operation we will perform on "this" , that would be reflected to the current object. That' it.

Kindly comment below if you have any question or query regarding this.

Happy Learning.

Tuesday, May 24, 2016

Difference between subsequence and substring in Java

Although we know that String.subSequence and String.subString methods produce the same output yet there are some differences in these methods . Also, we will go through the concept that why String has subSequence method at all when we have subString method.


1) Return Type :: String.subSequence(begin,end) method returns a CharSequence while String.subString(begin,end) returns the String reference. Although it does not make any difference to the end result and both will be same.
For Example:
String string = "Punia";
CharSequence subSequence = string .subSequence(0,2);
String subString = string .subString(0,2);

If we print the values of subSequence and subString, it will be Pu in both the cases. Hence the only difference is the return type. Below are the signatures of both:

public CharSequence subSequence(int beginIndex, int endIndex)
public String substring(int beginIndex, int endIndex)

2) Consecutivity : If we talk about the basics of these two concepts, Substrings are the consecutive combinations of the letters while subsequences are the non-consecutive combinations, like:

if "abc" is series of characters then ,

substrings: a, ab, abc, bc, c and the empty substring.
subsequences: a, b, ab, c, ac, bc, abc and the empty subsequence.


From the upper points , it is clear that there is no difference in usage of these two methods, So why the core team of java put the subsequence method in the methods list of Stirng class. Here is the reason.

String class implements the CharSequence interface. And, CharSequence interface have a method named subSequence, hence String must give the implementation of this method whether it's functionality is similar to the substring or not.

Although, it's a point of confusion that they could have avoided the substing(begin,end) method to be defined in the String class. The reason is, they could not stop the subsequence method to come in the class if they are implementing the CharSequence interface. Rather, they could stop themselves to put the substring(begin,end) mehtod in the String class. They could have defined other Substring methods with different parameters plus this subsequence method is dropping in from CharSequence interface. Might be a matter of thought.

Java : How To Calculate Manually The Hashcode Of Any String OR How hashcode method works internally to calculate hashcode of a String

Though its not such a practical thing that would be needed in daily practices of coding, yet we are going to cover this part of String because its been asked by many interviewers now a days and can also be used in some situations while coding where it requires to calculate the hashcode and the developer needs some further operations on the calculated hashcode.

Well, we have a simple formula for calculating the hashcode of any String manually and that is :

hashcode = s[0]*31^(n-1) + s[1]*31^(n-2) + ......................+s[n-1].

Here, s[0], s[0] ...s[n-1] are the ASCII values of the characters occurring in the String. n is the length of the String.

For example:

            Let us suppose, we have a String like follows.
            String str = "ab";

and we run str.hashcode() then it will produce the output as 3105. Here is how it comes,

hashcode = ASCII(a)*31^(1) + ASCII(b);
               = 97*31+98=3105.

And this is the reason why the hashcode of space(" ") is equal to the ASCII value of space (" ").

Also, the same reason why the hashcode of empty string is ZERO.

That's it. Kindly, post in the comments if you have any questions or queries regarding this. Happy learning.