Sunday, October 6

'javac' is not recognized as an internal or external command, operable program or batch file.

'javac' is not recognized as an internal or external command, operable program or batch file.

This error might occur as JDK is not set in path System variable in environment variable


-->


To set this find out where Java is installed on your system

Let's say you have Java 7 installed on your system , copy bin directory path as below :

\jdk1.7.0\bin

Now access the path variable in environment variable from :

Control Panel\System and Security\System



Set Java_Home as
\jdk1.7.0\bin

then set  path variable value as : %Java_Home%;(current value in path)

OR

set path directly as
\jdk1.7.0\bin;(current value in path)


If Still it does not work and throw same error , Access command line 

and check the path with path command 

Now see if \jdk1.7.0\bin is there in the output ..

If it is not there then set path from command line using command 

set path =%path%;\jdk1.7.0\bin

Now check again the value of path variable , \jdk1.7.0\bin should be there 

Try executing program again , it should work now.. 












Builder Design Pattern

What is builder design pattern ?

This is used to segregate the logic for creation of complex objects. 

For example

 If we want to create an object of class representing real Estate residential project . We need to take into account lot of factors in building full fledged object . Object will consist of features like 
 payment plan 
layout 
construction plan 
builder information 
land details 
finance details 
location details
salient features 

and so on.....




So we won't prefer to embed the logic of creation of this instance in actual business logic and unnecessarily clutter the business logic flow Instead It would be good to have a dedicated service which can build up this object and once prepared can return it to business logic . Thus actual business logic remains agnostic of all object creation complexities..

So how do we achieve that in Object oriented language . 


Let us try to understand this with code. As usual I have written lot of System.out.println statements in the code to bring are execution flow steps in print statements . This code can be directly copied and executed .All steps of design pattern will be clearly written on console.


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

//This is the Client class which basically place an order. Here this client first place an order of //commercial project and after it's successful delivery It approaches for residential project and //place an order for that.



package realEstate;

public class Client {

    /**
     * @param args
     */
    public static void main(String[] args) {
      
        projectOwner owner=new projectOwner(new CommercialProjectBuilder());
        owner.placeRoder();
        owner.getProject();
        System.out.println("CLIENT :::: Thank you for timely delivry of commerical project");
        System.out.println("===============================================================");
        System.out.println("CLIENT :::: Now let's deal in residenrial");
         owner=new projectOwner(new ResidentialProjectBuilder());
        owner.placeRoder();
        owner.getProject();
        System.out.println("CLIENT :::: Thank you for timely delivry of Residential project.. Rocking performance");
    }

}

// This is project Owner . Client passes the type of project It is looking for : commercial or residential //and creates Project Owner instance . Owner will further place order of construction to Commercial //or Residential department based of which object is passed by client 
class projectOwner{
    ProjectBuiding building;
    projectOwner(ProjectBuiding building){
        this.building=building;
        }
   
  void  placeRoder(){
      building.constructBase();
      building.constructFloors();
      building.doFinishing();
      building.decorate();

   }
 
  ProjectBuiding  getProject(){
      return building;
  }
  
   
}

// Interface for Residential and commercial project builder classes 
interface ProjectBuiding{
   
   
   
    void constructBase();
   
    void constructFloors();
   
    void doFinishing();
   
    void decorate();
   
   
}

// entire process and logic of building a residential project is encapsulated in this class
class ResidentialProjectBuilder implements ProjectBuiding {
   
    ResidentialProjectBuilder(){
        System.out.println("ResidentialProjectBuilder:::Thank you for reaching us..We deal in Residential Projects..");
    }

    public void constructBase() {
      
        System.out.println("ResidentialProjectBuilder:::Construction is already started.. Promise to deliver on time ");
    }

    public void constructFloors() {
        System.out.println("ResidentialProjectBuilder::::Construction is on full Swing.. Pay installments timely ");
       
    }

    public void doFinishing() {
        System.out.println("ResidentialProjectBuilder::::About to deliver .. Have litte more Patience ");
       
    }

    public void decorate() {
        System.out.println("ResidentialProjectBuilder:::IT is well decorated.. Ready to move");
       
    }
   
}


// entire process and logic of building a Commercial project is encapsulated in this class


class CommercialProjectBuilder implements ProjectBuiding{

    CommercialProjectBuilder(){
        System.out.println("CommercialProjectBuilder ::: Thank you for reaching us..We deal in Commercial Projects..");
    }
   
    public void constructBase() {
        System.out.println("CommercialProjectBuilder :::Construction is already started.. Promise to deliver on time ..");
       
    }

    public void constructFloors() {
        System.out.println("CommercialProjectBuilder :::Construction is on full Swing.. Pay installments timely ");
       
    }

    public void doFinishing() {
        System.out.println("CommercialProjectBuilder :::About to deliver .. Have litte more Patience ");
       
    }

    public void decorate() {
        System.out.println("CommercialProjectBuilder :::IT is well decorated.. Ready to move");
       
    }
   
}


 Below would be the output of console on program execution
-------------------------------------------------------------------------------------------










CommercialProjectBuilder ::: Thank you for reaching us..We deal in Commercial Projects..
CommercialProjectBuilder :::Construction is already started.. Promise to deliver on time ..
CommercialProjectBuilder :::Construction is on full Swing.. Pay installments timely
CommercialProjectBuilder :::About to deliver .. Have litte more Patience
CommercialProjectBuilder :::IT is well decorated.. Ready to move
CLIENT :::: Thank you for timely delivry of commerical project

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



CLIENT :::: Now let's deal in residenrial
ResidentialProjectBuilder:::Thank you for reaching us..We deal in Residential Projects..
ResidentialProjectBuilder:::Construction is already started.. Promise to deliver on time
ResidentialProjectBuilder::::Construction is on full Swing.. Pay installments timely
ResidentialProjectBuilder::::About to deliver .. Have litte more Patience
ResidentialProjectBuilder:::IT is well decorated.. Ready to move
CLIENT :::: Thank you for timely delivry of Residential project.. Rocking performance

 


-->

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.