Monday, October 15, 2012

Run JavaScript from Java

Scripts can be executed from within java in the JVM. Let us take javascript language for this example. There are couple of important classes in this package and they are,
ScriptEngineManager and ScriptEngine.

ScriptEngineManager: It has 2 roles
1) Discovery of Script Engine.
2) Storing data in context. (This is shared across programs)

ScriptEngine:
This is an interface available in javax.script. Here we have to specify the scripting language.

Below is the example.



You can access source code from below link.
https://bitbucket.org/nkancharla/javaexamples/src/9582af48772c496f004485762c45dbea690cf551/InvokeJavaScript/src/InvokeJavaScript.java?at=master



Sunday, June 24, 2012

Java Shutdown Hooks


What is Shutdown Hook
We know that in some situations we will have to do some clean-up operations  when the user shuts down our application. Sometimes  the user does not always follow the recommended procedure to exit the application. Java provides an API for programmers to execute code in the middle of the shutdown process,this in turn make sure that our clean-up code is always executed.
This article shows how to use a shutdown hook to guarantee that clean-up code is always run, regardless of how the user terminates the application.
Shutdown Hook is a simple thread which is registered in JVM.
It can be registered by using addShutdownHook (Thread hook). It is a method of java.lang.Runtime class
Some Important points to be remembered:
1) When JVM starts shut down process,  it starts execution of its all registered shutdown Hook  concurrently.
2) You can use Shutdown hook if you want to display messages or execute some code before JVM shut down.
3) We cannot register Shutdown Hook during shut down process. It will through IllegalStateException.
4) We cannot guaranteed that during JVM shutdown process all the registered Shutdown hook complete their execution.
5) If the VM crashes due to an error in native code then no guarantee can be made about whether or not the hooks will be run.
Now lets see one complete example which will demonstrate the use of shutdown hook.
Example
The below example code provides two classes
1)  ShutdownHookDemo
and
2) A subclass of Thread named ShutdownHook.
After instantiation of the public class ShutdownHookDemo , its begin method is called. The begin method creates a shutdown hook and registers it with the current runtime.
ShutdownHook shutdownHook = new ShutdownHook();
Runtime.getRuntime().addShutdownHook(shutdownHook);
When the user press any key, the program exits. But still the the virtual machine will run the shutdown hook and print the message “Im Shutting down” 

lets a create class which actually does the job to be done while VM is shutting down
Output
Im inside start
Im Shutting down
When finalizers will run, before, during, or after shutdown hooks?
Finalization-on-exit processing is done after all shutdown hooks have finished. Otherwise a hook may fail if some live objects are finalized prematurely.

For more information please go through this link



Monday, May 28, 2012

Resource Injection Using Spring

Many times we would come across reading a file into application. File can be located anywhere in the system or network.
To handle such file accessing tasks, Spring provides an interface called as “Resource” contained in the package org.springframework.core.io. To stream in the file, this interface has a method called as getInputStream(). we can get input stream from FileSystemResource, URLResource and ClassPathResource.


Spring’s resource loader provides a very generic getResource() method to get the resources like (text file, media file, image file…) from file system , classpath or URL. You can get the getResource() method from the application context.

Without this getResource() method, you will need to deal with different resources with different solution, like File object for file system resource, URL object for URL resource. Spring really did a good job with this super generic getResource() method, it really save our time to deal with resources.

Here’s an example to show how to use getResource() to load a text file from


1) The following code will read a file named sample.txt located in the src folder in the current working directory using class FileSystemResource.

2) For the files which you usually access using the url protocol like http://, ftp://, file:// etc, we have UrlResource. The following code will read a file named sample.txt present in C drive and that can be accessed from your browser using file:// protocol.


3) For the resources that are present on your classpath, you can use ClassPathResource. The following code will read in a file named sample.txt present in the classpath.


Injecting Resources
  Resource Injection(Static resources): Here we inject resources like the usual Spring Injection. This way is used for loading static resources i.e. when we know the resource which is required beforehand.

 Resource Loader(Dynamic Resources): Here we use Resource Loader interface to help us a resource we require. This way is used for loadind dynamic resources i.e which will be loaded based on some business logic .


Resource Injection: for static resources


In the above class, we have created a property of type Resource. And in the below context xml file we have injected this property with the path of the file we want spring to provide us with.

resourceContext.xml

SpringResourceTest.java


In the above test class, we get this bean in the usual way and when you get the textFile property from this bean, you can successfully read the information from this resource object. Now let us see the second way i.e how to access dynamic resources.


resourceContext.xml resource path has no prefix, so because the application context itself is going to be used as the ResourceLoader, the resource itself will be loaded via a ClassPathResource, FileSystemResource, or ServletContextResource (as appropriate) depending on the exact type of the context.
If there is a need to force a specific Resource type to be used, then a prefix may be used. The following two examples show how to force a ClassPathResource and a UrlResource (the latter being used to access a filesystem file).

<property name="template" value="classpath:some/resource/path/myTemplate.txt">

<property name="template" value="file:/some/resource/path/myTemplate.txt"/>


Resource Loader Injection: for dynamic resources



The above class has a property of type ResourceLoader. This ResourceLoader will be used to dynamically load a resource.To tell the spring about injecting value into this, we have used the @Autowired annotation. With annotations, we need not create setter methods for our properties. Only thing we have to do is to tell Spring framework that we are using the annotation, so in addition to the injecting values based on the property tags from the xml, it has to read class level annotations also. We do this by adding in the content xml file as seen below.

resourceContext.xml


SpringResourceTest.java
In our test class, we get this bean in the usual way and call its loadDynamicResource. This method internally uses the ResourceLoader to return a Resource dynamically.


Thursday, April 26, 2012

ThreadLocal in Java



Thread local class is to share information across multiple threads where each thread will have independent copy of the variable. We can use syncronization for the same but it is expensive. If there are frequent read operations , less number of modify operations and no interdependence among state variables across different threads,we can use thread local variables.



Thread local variables can be used when each thread wants to get default initialized copy of the variable and modify it as per their algorithm and use it across.It does not depend on the state variable in different threads.
Example:Lets take one use case in which we span multiple threads and create a thread local variable for the simple String as myFavPlace.Here depending upon the thread name we set myFavPlace in thread local variable which is then used by another class to print the current myFavPlace value.
Attached is the code snippet for reference



package threadLocal;
public class ThreadLocalExample{
 
  public static void main(String[] args) {
   Runnable runnable=new RunnableImpl();
   Thread thread1=new Thread(runnable,"USA");
   Thread thread2=new Thread(runnable,"UK");  
   Thread thread3= new Thread(runnable);
   Thread thread4= new Thread(runnable, "Europe");
  
   thread1.start();
   thread2.start();
   thread3.start();
   thread4.start();
  }
}


public class RunnableImpl implements Runnable {
  /**
   * Overridden run method implementation for Thread
   * Here depending upon the thread name we put String myFavPlace in
   * thread local variable which is then used  to print the
   * current place
   */
  @Override
  public void run() {
   String name = Thread.currentThread().getName();
  
   if(name !=null){
    if(name.equals("USA")){
       ThreadLocalDataHolder.setMyFavPlace(" Denver " );
    }else if(name.equals("UK")){
     ThreadLocalDataHolder.setMyFavPlace(" Gibraltor " );
    }else if(name.equals("Europe")) {
     ThreadLocalDataHolder.setMyFavPlace(" Belgium ");
    }
   }
  
   System.out.println("Thread Name -"+ Thread.currentThread() + " Current state is -"+ ThreadLocalDataHolder.getMyFavPlace());   
  
  }
 }


public class ThreadLocalDataHolder {

 private static ThreadLocal<String> myFavPlace=new ThreadLocal<String>(){
    public String initialValue() {
       System.out.println(" magic magic ");
           return new String();
       }  
   };
  
   public static void setMyFavPlace(String value){ 
    myFavPlace.set(value);
   }
  
   public static String getMyFavPlace(){
    return myFavPlace.get();
   }
}

output 
Thread Name -Thread[Thread-0,5,main] Current state is -
Thread Name -Thread[UK,5,main] Current state is - Gibraltor
Thread Name -Thread[Europe,5,main] Current state is - Belgium
Thread Name -Thread[USA,5,main] Current state is - Denver


you can also test with out locale in ThreadLocalDataHolder.java and see the output (without locale)

 public class ThreadLocalDataHolder { 

 private static String myFavPlace = " empty ";

 public static void setMyFavPlace(String value)
 {
  myFavPlace = value;
 }
 
 public static String getMyFavPlace()
 {
  return myFavPlace;
 }
}
output without Locale
Thread Name -Thread[UK,5,main] Current state is - Gibraltor
Thread Name -Thread[Europe,5,main] Current state is - Gibraltor
Thread Name -Thread[USA,5,main] Current state is - Gibraltor
Thread Name -Thread[Thread-0,5,main] Current state is - Gibraltor



 Where all thread locals are used?Its widely used in lots of frameworks like Spring ,Hibernate and others for passing particular thread specific information like transaction attributes,connection details,authorization information and others.

Is Thread Local safe to use or does it have some issues?
If thread local variables are not handled properly,it may lead to Class loader memory leak issue.Normally we get errors like this OutOfMemory: PermGen error...............................
Reason being if we don't clear the thread local variables after use and if thread local variables references some object.It will still be there and won't be garbage collected even though thread has finished the execution.Gradually with multiple installations/un-installations or multiple threads being spawned this memory issue will cause application to crash .So we should take proper care of removing the referencing to objects in thread local variables after use.

Wednesday, September 7, 2011

Java Concurrency - Barrier

In this series we will discuss different concurrent structures provided in the new Java 5 Concurrent package. We will start with a simple parallel processing concept called "barrier" that we have all studied and forgotten. By definition if there are set of independent tasks (T1..Tn) that need to fully completed to initiate another task (Tx) which is dependent on all these tasks (T1...Tn) we can synchronize them using a barrier.


why is the barrier not more commonly used?
The functionality is simple enough that it can be accomplished with the low-level tools provided by Java. We can solve the coordination problem in two ways, without using a barrier.

First, we can simply have the threads wait on a condition variable. The last thread releases the barrier by notifying all of the other threads.

A second option is to simply await termination of the threads by using the join() method. Once all threads have been joined, we can start new threads for the next phase of the program

 However, in some cases it is preferable to use barriers. When using the join() method, threads are exiting and we're starting new ones. Therefore, the threads lose any state that they have stored in their previous thread object; they need to store that state prior to terminating. Furthermore, if we must always create new threads, logical operations cannot be placed together; since new threads have to be created for each subtask, the code for each subtask must be placed in separate run() methods. It may be easier to code all of the logic as one method, particularly if the subtasks are very small.

CyclicBarrier – a pair of threads computes the sum of all numbers in a
matrix by iterating over neighbour rows. Imagine you have a matrix (with an
even number of columns). You want to sum all its elements using 2 threads. The
simple way is to run 2 threads from inside main () to process rows 0 and 1, wait
(using busy-wait) until computation is complete; sum the resulting values; then
run 2 threads on rows 2 and 3, wait, sum and so on. This is demonstrated in
cyclsimple example


Below is the example:

package Barrier;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

public class CyclicBarrierExample
{
    private static int matrix[][] =
    {
        { 1 },
        { 2, 2 },
        { 3, 3, 3 },
        { 4, 4, 4, 4 },
        { 5, 5, 5, 5, 5 } };

    private static int results[];

    private static class Summer extends Thread
    {
        int row;

        CyclicBarrier barrier;

        Summer(CyclicBarrier barrier, int row)
        {
            this.barrier = barrier;
            this.row = row;
        }

        public void run()
        {
            int columns = matrix[row].length;
            int sum = 0;
            for (int i = 0; i < columns; i++)
            {
                sum += matrix[row][i];
            }
            results[row] = sum;
            System.out.println("Results for row " + row + " are : " + sum);
            // wait for others
            try
            {
                barrier.await();
            } catch (InterruptedException ex)
            {
                ex.printStackTrace();
            } catch (BrokenBarrierException ex)
            {
                ex.printStackTrace();
            }
           
           
        }
    }

    public static void main(String args[])
    {
        final int rows = matrix.length;
        results = new int[rows];
        Runnable merger = new Runnable()
        {
            public void run()
            {
                int sum = 0;
                for (int i = 0; i < rows; i++)
                {
                    sum += results[i];
                }
                System.out.println("Results are: " + sum);
            }
        };
        /*
         * public CyclicBarrier(int parties,Runnable barrierAction)
         * Creates a new CyclicBarrier that will trip when the given number
         * of parties (threads) are waiting upon it, and which will execute
         * the merger task when the barrier is tripped, performed
         * by the last thread entering the barrier.
         */
        CyclicBarrier barrier = new CyclicBarrier(rows, merger);
        for (int i = 0; i < rows; i++)
        {
            new Summer(barrier, i).start();
        }
        System.out.println("Waiting...");
    }
}


output :

Results for row 0 are : 1
Waiting...
Results for row 2 are : 9
Results for row 4 are : 25
Results for row 3 are : 16
Results for row 1 are : 4
Results are: 55

To access the source code:
https://bitbucket.org/nkancharla/javaexamples/src/bf0dcc13573e0782807788b99e934b64f592dd41/Barrier?at=master

Tuesday, September 6, 2011

Creating java objects without calling constructors

If the object is serializable, then it is created magically without having the constructor called. This means if a class implements Serializable interface then that class constructor wont be called while Deserialization process.

See below example for more details.


public class parent {
  public parent() {
    System.out.println("parent constructor called");

  }
}



import java.io.Serializable;

public class child extends parent implements Serializable {
   public child() {
      System.out.println("child constructor called");
   }
}



import java.io.*;
public class DeserializeTest {
  public static void main(String[] args) throws IOException, ClassNotFoundException {
    child ms = new child();

    // writing object to byte[]
    System.out.println("writing ms");
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ObjectOutputStream oos = new ObjectOutputStream(baos);
    oos.writeObject(ms);
    oos.close();
    byte[] objectInBinaryForm = baos.toByteArray();


    // reading object from byte[]
    System.out.println("....Deserialization flow");
    System.out.println("reading ms2");
    ObjectInputStream ois = new ObjectInputStream( new ByteArrayInputStream(objectInBinaryForm) );
    child ms2 = (child) ois.readObject();
    System.out.println("ms == ms2 = " + (ms == ms2));
    System.out.println("ms = " + ms);
    System.out.println("ms2 = " + ms2);
  }
}


The output is the following, note the number of times that each constructor is called:


parent constructor called
child constructor called
writing ms
....Deserialization flow
reading ms2
parent constructor called
ms == ms2 = false
ms = mySerialization.child@1a626f
ms2 = mySerialization.child@95fd19

While deserialization child constructor is not called. but still we got object after deserialzation.

Can you guess how it is done?

Below code will explain you in detail.

For example, to simulate what happens in the DeserializeTest, we could call it with
      SilentObjectCreator.create(child.class, parent.class)
    
Here is my SilentObjectCreator, used to instantiate objects without invoking any constructors:


import sun.reflect.ReflectionFactory;
import java.lang.reflect.Constructor;

public class SilentObjectCreator {

  public static <T> T create(Class<T> clazz) {
    return create(clazz, Object.class);
  }


  public static <T> T create(Class<T> clazz,
                             Class<? super T> parent) {
    try {
      ReflectionFactory rf =  ReflectionFactory.getReflectionFactory();
      Constructor objDef = parent.getDeclaredConstructor();
      Constructor intConstr = rf.newConstructorForSerialization( clazz, objDef );
      return clazz.cast(intConstr.newInstance());
    } catch (RuntimeException e) {
      throw e;
    } catch (Exception e) {
      throw new IllegalStateException("Cannot create object", e);
    }
  }
}



Lets test with our test class below


public class Creatiopublic class CreationTest {
   public static void main(String[] args) {
     // Creating child by calling parent no-args constructor, but not the child constructor.
    System.out.println("Creating child by calling parent no-args constructor, but not the child constructor");
    child ms = SilentObjectCreator.create( child.class, parent.class);
     System.out.println("ms = " + ms);

     // Creating child by not calling any constructors.
     System.out.println("Creating child by not calling any constructors");
     child ms2 = SilentObjectCreator.create( child.class );
     System.out.println("ms2 = " + ms2);
   }
}


In the output we see that in the first case, the NotSerializable constructor is called, but not in the second:

Creating child by calling parent no-args constructor, but not the child constructor
parent constructor called
ms = mySerialization.child@f9f9d8
Creating child by not calling any constructors
ms2 = mySerialization.child@112f614

We can use this mechanism to create just about any class, except abstract classes.