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