Sunday, January 19, 2014

Proxy Design Pattern


Proxy design pattern allows you to create a wrapper class over real object.Wrapper class which is proxy,controls access to real object so in turn you can add extra functionalities to real object without changing real object's code.

As described by GoF:
"Provide a surrogate or placeholder for another object to control access over it."





Real life example may be proxy server used in IT companies for internet access.It blocks access to social networking sites like facebook,twitter and other contents which are not work related.








When to use it:

Proxy is required whenever there is need for more sophisticated or versatile reference to an object than a simple pointer.Here are some situations when proxy pattern is applicable.
  1. A remote proxy provides a local representative for an object in a different address space.Providing interface for remote resources such as web service or REST resources.
  2. A virtual proxy creates expensive object on demand.
  3. A protection proxy controls access to the original object.Protection proxies are useful when objects should have different access rights.
  4. A smart reference is a replacement for a bare pointer that performs additional actions when an object is accessed.
  5. Adding a thread-safe feature to an existing class without changing the existing class's code. 

Read more at http://javapostsforlearning.blogspot.com/2012/09/proxy-design-pattern-in-java.html#IESZ2CQGT1L5udOK.99
When to use it:

Proxy is required whenever there is need for more sophisticated or versatile reference to an object than a simple pointer.Here are some situations when proxy pattern is applicable.

  1.     A remote proxy provides a local representative for an object in a different address space.Providing interface for remote resources such as web service or REST resources.
  2.     A virtual proxy creates expensive object on demand.
  3.     A protection proxy controls access to the original object.Protection proxies are useful when objects should have different access rights.
  4.     A smart reference is a replacement for a bare pointer that performs additional actions when an object is accessed.
  5.     Adding a thread-safe feature to an existing class without changing the existing class's code.











Lets see one Example :

package com.javasouls.proxypattern;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;



interface Calculator{
    public int calculate(int operand1, int operand2, Operator operator);
}
enum Operator {
    ADD, MULTIPLY, SUBTRACT, DIVIDE, POWER;
    Operator (){

    }
}

class CalculatorImpl implements Calculator {

    public int calculate(int operand1,int operand2, Operator operator){
        int result = -1;
        switch (operator) {
        case ADD:
            result = operand1 + operand2;
            break;
        case SUBTRACT:
            result = operand1 - operand2;
            break;
        case MULTIPLY:
            result = operand1 * operand2;
            break;
        case DIVIDE:
            result = operand1 / operand2;
            break;
        case POWER:
            result = operand1 ^ operand2;
            break;
        default:
           
            break;
        }
        return result;
    }
}

class CalculatorInvocationHandler implements InvocationHandler{

    private Object realSubject = null;
    public CalculatorInvocationHandler (Object realSubject){
        this.realSubject = realSubject;
    }
    @Override
    public Object invoke(Object proxy, Method method, Object[] args)throws Throwable {
        Object result = null;
        try{
            result = method.invoke(realSubject, args);
        }
        catch(Exception e){
            e.printStackTrace();
        }
       
        return result;
    }
   
}
public class ProxyPattern {
    public static void main(String[] args) {
        Calculator realSubject = new CalculatorImpl();
        Calculator proxy = (Calculator)Proxy.newProxyInstance(realSubject.getClass().getClassLoader(), realSubject.getClass().getInterfaces(), new CalculatorInvocationHandler(realSubject));
        System.out.println("Calculating via proxy object "+proxy.calculate(2, 3, Operator.ADD));
    }
}






Real life example may be proxy server used in IT companies for internet access.It blocks access to social networking sites like facebook,twitter and other contents which are not work related.

Proxy design pattern allows you to create a wrapper class over real object.Wrapper class which is proxy,controls access to real object so in turn you can add extra functionalities to real object without changing real object's code.
As described by GoF:
"Provide a surrogate or placeholder for another object to control access over it."

Read more at http://javapostsforlearning.blogspot.com/2012/09/proxy-design-pattern-in-java.html#VpxrVQBCAgI63W4S.99
Proxy design pattern allows you to create a wrapper class over real object.Wrapper class which is proxy,controls access to real object so in turn you can add extra functionalities to real object without changing real object's code.
As described by GoF:
"Provide a surrogate or placeholder for another object to control access over it."

Read more at http://javapostsforlearning.blogspot.com/2012/09/proxy-design-pattern-in-java.html#VpxrVQBCAgI63W4S.99
Proxy design pattern allows you to create a wrapper class over real object.Wrapper class which is proxy,controls access to real object so in turn you can add extra functionalities to real object without changing real object's code.
As described by GoF:
"Provide a surrogate or placeholder for another object to control access over it."

Read more at http://javapostsforlearning.blogspot.com/2012/09/proxy-design-pattern-in-java.html#VpxrVQBCAgI63W4S.99
Proxy design pattern allows you to create a wrapper class over real object.Wrapper class which is proxy,controls access to real object so in turn you can add extra functionalities to real object without changing real object's code.
As described by GoF:
"Provide a surrogate or placeholder for another object to control access over it."

Read more at http://javapostsforlearning.blogspot.com/2012/09/proxy-design-pattern-in-java.html#VpxrVQBCAgI63W4S.99
Proxy design pattern allows you to create a wrapper class over real object.Wrapper class which is proxy,controls access to real object so in turn you can add extra functionalities to real object without changing real object's code.
As described by GoF:
"Provide a surrogate or placeholder for another object to control access over it."

Read more at http://javapostsforlearning.blogspot.com/2012/09/proxy-design-pattern-in-java.html#VpxrVQBCAgI63W4S.99
Proxy design pattern allows you to create a wrapper class over real object.Wrapper class which is proxy,controls access to real object so in turn you can add extra functionalities to real object without changing real object's code.
As described by GoF:
"Provide a surrogate or placeholder for another object to control access over it."

Read more at http://javapostsforlearning.blogspot.com/2012/09/proxy-design-pattern-in-java.html#VpxrVQBCAgI63W4S.99
Proxy design pattern allows you to create a wrapper class over real object.Wrapper class which is proxy,controls access to real object so in turn you can add extra functionalities to real object without changing real object's code.
As described by GoF:
"Provide a surrogate or placeholder for another object to control access over it."

Read more at http://javapostsforlearning.blogspot.com/2012/09/proxy-design-pattern-in-java.html#VpxrVQBCAgI63W4S.99
Proxy design pattern allows you to create a wrapper class over real object.Wrapper class which is proxy,controls access to real object so in turn you can add extra functionalities to real object without changing real object's code.
As described by GoF:
"Provide a surrogate or placeholder for another object to control access over it."

Read more at http://javapostsforlearning.blogspot.com/2012/09/proxy-design-pattern-in-java.html#VpxrVQBCAgI63W4S.99
Proxy design pattern allows you to create a wrapper class over real object.Wrapper class which is proxy,controls access to real object so in turn you can add extra functionalities to real object without changing real object's code.
As described by GoF:
"Provide a surrogate or placeholder for another object to control access over it."

Read more at http://javapostsforlearning.blogspot.com/2012/09/proxy-design-pattern-in-java.html#VpxrVQBCAgI63W4S.99
Proxy design pattern allows you to create a wrapper class over real object.Wrapper class which is proxy,controls access to real object so in turn you can add extra functionalities to real object without changing real object's code.
As described by GoF:
"Provide a surrogate or placeholder for another object to control access over it."

Read more at http://javapostsforlearning.blogspot.com/2012/09/proxy-design-pattern-in-java.html#VpxrVQBCAgI63W4S.99
How to get the Race condition among multiple threads and how to handle using wait/notify (inter thread communication)
package com.rafi.concurrency;


public class RaceConditionTest2 {

    public volatile Object locker1 = new Object();
    public volatile Object locker2 = new Object();
    public volatile Object locker3 = new Object();
   
    public volatile boolean waitLock3 = false;
    public volatile boolean waitLock2 = false;
    public volatile boolean waitLock1 = false;
   
    public class MyRunnable2 implements Runnable {
        public void run() {
            System.out.println( "MyRunnable2 started" );
            synchronized( locker3 ) {
               
                try {
                    System.out.println( "r2: waiting for locker3" );
                    waitLock3 = true;
                    locker3.wait();
                    System.out.println( "r2: got locker3" );
                } catch ( java.lang.InterruptedException e ) {
                    System.out.println( "e: " + e );
                }
            }



            for ( int c = 0; c < 2; ++c ) {

                synchronized( locker2 ) {

                    try {
                        System.out.println( "r2: waiting for locker2" );
                        locker2.wait();
                        System.out.println( "r2: got locker2" );
                    } catch ( java.lang.InterruptedException e ) {
                        System.out.println( "e: " + e );
                    }
                }

                System.out.println( "r2: " + ( c ) );
                /*try {
                    Thread.sleep(1);
                } catch ( Exception e ) {
                }
*/
                synchronized( locker1 ) {
                    System.out.println( "r2: signaling locker1" );
                    locker1.notify();
                    System.out.println( "r2: locker1 signaled" );
                }
            }
        }
    }

    public class MyRunnable1 implements Runnable {
        public void run() {
            System.out.println( "MyRunnable1 started" );

            synchronized( locker3 ) {
                try {
                    System.out.println( "r1: waiting for locker3" );
                    locker3.wait();
                    System.out.println( "r1: got locker3" );
                } catch ( java.lang.InterruptedException e ) {
                    System.out.println( "e: " + e );
                }
            }

            for ( int c = 0; c < 2; ++c ) {


                synchronized( locker1 ) {

                    try {
                        System.out.println( "r1: waiting for locker1" );
                        locker1.wait();
                        System.out.println( "r1: got locker1" );
                    } catch ( java.lang.InterruptedException e ) {
                        System.out.println( "e: " + e );
                    }
                }

                System.out.println( "r1: " + ( c ) );
                /*try {
                    Thread.sleep(1);
                } catch ( Exception e ) {
                }
*/
                synchronized( locker2 ) {
                    System.out.println( "r1: signaling locker2" );
                    locker2.notify();
                    System.out.println( "r1: locker2 signaled" );
                }

            }
        }
    }

    public static void main(String[] args) {
        RaceConditionTest t = new RaceConditionTest();
        t.test();
    }

    public void test() {
        MyRunnable1 r1 = new MyRunnable1();
        MyRunnable2 r2 = new MyRunnable2();
        Thread t1 = new Thread( r1 );
        Thread t2 = new Thread( r2 );
        t1.start();
        t2.start();

        /*try {
            Thread.sleep(1000);
        } catch ( Exception e ) {

        }*/
        while(!waitLock3){
            synchronized( locker3 ) {
                System.out.println( "main: signaling locker3" );
                locker3.notifyAll();
//                locker3.notify();
                waitLock3 = false;
                System.out.println( "main: locker3 signaled" );
            }   
        }
       
/*
        try {
            Thread.sleep(1000);
        } catch ( Exception e ) {

        }*/

        synchronized( locker1 ) {
            System.out.println( "main: signaling locker1" );
            locker1.notify();
            System.out.println( "main: locker1 signaled" );
        }


        try {
            t1.join();
            t2.join();


        } catch ( java.lang.InterruptedException e ) {
            System.out.println( "e: " + e );
        }
    }
}




The above code contains the race conditions between three threads. At some unlucky time the One of the threads wait indefinitely when nobody is there to notify. 


To avoid java.lang.IllegalMonitorStateException, first acquire lock on the object using synchronized keyword


Here are points that Brian emphasized:
  • If you read or write a field that is read/written by another thread, you must synchronize. This must be done by both the reading and writing threads, and on the same lock.
  • Don't try to reason about ordering in undersynchronized programs. 
  • Avoiding synchronization can cause subtle bugs that only blow up in production. Do it right first, then make it fast.

Friday, January 17, 2014

What is a ClassLoader?


Importing the compiled class into the JVM to execute
Among commercially popular programming languages, the Java language distinguishes itself
by running on a Java virtual machine (JVM). This means that compiled programs are
expressed in a special, platform-independent format, rather than in the format of the
machine they are running on. This format differs from traditional executable program formats
in a number of important ways.
In particular, a Java program, unlike one written in C or C++, isn't a single executable file, but
instead is composed of many individual class files, each of which corresponds to a single
Java class.
Additionally, these class files are not loaded into memory all at once, but rather are loaded
on demand, as needed by the program. The ClassLoader is the part of the JVM that loads
classes into memory.
The Java ClassLoader, furthermore, is written in the Java language itself. This means that it's
easy to create your own ClassLoader without having to understand the finer details of the
JVM.



Below is the example for custom class loading



package com.javasoul.classloader;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
 *
 * Simple custom class loader implementation
 *
 */
public class CustomClassLoader extends ClassLoader {

    /**
     * The HashMap where the classes will be cached
     */
    private Map<String, Class<?>> classes = new HashMap<String, Class<?>>();

    @Override
    public String toString() {
        return CustomClassLoader.class.getName();
    }

    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        /**Searches through cache of Class Instances If it founds retruns the Class Instance
         *
         */
        if (classes.containsKey(name)) {
            return classes.get(name);
        }

        byte[] classData;

        try {
            classData = loadClassData(name);
        } catch (IOException e) {
            throw new ClassNotFoundException("Class [" + name
                    + "] could not be found", e);
        }
        /**
         * byte [] of the physical class file is passed to the defineClass method
         */
        Class<?> c = defineClass(name, classData, 0, classData.length);
        resolveClass(c);
        /**
         * Putting inside the cache for reuse
         */
        classes.put(name, c);

        return c;
    }

    /**
     * Load the class file into byte array
     *
     * @param name
     *            The name of the class e.g. com.codeslices.test.TestClass}
     * @return The class file as byte array
     * @throws IOException
     */
    private byte[] loadClassData(String name) throws IOException {
        BufferedInputStream in = new BufferedInputStream(ClassLoader.getSystemResourceAsStream(name.replace(".", "/")
                        + ".class"));
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int i;

        while ((i = in.read()) != -1) {
            out.write(i);
        }

        in.close();
        byte[] classData = out.toByteArray();
        out.close();

        return classData;
    }

    /**
     * Simple usage of the CustomClassLoader implementation
     *
     * @param args
     * @throws ClassNotFoundException
     * @throws IllegalAccessException
     * @throws InstantiationException
     * @throws SecurityException
     * @throws NoSuchMethodException
     * @throws InvocationTargetException
     * @throws IllegalArgumentException
     */
    public static void main(String[] args) throws ClassNotFoundException,
    InstantiationException, IllegalAccessException,
    NoSuchMethodException, SecurityException, IllegalArgumentException,
    InvocationTargetException
    {
        CustomClassLoader loader = new CustomClassLoader();
        // This class should be in your application class path
        Class<?> c = loader.findClass("com.javasoul.Blog");
        /**
         * Invoking the constructor with arg-types and instantiating the object with arg-list
         */
        Constructor constr =  c.getConstructor(Long.TYPE,String.class,String.class,Long.TYPE);
        Object o = constr.newInstance(1,"Java Souls","rafi",System.currentTimeMillis());
        Method m = c.getMethod("toString");
        System.out.println(m.invoke(o));
    }

}




Blog.java




package com.javasoul;

public class Blog {
    private long bloggerId;
    private String bloggerName;
    private String author;
    private long creationtime;

    public Blog(long bloggerId, String bloggerName, String author, long creationtime){
        this.bloggerId = bloggerId;
        this.bloggerName = bloggerName;
        this.author = author;
        this.creationtime = creationtime;
    }
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("Blog Id : "+bloggerId);
        sb.append("\tBlogger Name : "+bloggerName);
        sb.append("\tAuthor of Blog  : "+author);
        sb.append("\tcreation time  : "+creationtime);
        return sb.toString();
    }
}