Friday, October 4

Blocking Queue and Consumer pattern for fixed resources

                                 Blocking Queue and Consumer pattern for fixed resources

What is blocking Queue 

Blocking Queue is a collection   introduced in java 1.6 . It provides lot of useful methods to write efficient mutithreaded and concurrent program . 

We will discuss here two very important methods of blocking  Queue here 

1. put() : this method put an object in the queue only If there is capacity to add. In blocking queue ,we can define the maximum possible size of the queue at Queue instance construction time. 

So If we say : 

    BlockingQueue tokensQueue = new LinkedBlockingQueue(10);

maximum allowed Token objects in queue is 10 . 

Blocking Queue is interface and LinkedBlockingQueue is one of it's implementation. 

So if current size of queue is 10 and we call put method like queue.put(Object) , this call will be blocked until an object is consumed from the queue by one of the consumer . After consumption , current size will reduce and queue will have capacity to add more objects. Then queue.put(Object) cal will succeed . 

2. take() : This method retrieves the Object from Queue. This is also blocking call If there is no object available in the queue and queue is empty . It will continue waiting until and object is inserted in the queue by some other thread . Once at least once object is available in queue , queue.take() method will succeed and blocking will break.

One more method I would like to discuss is offer() . offer() is method that puts object in the queue But that is not a blocking call. It simply returns false If object is not added due to capacity and does not wait for Queue getting space for another object. 





-->



Before starting my code example I would like to touch upon one more thing : 

AtomicInteger : this is class available in java now to provide atomic operations while accessing and modifying value of a primitive type. It provides certain methods to provide synchronization and atomicity . Will see in the example How to use that ..

 So now lets move to our code example :

Consider there is a class of 1000 odd students. Now being summer season students keep of going out of class to take water . Teacher can not send a lot of students together So a rule is maintained that at one time maximum of only 10 students can stay outside . 

So implement this practically , 10 tokens are created. Every time student goes outside has to carry a token . After returning will put the token back in pool for someone else to use. 





So how can we implement this using Blocking Queue : 

As usual below code has lot of System.out.println statements . Executing this program will print them on console and they will take you through all the steps followed. 

------------------------------------


import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.atomic.AtomicInteger;


// This is the class where tokens are created . It interact with other classes to create and overall //flow.
 
public class Class {


    BlockingQueue tokensQueue = new LinkedBlockingQueue(10);

    public static void main(String[] args) {

        Class Class = new Class();
        Class.generateTokens();

    }
// this method is doing nothing but adding 10 instances of Token //class in queue
    public void generateTokens() {

        for (int i = 0; i < 10; i++) {
            System.out.println("generating token no" + i);

            try {
                tokensQueue.put(new Token());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }

        System.out.println("Now all 10 tokens are created and are stored in blocking queue ");


// Here consumer thread is started to start using tokens
        Thread BCC = new Thread(new Student(tokensQueue));
        BCC.start();

    }

}
// This is Token class . These tokens are allotted to students 

 
class Token {

    public static AtomicInteger tokenNumber = new AtomicInteger(0);

    public int number_Of_Token_Assigned;

    void useToken(Token token) {
        System.out.println("Student is using token " + token.number_Of_Token_Assigned);
   
}

    Token() {
        this.number_Of_Token_Assigned = tokenNumber.incrementAndGet();
    }

}

// Students are continuously using the tokens So infinite while loop is executed... 
 
class Student implements Runnable {
    BlockingQueue tokenQueue;

    Student(BlockingQueue tokenQueue) {
        this.tokenQueue = tokenQueue;
    }

    public void run() {

        try {
            while (true) {
                System.out.println("student request for a token..");
                Token token = tokenQueue.take();
                System.out.println(token.number_Of_Token_Assigned + " is the token no alloted ...");
                token.useToken(token);
                System.out.println("token" + token.number_Of_Token_Assigned
                        + "is used .Now putting that back into tokenQueue");


                tokenQueue.offer(token);
            }
        } catch (InterruptedException e) {

            e.printStackTrace();
        }

    }

}
 


This will print on console something like :





-----------------------------
2 is the token no alloted ...
Student is currently using token
token2is used .Now putting that back into tokenQueue
student request for a token..
3 is the token no alloted ...
Student is currently using token
token3is used .Now putting that back into tokenQueue
student request for a token..
4 is the token no alloted ...
Student is currently using token
token4is used .Now putting that back into tokenQueue
student request for a token..
5 is the token no alloted ...
Student is currently using token
token5is used .Now putting that back into tokenQueue
student request for a token..
6 is the token no alloted ...
Student is currently using token
token6is used .Now putting that back into tokenQueue
student request for a token..
7 is the token no alloted ...
Student is currently using token
token7is used .Now putting that back into tokenQueue
student request for a token..
8 is the token no alloted ...
Student is currently using token
token8is used .Now putting that back into tokenQueue
student request for a token..
9 is the token no alloted ...
Student is currently using token
token9is used .Now putting that back into tokenQueue
student request for a token..
10 is the token no alloted ...
Student is currently using token
token10is used .Now putting that back into tokenQueue
student request for a token..
1 is the token no alloted ...
Student is currently using token
token1is used .Now putting that back into tokenQueue
student request for a token..
2 is the token no alloted ...
Student is currently using token
token2is used .Now putting that back into tokenQueue
student request for a token..
3 is the token no alloted ...
Student is currently using token
token3is used .Now putting that back into tokenQueue
student request for a token..
4 is the token no alloted ...
Student is currently using token
token4is used .Now putting that back into tokenQueue
student request for a token..
5 is the token no alloted ...
Student is currently using token
token5is used .Now putting that back into tokenQueue
------------

----------
--------

 You can repeat tis example with more consumer by creating more consumer classes as below and see how output comes 

public void generateTokens() {

        for (int i = 0; i < 10; i++) {
            System.out.println("generating token no" + i);

            try {
                tokensQueue.put(new Token());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }

        System.out.println("Now all 10 tokens are created and are stored in blocking queue ");

        Thread BCC = new Thread(new Student(tokensQueue));
        BCC.start();

  Thread BCC1 = new Thread(new Student(tokensQueue));
        BCC1.start();

  Thread BCC2 = new Thread(new Student(tokensQueue));
        BCC2.start();


    }



Monday, September 30

error:Class names are only accepted if annotation processing is explicitly requested






-->

This error generally occurs when one try to compile a java file without appending .java extension in file name ..

For example

I have below class at location C:\Users\mkum\Desktop\java


public class Test{

               
                public String result() {

                                return "abc";

                }

}

On compiling this as below :

C:\Users\mkum\Desktop\java>javac Test

error: Class names, 'Test', are only accepted if annotation processing is explicitly requested
1 error








So correct way to compile class from command line would be

C:\Users\mkum\Desktop\java>javac Test.java

Now it will compile well and will generate the binary file.




Saturday, September 28

Visitor Design pattern in java

                                             Visitor Design pattern in java

Think from a visitors perspective for a while ---

A person comes from US to visit India ... 

Visitor want to visit certain places .. He has the list of places he want to visit . 

So he provide the same list to his travel organizer and ask him to prepare a suitable plan for him to make him travel all the places available in the list.

Organizer takes the list and start contacting his site contact persons . He ask his agents at all places visitor want to visit to accept and welcome the visitor and make him Visit the place. 

So here entire task is divided in to few sub tasks :

1. Visitor -- Ask visitor to plan . Visit the places.
2. Organizer -- activate his place specific agents 
3. Place agents --- Accept the visitor and make him Visit. 





Now lets understand this scenario in Object oriented world of java technology . How design pattern deals with this situation.

As usual , I would be providing all steps involved in the process in system.out.println statements. Code below can be copied as it is and executed in any java environment . System.out,print statements will print all the steps involved in process on console as well


==============================================

Visitor class represents the visitor . He creates the list of places to be visited and invoke schedule method on organizer . Before invoking schedule method Visitor creates instance of Organizer and while constructing instance it uses one argument constructor to initiate Organizer instance with a state having list of Place instances.



package incredibleIndia;

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

public class Visitor implements IVisotor {

    /**
     * @param args
     */
    public static void main(String[] args) {
        List places = new ArrayList();
        places.add(new IndiaGate());
        places.add(new Tajmahal());
        places.add(new BirSujra());
        places.add(new RedFort());
        places.add(new JamaMasjid());
        Organizer org = new Organizer(places);
        System.out
                .println("Visitor ask Organizer to plan for his visit. Visitor provides Organizer the list of places he is interested in ");
        org.schedule(new Visitor());
       
        System.out.println("Visotor Thanks  all .. It wwas wondeful experience... truely incredible India");

    }

    public void visit(IndiaGate india) {
        System.out.println("visitng india gate.....");

    }

    public void visit(Tajmahal india) {
        System.out.println("visitng Tajmahal.....");

    }

    public void visit(BirSujra birSujra) {
        System.out.println("visitng birSujra.....");

    }

    public void visit(RedFort redFort) {
        System.out.println("visitng RedFort....");

    }

    public void visit(JamaMasjid jamaMasjid) {
        System.out.println("visitng JamaMasjid....");

    }

}

This is contract interface which is helping Visitor to visit the places available in the list. Visitor implements this interface and implement are overloaded methods each referring to one single element /place 
interface IVisotor {

    void visit(IndiaGate indiaGate);

    void visit(Tajmahal tajMahal);

    void visit(BirSujra birsujra);

    void visit(RedFort redFort);

    void visit(JamaMasjid jamaMasjid);
}

This is interface for Organizer to implement . It has only schedule method

interface IOrganize {

    public void schedule(IVisotor visitor);

}

Organizer takes the list of places in constructor . In schedule method It iterates over Place instances and invoke their accept method to make the places accept the visitor . in accept() method it passes the Visitor as parameter. Each Place instance being iterated here refer to once actual Place / class implementing Place interface
class Organizer implements IOrganize {
    List places = new ArrayList();

    public Organizer(List places) {
        this.places = places;
    }

    public void schedule(IVisotor visitor) {

        System.out
                .println("Organizer get through the process to initiate the visit and ask place coordinators to welcomes the visitor  ");

        for (Place place : places) {
            place.accept(visitor);
        }

    }

}

Interface for place . Has only one method . Accept . This needs to be implemented by all Place classes
interface Place {

    void accept(IVisotor visitor);

}

One of the class implementing Place interface and defining the logic of accept method . Accept method will accept the visitor and then on visitor instance invoke visit method and pass the current place instance to the visitor . Visitor can use this instance to visit the place 

class IndiaGate implements Place {

    public void accept(IVisotor visitor) {

        System.out.println("IndiaGate accept the visotr and welcomes him");

        System.out.println("IndiaGate visit is started");
        visitor.visit(this);
    }

}


One of the class implementing Place interface and defining the logic of accept method . Accept method will accept the visitor and then on visitor instance invoke visit method and pass the current place instance to the visitor . Visitor can use this instance to visit the place 


class Tajmahal implements Place {

    public void accept(IVisotor visitor) {

        System.out.println("Tajmahal accept the visotr and welcomes him");

        System.out.println("Tajmahal visit is started");
        visitor.visit(this);
    }

}


One of the class implementing Place interface and defining the logic of accept method . Accept method will accept the visitor and then on visitor instance invoke visit method and pass the current place instance to the visitor . Visitor can use this instance to visit the place 


class RedFort implements Place {

    public void accept(IVisotor visitor) {
        System.out.println("RedFort accept the visotr and welcomes him");

        System.out.println("RedFort visit is started");
        visitor.visit(this);
    }

}



-->


One of the class implementing Place interface and defining the logic of accept method . Accept method will accept the visitor and then on visitor instance invoke visit method and pass the current place instance to the visitor . Visitor can use this instance to visit the place 


class JamaMasjid implements Place {

    public void accept(IVisotor visitor) {
        System.out.println("JamaMasjid accept the visotr and welcomes him");

        System.out.println("JamaMasjid visit is started");
        visitor.visit(this);
    }

}


One of the class implementing Place interface and defining the logic of accept method . Accept method will accept the visitor and then on visitor instance invoke visit method and pass the current place instance to the visitor . Visitor can use this instance to visit the place 


class BirSujra implements Place {

    public void accept(IVisotor visitor) {
        System.out.println("BirSujra accept the visotr and welcomes him");

        System.out.println("BirSujra visit is started");

        visitor.visit(this);
    }

}








 Now let us see the output of console
 -------------------------------------------------------------------------------
Visitor ask Organizer to plan for his visit. Visitor provides Organizer the list of places he is interested in 


Organizer get through the process to initiate the visit and ask place coordinators to welcomes the visitor  


IndiaGate accept the visotr and welcomes him
 IndiaGate visit is started

 visiting india gate.....


Tajmahal accept the visotr and welcomes him

Tajmahal visit is started
 visiting Tajmahal.....


BirSujra accept the visotr and welcomes him

BirSujra visit is started
 visitng birSujra.....


RedFort accept the visotr and welcomes him

RedFort visit is started
 visitng RedFort....


JamaMasjid accept the visotr and welcomes him

JamaMasjid visit is started
 visitng JamaMasjid....


Visotor Thanks  all .. It wwas wondeful experience... truly incredible India