Thursday 30 December 2010

Java conccurency -a brief overview

Java is typically compiled to bytecode language that it's later interpreted by the JVM(Java Virtual Machine). This approach has advantages and disadvantages. On one hand, application developers can "write once, run anywhere" as one of the most remarkable benefits, but on the other hand this approach also make Java a low performance programming language.

Java has been criticised for its performance compared to other languages and as a result an entire set of performance practices has been utilised.

Java bytecode can either be interpreted at run time by a virtual machine, or it can be compiled at load time or runtime into machine code which runs directly on the computer's hardware. Interpretation is slower than native execution, and compilation at load time or runtime has an initial performance penalty for the compilation. Although this concepts can explain much of the performance issues, there is something we can do to improve our programs performance.

Concurrent programming has always been difficult, and this is one of the most important deficiencies in the programmers knowledge since ever. However, the Java Team have been building packages to manage this in the painless manner. Nevertheless, it is necessary to know the basics to use this in an application and get the wanted results.

A computer system normally has many active processes and threads. This is true even in systems that only have a single execution core, and thus only have one thread actually executing at any given moment. Processing time for a single core is shared among processes and threads through an OS feature called time slicing.

A process has a self-contained execution environment. A process generally has a complete, private set of basic run-time resources; in particular, each process has its own memory space. Threads are sometimes called lightweight processes. Both processes and threads provide an execution environment, but creating a new thread requires fewer resources than creating a new process. Threads lives within a process and a process has at least one thread.

A computer system normally has many active processes and threads. This is true even in systems that only have a single execution core, and thus only have one thread actually executing at any given moment. Processing time for a single core is shared among processes and threads through an OS feature called time slicing.

A process has a self-contained execution environment. A process generally has a complete, private set of basic run-time resources; in particular, each process has its own memory space. Threads are sometimes called lightweight processes. Both processes and threads provide an execution environment, but creating a new thread requires fewer resources than creating a new process. Threads lives within a process and a process has at least one thread.

In order to answer some questions I will give my best(:)) and I will present a scenario to give some sense to all of these. Suppose you want to simulate a situation in which you have multiple threads asking for process some information and you want to maximise your resources by having multiple threads processing those request. The first that come to my mind is a producer-consumer scenario.

The next big question for me was which one would be the topic of this short application that allows me to make my point. And I thought in the most common situation. Threads trying to make a deposit or withdraw from one only account. That way you have multi-threading, control over the amount of threads that are consuming resources and data sharing where you can have data corruption.

Let's see some code:

First of all I will implement the Accout class:

public class Account {
    private static ReentrantLock lock = new ReentrantLock(true);
    
    private long balance = 200;
    
    public Account() {
    }
    
    public long transfer(long amount) throws CorruptedAccountException {
//        lock.lock();
//        try {
            if (balance < 0)
                throw new CorruptedAccountException();
        
            if ((balance + amount) < 0)
                return balance;
            
            // This emulate a complex task after the control and before the
            // operation that affect the shared variable.
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            
            balance += amount;
            
            return balance;
        
//        } finally {
//            lock.unlock();
//        }
    }
}
The Account class is created once only and then passed by value to all other classes as you will see further. This will gives us the perfect scenario to the data sharing and is the critical piece of code also. Pay attention to the method transfer that is where all happens. There is a control there that throws an exception if the balance is 0 or less. That way we will know if two threads access the same variable and leave inconsistent data there. Now we have the producer, which in this case is divided in two classes. DepositRequestsProducer that is responsible of add money to the account and WithdrawRequestsProducer which is responsible of withdraw from the account. Both are almost identical except for the sign of the amount(that was done like this to clarify the idea). Furthermore, it is important to note that both producers add transactions to a queue. This is not a minor detail, indeed this queue is the clue to prevent that the amount of transactions growth infinitely demanding more and more resources until an "out of memory" stop the program. That would the case if the producers add transactions more quickly that the consumer can process.
public class DepositRequestsProducer implements Runnable {
    
    private Thread tread;
    private BlockingQueue queue;

    public DepositRequestsProducer(BlockingQueue q) {
        queue = q;
        tread = new Thread(this);
        tread.start();
    }

    public void run() {
        try {
            Random randomGenerator = new Random();
            while (true) {
                int amount = randomGenerator.nextInt(100);            
                queue.put(new Long(amount));
                Thread.yield();
            }
            
        } catch (InterruptedException ex) {
            ex.printStackTrace();
        }
    }
}
public class WithdrawRequestsProducer implements Runnable {

    private Thread thread;
    private BlockingQueue queue;

    public WithdrawRequestsProducer(BlockingQueue q) {
        queue = q;
        thread = new Thread(this);
        thread.start();
    }

    public void run() {
        try {
            Random randomGenerator = new Random();
            while (true) {
                int amount = randomGenerator.nextInt(300);
                queue.put(new Long(amount*-1));
                Thread.yield();
            }
            
        } catch (InterruptedException ex) {
            ex.printStackTrace();
        }
    }
}
Note that both classes receives a queue. This queue is where the transactions produced by them are going to be put. Lately, the consumer will get the transactions from there to process them. On the other side of the desk we need the Consumer, which is responsible of process the transactions:
public class TransactionConsumer implements Runnable {
    
    private Thread tread;
    private BlockingQueue queue;
    private Account account;

    public TransactionConsumer(BlockingQueue q, Account account, int thread) {
        queue = q;
        this.account = account;
        tread = new Thread(this, "Consumer_" + thread);
        tread.start();
    }

    public void run() {
        long request, result = 0;
        Runtime s_runtime = Runtime.getRuntime();
        
        NumberFormat numberFormat = NumberFormat.getNumberInstance();
        numberFormat.setRoundingMode(RoundingMode.DOWN);

        try {
            while (true) {
                request = queue.take().longValue();
                result = account.transfer(request);
                
                double freeMemory = (s_runtime.freeMemory() / 1048576);
                
                System.out.println("Calculated result after add " + request + " is " + result + " -- Free Memory: " +  numberFormat.format(freeMemory) + " / " + numberFormat.format(s_runtime.totalMemory() / 1048576));
            }
            
        } catch (InterruptedException ex) {
            ex.printStackTrace();
        }
        
        System.exit(0);
    }
}
This class also receives the queue in the constructor and open a thread to run as soon as a transaction were found in the queue. Lastly we have the class that makes it work:
import java.util.concurrent.ArrayBlockingQueue;

public class TestConcurrency {

    public static void main(String[] args) {
        Account account = new Account();
        final ArrayBlockingQueue queue = new ArrayBlockingQueue(40);
        
        for (int i = 0; i < 15; i++)
            new TransactionConsumer(queue, account, i);

     for (int i = 0; i < 30; i++) {
         new Thread(new DepositRequestsProducer(queue)).start();
         new Thread(new WithdrawRequestsProducer(queue)).start();
     }
    }
}

As you can see, when you run the program, the first thread executes the main method. Here an ArrayBlockingQueue is created as final and this is the first clue to analyse. This queue, as we mentioned above, protects the program of an infinite increase on the resource demand. Once the queue reaches the highest of it's capacity, all the threads that intend to put transactions in, will be put to sleep until a consumer takes a transaction out. At this moment all the threads that were sleeping waiting for a place in the queue, are wake up to compete for the queue. The implementation of this ArrayBlockingQueue is very useful because it avoids us a lot of work regarding monitoring threads.

Then we can see that a specified number of threads are created to run producers and consumers, and we are going to have at least 75 threads running as sub-processes of the main one.

Back in the Account class, all the threads will access transfer method code without any synchronisation. This will produce shared data corruption when two threads access to critical sections of code. Lets present a simple example:

Suppose that two threads(which we'll call A and B) access transfer method. Let say that balance variable is 125 and and the thread A is invoked with -100 and the thread B with -50. The thread A passes through the "if" that prevent negative balance and reaches the sleep command. Meanwhile, thread B passes through the balance check before the thread A updates the balance amount. Consequently, the balance will be updated by thread A leaving the balance in 25. When thread B reaches the balance update operation, the shared data gets corrupted.

This is the moment in which we realise that this is "a critical code". Here is when we have to add some protection to transfer method. In Account class you will see some commented lines of code which you should un-comment in order to see the difference.

I have added some extra lines in order to add some information related to memory use. Try to run the program with and without comments to see the difference.

Have luck!!!

Tuesday 13 July 2010

A simple example of Java Reflection API

Java reflection API allows us to inspect classes on runtime. This is a very powerful tool but it's also very bad on performance. I use that technique on class converting. Suppose you have an entity you named User, and you don't want to serialize it to the client layer. You have to create a serializable class that has all the attributes you want to send back to the client and fill it with the entity content. This is a very good work for reflection.

I faced this problem on a project and I made a utility class to help resolve that. This is a very basic approach to a real solution but it works for me.

Let's see some code:

import java.lang.reflect.*;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;

import com.jflow.entities.GenericEntity;
import com.jflow.exceptions.EWConversionException;

public class ReflectionUtil {

    private static String capitalize(String s) {
        if (s.length() == 0) return s;
        return s.substring(0, 1).toUpperCase() + s.substring(1).toLowerCase();
    }
    
 public static <T> T convertClass(GenericEntity source, Class<T> destinationClass) throws EWConversionException {
  T desteny = null;
  try {
   if (source == null) {
    return desteny;
   }
   
   desteny = destinationClass.newInstance();
   Class<?> sourceClass = source.getClass();
         
         Field destFieldList[] = destinationClass.getDeclaredFields();
   for (Field field : destFieldList) {
    String name = field.getName();
    Field sourceField = null;
    
    try {
     sourceField = getField(sourceClass, name);
     
     field.setAccessible(true);
     sourceField.setAccessible(true);
     field.set(desteny, sourceField.get(source));
     
    } catch(IllegalAccessException e) {
     try {
      String methodName = capitalize(sourceField.getName());
      Method method;
      method = getMethod(sourceClass, "get" + methodName);
      method.setAccessible(true);
      field.set(desteny, method.invoke(source));
      
     } catch (IllegalArgumentException e1) {
      e1.printStackTrace();
     } catch (InvocationTargetException e1) {
      e1.printStackTrace();
     } catch (IllegalAccessException e1) {
      e1.printStackTrace();
     } catch (NoSuchMethodException e1) {
      e.printStackTrace();
     }
    } catch (NoSuchFieldException e) {
     e.printStackTrace();
    }
   }
  
  } catch (SecurityException e1) {
   throw new EWConversionException(e1.getMessage());
  } catch (InstantiationException e1) {
   throw new EWConversionException(e1.getMessage());
  } catch (IllegalAccessException e1) {
   throw new EWConversionException(e1.getMessage());
  }
  
  return desteny;
 }
 
 private static Field getField(Class<?> clazz, String fieldName) throws NoSuchFieldException {
  Field field = null;
  while (clazz != Object.class) {
       try {
        field = clazz.getDeclaredField(fieldName);
        field.setAccessible(true);
        break;
       } catch (NoSuchFieldException ex) {
        clazz = clazz.getSuperclass();
       }
  }
  
  if (field == null)
   throw new NoSuchFieldException(field + " no such a field.");
  
  // only needed if the two classes are in different packages
  return field;
 }
 
 private static Method getMethod(Class<?> clazz, String methodName) throws NoSuchMethodException {
  Method method = null;
  while (clazz != Object.class) {
       try {
        method = clazz.getDeclaredMethod(methodName);
        method.setAccessible(true); 
        break;
       } catch (NoSuchMethodException ex) {
        clazz = clazz.getSuperclass();
       }
  }
  
  if (method == null)
   throw new NoSuchMethodException(methodName + " no such a method.");
  
  // only needed if the two classes are in different packages
  return method;
 }
 
 @SuppressWarnings("unchecked")
 public static <T> HashSet<T> convertToHashSet(Collection<? extends GenericEntity> source, Class<T> destinationClass) throws EWConversionException {
  HashSet<T> returnCollection = new HashSet<T>();
  
  for (GenericEntity s : source) {
   T element = (T) ReflectionUtil.convertClass(s, destinationClass.getClass());
   returnCollection.add(element);
  }
  
  return returnCollection;
 }

 
 @SuppressWarnings("unchecked")
 public static <T> Map<Long, T> convertToMap(Collection<? extends GenericEntity> source, Class<T> destinationClass) throws EWConversionException {
  Map<Long, T> returnCollection = new HashMap<Long, T>();
  
  for (GenericEntity s : source) {
   T element = (T) ReflectionUtil.convertClass(s, destinationClass.getClass());
   returnCollection.put(s.getId(), element);
  }
  
  return returnCollection;
 }
 
 public static <T> List<T> convertToArrayList(Collection<? extends GenericEntity> source, Class<T> destinationClass) throws EWConversionException {
  List<T> returnCollection = new ArrayList<T>();
  
  for (GenericEntity s : source) {
   T element = (T) ReflectionUtil.convertClass(s, destinationClass);
   returnCollection.add(element);
  }
  
  return returnCollection;
 }
 
}

I also provide a couple of methods to help on more complex conversions, such as Map, List and Sets. GenericEntity is an abstract class from where all entities inherit.

I made some performance test with a class that has 5 attributes, based on the supposed that both has the same attributes. As a mean I get 2 milliseconds for the traditional way of fill one class with the content of the other one, and on the other hand an 8 milliseconds mean using the utility class.

I think that this is very useful for non real time applications and avoid you from being specific converting code for each class you need to send back to the client layer.

This is a wide open discussion field and most of you should have different opinions. The aim is to present one way of doing this. If you have buts or other ways to do this please don't hesitate to post a comment.

If you want to get more in deep details on "Java Reflection API" you can read this tutorial. He gave very good explanations on this concern.

See you!!

Tuesday 6 July 2010

An overview of the defalut GWT application.

GWT is basically a translator(very big and complex one) that mainly translates the Java programming language to the JavaScript programming language. It sounds easy but it's not. This is a very innovative idea that allows us to work on web applications like in Swing. For those who have some experience in Swing programming so GWT looks like very familiar.

GWT not only translate from one language to another, also offers a lot of libraries to get easy the most common things on the web development.
Those are some of the features that GWT offers:
  • Dynamic and reusable UI components: programmers can use pre-designed classes to implement otherwise time-consuming dynamic behaviors, such as drag-and-drop or sophisticated visual tree structures.
  • Simple RPC mechanism
  • Browser history management
  • Support for full-featured Java debugging
  • GWT handles all cross-browser issues for the developer.
  • JUnit integration
  • Easy internationalization
those are some of the most remarkable features.

This intend to be an overview of a very basic GWT application. My intention is to explain briefly and with my very basic knowledge how does it works.

Here we're going to explain the process to get a running environment on Eclipse for linux. In order to do that, you can follow this recipe. Take into account that the last version of Eclipse is 3.6 Helios, so you can use the appropriate plug-in version.

As it says the recipe, to create a Web Application, select File > New > Web Application Project from the Eclipse menu.

In the New Web Application Project wizard, enter a name for your project and a java package name, on our example com.example.firstproject. If you installed the Google App Engine SDK, the wizard gives you the option to use App Engine as well. For now, uncheck this option and click Finish.

Now we have our first GWT project. The wizard generates all necessary to get us a running project. This is a great aid, and allows us to be on the road very fast.

That's how "project view" should looks like:


As we can see, there are four packages that were created following the pattern we gave to the wizard.

The first thing we going to look at, is the FirstProject.gwt.xml file. This file is to configure the GWT application module. In this file we will set the EntryPoint, which is the class that will be responsible of start the application. The method that will be called is onModuleLoad() and here you have to write your code.

As you can see in FirstProject.gwt.xml file, the default EntryPoint class was set:



That way, GWT knows from where to start when a client invocation arrives.

Now we going to pay attention to onModuleLoad() method. The significant thing to notice here is the connection between this and the main page. The "main page" is how I called to the basic html page where you set the layout. In this case this page is /war/FirstProject.html. The body of this page will be represented by the RootPanel class. That class allows you to get any object by his name. So the the trick here is to place some named properly(nameFieldContainer for example) and then get it using RootPanel.get("nameFieldContainer") to add widgets to it. As can be seen in the example, a TextBox is created and labeled "GWT User" for lastly being added to nameFieldContainer.

final Button sendButton = new Button("Send");
final TextBox nameField = new TextBox();
nameField.setText("GWT User");
final Label errorLabel = new Label();

// We can add style names to widgets
sendButton.addStyleName("sendButton");

// Add the nameField and sendButton to the RootPanel
// Use RootPanel.get() to get the entire body element
RootPanel.get("nameFieldContainer").add(nameField);
RootPanel.get("sendButtonContainer").add(sendButton);
RootPanel.get("errorLabelContainer").add(errorLabel);


Similarly, sendButton and errorLabel, are added to their respective root panels.




Furthermore, we can observe the creation of an event handler class. This class will manage the events that it implements. In this case we are talking about ClickHandler and KeyUpHandler. As you can see, this class overrides two methods, onClick and onKeyUp. Then this handler is set to the button and to the TextBox.

We have also the implementation of communication between the client and the server. This is achieved using RPC(remote procedure calls), GWT has he's own implementation of that design pattern. The good news is that is very simple to use.

There are a couple of things to do here. First we have to add the servlet to web.xml. This file is located as usual, in /war/WEB-INF, and you will see that piece of code that means that:

  
    greetServlet
    com.example.firstproject.server.GreetingServiceImpl
  
  
  
    greetServlet
    /firstproject/greet
  


As we can see in the servlet mapping url, we are pointing the servlet to "/firstproject/greet". The following part of the project name is the relative path and is the one that must be used in the RPC interface. Now, if we take a look at GreetingService interface we will see the reference to "greet".

package com.example.firstproject.client;

import com.google.gwt.user.client.rpc.RemoteService;
import com.google.gwt.user.client.rpc.RemoteServiceRelativePath;

/**
 * The client side stub for the RPC service.
 */
@RemoteServiceRelativePath("greet")
public interface GreetingService extends RemoteService {
    String greetServer(String name) throws IllegalArgumentException;
}


In that interface we will define the methods to be called. In this case we can see greetServer method that is the only one we going to use.

Now we have the implementation of that interface that is the responsible to answer:

package com.example.firstproject.server;

import com.example.firstproject.client.GreetingService;
import com.example.firstproject.shared.FieldVerifier;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;

/**
 * The server side implementation of the RPC service.
 */
@SuppressWarnings("serial")
public class GreetingServiceImpl extends RemoteServiceServlet implements GreetingService {

    public String greetServer(String input) throws IllegalArgumentException {
        // Verify that the input is valid. 
        if (!FieldVerifier.isValidName(input)) {
            // If the input is not valid, throw an IllegalArgumentException back to
            // the client.
            throw new IllegalArgumentException("Name must be at least 4 characters long");
        }

        String serverInfo = getServletContext().getServerInfo();
        String userAgent = getThreadLocalRequest().getHeader("User-Agent");

        // Escape data from the client to avoid cross-site script vulnerabilities.
        input = escapeHtml(input);
        userAgent = escapeHtml(userAgent);

        return "Hello, " + input + "!

I am running " + serverInfo + ".

It looks like you are using:
" + userAgent;
    }

    /**
     * Escape an html string. Escaping data received from the client helps to
     * prevent cross-site script vulnerabilities.
     * 
     * @param html the html string to escape
     * @return the escaped string
     */
    private String escapeHtml(String html) {
        if (html == null) {
            return null;
        }
        return html.replaceAll("&", "&").replaceAll("<", "<").replaceAll(">", ">");
    }
}


Now it's time to play. I did some little things that I will share on later posts.

I hope that will be useful!!

Wednesday 16 June 2010

Singleton EJBs . . . good news

JBoss is releasing the milestone 3 of JBoss 6. One of the good news is that it seems to be possible to annotate an EJB as a singleton. That mean, no more unnecessary queries all over the application or parameters where has non sense. Neither Stateless Session Beans nor Stateful Session Beans meet this need.

Now you only need the @Singleton class annotation to make an EJB singleton.

With this you guarantee that there will be only one instance of that EJB in the entire application. This is very useful to manage application shared data.

But this brings some concurrency problems. Now we need to look after the access of that shared data.

Suppose the following example:


import javax.ejb.Lock;
import javax.ejb.LockType;
import javax.ejb.Remote;
import javax.ejb.Stateful;

@Stateful
@Remote(UsersCounter.class)
public class UsersCounterBean {
 int maximun = 2000;
 int users;

 @Lock(LockType.WRITE)
 public boolean canLogin() {
     if (users < maximun) {
         users++;
         return true;
     }else{
         return false;
     }
 }

 @Lock(LockType.WRITE)
 public void doLogout() {
  users--;
 }

 @Lock(LockType.READ)
 public int getUsersCount() {
  return users;
 }

}


For some weird reason you want to control the maximum number of users, and obviously you decide to use this approach(:D).

How to deal with synchronization?
Supposing that two clients invokes the same method. The container ensure us that there will be only on thread at a time executing each method.

For those who have ever use the synchronization on J2SE, this is exactly like the same as if we marked a method as synchronized.

This is quiet good but it's also a bottleneck but you have a workaround on this.

J2EE allows us to fine tune this by using @Lock annotation. That way we can make some methods to have a read lock allowing multiple threads accessing it but with the consign of not modifying class attributes.

So, we can add @Lock(LockType.WRITE) to those methods that modify the users attribute and @Lock(LockType.READ) to the other.

This will be get much more performance to the use of the users count.

I hope you can use this soon and please correct me if you find mistakes(also English please)

:D

My other big passion!!

Lutherie is my other passion. I started to be interested in lutherie up to 4 years ago. I was learning to play classical guitar
and I start to feel the need of a better guitar. Because I couldn't buy a concert guitar I started to read guitarmaking material. Soon I found myself, building my first ukelele with guitar dreams(jaja just a joke). My second try was a better approach. Nevertheless, I never gave up and I try once again. The third one was the good one. Now I'm playing with this one. The emotion when I listen this this guitar was indescribable. In that moment I knew that this going to be the hobby for the rest of my life.

Ok guys!! Soon I will write more about that. Meanwhile, I will show you a picture of my workshop!!

Kick off!!

First of all, I want to explain the name of the blogg. The first time I comment that I'm planning to move to Australia, one friend told me that he has an Australian friend nicknamed "alfadingo". I made a little research and find out that the Dingo is an Australian traditional wild dog. And I start to call myself javadingo, because Java is almost my way of life. Then I found, over the Internet, this funny abbreviation of overseas that really likes me so I made that weired mix of none senses my blogg name. Yes. I'm a little crazy!!

The reason why I'm writing in English is because I need practice to take the IELTS which it's needed to migrate Australia. This is a good way of mix all my intentions.

See you soon!!