Thursday, December 30, 2010

Java5 CompletionService makes waiting for thread execution results so easy !

I recently had a scenario where I had to put some threads to do some work and wait till they complete. But I did not really want to wait till all of them completed their work, which is sub-optimal utilization of the cycles. I wanted to have some mechanism by which I could get the values as soon as each of my threads are done with the processing. So the scenario is something like this

  1. A main thread needs N tasks to be done 
  2. It spawns M threads from a Pool and works on the N tasks
  3. It waits till atleast one thread completes the task and does something with the result
  4. Continues to process the results till the time all of the N tasks are completed


    While I was breaking my head on this, I learnt about the "CompletionService" in Java5. This does exactly what I want, and I was able to complete the code in a few minutes. Attaching the code sample just in case this is useful to some.

    I defined a Callable which abstracts by business logic. You Can do what you need to do on the thread here

    package com.sreekanth.java5.threads;
    import java.util.concurrent.Callable;
    
    public class TestCallable implements Callable<Long> {
        @Override
        public Long call() throws Exception 
        {
            // do something here - just adding some numbers on the sample 
            
            long sum = 0;
            for (long i = 0; i <= 10; i++) 
            {
                sum += i;
            }
            return sum;
        }
    
    }
    
    

    Now I created the main class which does my processing using the CompletionService. The sample code is attached below

    package com.sreekanth.java5.threads;
    
    import java.util.concurrent.Callable;
    import java.util.concurrent.CompletionService;
    import java.util.concurrent.ExecutionException;
    import java.util.concurrent.ExecutorCompletionService;
    import java.util.concurrent.Executors;
    import java.util.concurrent.Future;
    
    public class CompletionServiceTest 
    {
        /**
         * @param args
         */
        @SuppressWarnings("unchecked")
        
        public static void main(String[] args) 
        {
            CompletionService service = new ExecutorCompletionService(Executors.newFixedThreadPool(5));
            
            int noOfRunningFutures = 0;
            
            for (int i = 0; i < 20; i++) 
            {
                Callable<Long> worker = new TestCallable();
                service.submit(worker);
                
                // add them to the number of futures which I am creating - to keep track of the Queue length
                noOfRunningFutures ++;
            }
            
            while (noOfRunningFutures > 0) 
            {
                try {
                    
                    // this is a blocking call - whenever there is a worker which is already completed
                    // then it is fetched from the Queue                 
                    Future<Long> completed = service.take();
                    noOfRunningFutures --;
                    
                    // get the value from computed from the Future
                    Long i = completed.get();
                    
                    // Do some thing with the value got from the callable - just printing it here.
                    System.out.println("Got from the callable " + i);
                    
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (ExecutionException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    }
    
    

    Really Cool and Simple!

    Thursday, December 23, 2010

    Simple JQuery Plugin to Format Validate a U.S Telephone number

    Recently I needed a simple Validation component which would take care of auto formatting the content entered in a text box to a U.S phone number (NPA)-NXX-XXXX. As I was using JQuery, I thought of writing a simple plug-in to do the same. Sharing the code here, just in case this is useful for someone else

    The plug-in does the following

         1. Formats the number to (NPA)-NXX-XXXX as it is typed
         2. It will not allow you to enter special characters or non-number in the textbox.
         3. It will validate that you can enter only 10 digits
         4. This plug-in as of now does not support chaining as I did not see a need.
      
      

         The code and the HTML Snippet are shown below. Please do add a comment for any bugs.

        Plug-in code : Save this as whatever JS file you need it to be - I have used jquery.usphone.js in the HTML

        (function( $ )
        {
          // This function formats a text field to a US 
          // phone number as the user types the information.
         
          $.fn.usphone = function() 
          {
            this.keyup(function() 
            {
             var curchrindex = this.value.length;
             var curval = $(this).val();
             var strvalidchars = "0123456789()-";
                  
             for (i =0; i < this.value.length; i++)
             {
              var curchar = curval[i];
              if (strvalidchars.indexOf(curchar) == -1) 
              {
               //delete the character typed if this is not a valid character.
               $(this).val(curval.substring(0, i) + curval.substring(i+1, this.value.length));
              }
             }
             
             // Insert formatting at the right places
             if (curchrindex == 3) 
             {
              $(this).val("(" + curval + ")" + "-");
             }
             else if (curchrindex == 9)
             {
              $(this).val(curval + "-");
             }
             
             //Do not allow more than 15 characters including the brackets and the "-"
             if (curchrindex == 15) 
             {
              //delete the last character typed 
                 $(this).val(curval.substring(0, this.value.length-1 ));
             }
             
            });
          };
        })( jQuery );
        
        
        
        

        The HTML code to use this plug-in

        <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
        <html>
        <head>
        <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
        <title>Insert title here</title>
        <script type="text/javascript" src="./scripts/jquery.js"></script>
        <script type="text/javascript" src="./jquery.usphone.js"></script>
        </head>
        
        <body>
            Please Enter a Valid US Phone number : 
            <input type = "text" id = "phonenumber" />
        </body>
        
        <script>
            $('#phonenumber').usphone();
        </script>
        
        </html>
        

        Wednesday, December 22, 2010

        Floating point numbers - great blog entry

        A great blog entry from my friend Ravi on Floating point arithmetic - great read, as this is more than often a confusing subject to a lot us in the programmer community.

        Floating-point-basics-made-easy

        Friday, December 17, 2010

        Springroo with STS - Issue - Missing artifact Errors

        I was trying to setup a springroo project on STS and kept getting Errors like the following
        Missing artifact org.springframework.roo:org.springframework.roo.annotations
        - It took me quite a lot of time to figure out what I was doing wrong. When you create the new springroo Project on STS,  make sure that the Maven Support - Provider is set to "Dependency management Only" - By default it is set to "Full maven build". It looks like the first version of STS had defaulted this value to "Dependency Management Only" and hence you will not see any mention of setting this value on the tutorials or on the videos.

        Thursday, December 09, 2010

        SEO and Web Analytics basics

        Recently presented SEO and Web Analytics to a set of Developers and the slides form the presentation is on my slideshare channel.

        http://www.slideshare.net/sreekanthn/seo-and-analytics-basics

        Saturday, October 30, 2010

        JavaMail : Altering the From field

        There are 2 APIs on the MimeMessage Object, sentSender and setFrom. If you are thinking that the Sender address would go in to the From Address field and using the setAddress field to set it, that would not work. It only sets the RFC 822 "Sender" header field. It does not alter the "From" Header which is used to show the From Address on the email. The code you should be using would look like the following

         MimeMessage message = new MimeMessage(session);
        
         message.setFrom(new InternetAddress("support@mydomain.com"));
         message.setSubject(subject);
         message.setContent(body, "text/html");
         message.setRecipient(Message.RecipientType.TO, new InternetAddress(recipients));
        
         Transport.send(message);
        
        

        Thursday, October 21, 2010

        Going Mobile for your enterprise? What to consider?

        There is a lot of buzz out there. Every enterprise wants a presence on the hand held device and rightly so. We have enough proof that it is the future. There are a plethora of platforms to run on, all of them distinct and to an extent proprietary. It is always a tough choice for the architects to choose what are the steps to follow and what to target. The following are some of my experiences and learning on this.

        The Mobile Web

        For any organization which is venturing out to the mobile platform, the first and the easiest option to have a presence is the Mobile Web. Most smart phones come with full fledged HTML browsers capable of running JavaScript and even flash. It is very quick to do so as all you need is to make a customized UI for fitting in the smaller screen sizes. (More on what to consider on my earlier post here)

        The advantages are many,

        • The time to market and cost is minimal.
        • You target all or most of the devices in one shot.
        • You can reuse your entire back-end infrastructure as it is.
        • You could always have 2 versions of your site - one for high-end devices and other for lower end and redirect traffic according to the User Agent headers.
        • It helps to understand your user base. (Explained in next section)

        Understand your user base

        If you look at the web there is enough data available on the prominent platforms, which is most popular today, which one is growing faster etc etc. I would think that as architects we look at our specific enterprises user base before jumping in to conclusions.

        For following points to be noted regarding developing native apps:

        • It is practically impossible for enterprises to target all platforms.
        • Also generic solutions like J2ME (which can run on all platforms having the run time installed) have been found to be not as powerful in exploiting the phone's specific features in a lot of platforms. So at times, your application loses the coolness it could have had by developing on the native SDK.

        Which platform should I target?

        I believe the answer lies in knowing your user base. And that is where your mobile website helps. By capturing the analytics on your mobile website, you could easily come up with the required data for the most prominent platforms in your user base. This is a fairly quick exercise and the patterns should be clear in a couple of months if you have enough traffic on your mobile web site.

        It makes sense to drive your decision based on data and customize your solutions to your specific user base.