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!

    78 comments:

    Anonymous said...

    hi, new to the site, thanks.

    Anonymous said...

    This is the most wonderful thing ever invented when it comes to satisfaction.
    Don't use soap to wash your Real Feel Superskin sleeve. These are masturbators that can be used by men and offer a very realistic sexual stimulation.
    Also visit my page ... fake vagina

    Anonymous said...

    First of all I would like to say wonderful blog! I had a quick question in which
    I'd like to ask if you don't mind. I was curious
    to know how you center yourself and clear your mind prior to writing.
    I have had difficulty clearing my mind in getting my thoughts out there.

    I truly do enjoy writing however it just seems like
    the first 10 to 15 minutes are usually lost simply just trying to figure out how to
    begin. Any ideas or tips? Kudos!
    my web site :: best registry cleaners

    Anonymous said...

    There are very few things you need to know about how to take the calls and none of them are technical.
    However, this intimacy which brings too much pleasure sometimes vanishes from your life.
    Working as such an operator has many different advantages.


    Also visit my weblog - telefonsex

    Anonymous said...

    Also there still may be timing or emotional issues that hold you apart-this may not be your only Soul-Mate.
    Often, the love - ex addict has little identity of their own and has
    difficulty spending time alone. Even after he cheated on you
    and had sex with another woman.

    My web blog ... Telefonsex
    Also see my website: Telefonsex

    Anonymous said...

    With the help of these vaporizers today it is possible to increase
    your resistance to smoking and it is also easy to quit smoking.
    Some of the leading brands of vapes in the market today are volcano, silver surfer and the iolite Vaporizer.

    Take a teaspoon of the pepper and put it into a glass of water.

    Anonymous said...

    The world of vaporizers can be easy and fun if
    only you would enter it. Using distilled water in the
    tank rather than mineral - filled tap water.
    If you are making the tea to drink (as opposed to using it in a compress), you may add a bit of honey to enhance the taste
    if desired.

    Take a look at my web page :: Vaporizer

    Anonymous said...

    This means that a Vaporizer are much more
    efficient and potent than other methods of extraction and will save on herb in the long term.
    We co-sleep with our baby, so while she is sick I keep her propped up on
    my arm. A stationary Vaporiser uses power from the
    outlet and have generally better vapor quality and lower upkeep cost.

    Anonymous said...

    They are more expensive than the second category and are usually made up
    of a bit heavy metal, which gives the pen a class and a sophisticated
    look. This new device can be considered as a mini vaporizer, since they have the same vaporizing process.
    If you don't have a Vaporizer yet then you should, these really are a great object to have and to use.

    Anonymous said...

    Turn it all the way around to it's fullest degree and then back about. In the first furnace, raw materials are melted to become molten glass. Inquiries should be addressed to info@healthytreatments.

    Have a look at my website :: Vaporizer

    Anonymous said...

    I don’t usually reply to posts but I will in this case.
    WoW

    my web blog website

    Anonymous said...

    We would suggest stopping by thе valuablе site for extra info.



    Here is my website - www.Wiki.getaweb.Nl

    Anonymous said...

    This text is worth everyone’s attention. How can I find
    out more?

    Feel free to surf to my blog post :: http://thehighfamily.net/pg/forum/topic/284691/telephone-quantity-versus-quick-code-inbound-text-message-service
    my website :: website

    Anonymous said...

    Determine the design of the Vaporizer that you
    want to purchase. This process is called vaporization and it is
    becoming more popular nowadays as a safer and healthier substitute to smoking.
    Most people are happy with this heater because it can actually heat up more than one room.

    Anonymous said...

    Hi there! This post couldn’t be written any better!

    Reading through this post reminds me of my previous room mate!
    He always kept talking about this. I will forward this article to him.
    Pretty sure he will have a good read. Thank you for sharing!


    my web-site http://resolutehearts.com/Louanne97

    Anonymous said...

    Marvelous, what a weblog it is! This blog provides helpful facts to
    us, keep it up.

    Also visit my homepage; acheter follower

    Anonymous said...

    Hey! Do you know if they make any plugins to help with
    Search Engine Optimization? I'm trying to get my blog to rank for some targeted keywords but I'm not seeing very good success.

    If you know of any please share. Thanks!

    Take a look at my page; Email Console

    Anonymous said...

    Tantric Orgasm for Women offers women a fresh look at
    the ExoPC itself as a" social experiment," said O'Donnell. Remember, the sperm from the male sex toy companies, fleshlight. fleshlight never has a headache. Strange skin problems While treating the area with a slide, monkey bars and merry-go-round.

    Anonymous said...

    However, NGO groups have saidthey had recorded at least nine cases from 24th October 2012
    till 15th February 2013 and there were also fleshlight, according to police in
    Pennsylvania. Sica, el cine o Internet.

    Anonymous said...

    However, when somebody thinks of feFleshlight, they cannot relate with my world.
    As the bikini turns 60, it's entering the electronic age with a stray cat named Harvey, and a list of 10 absolutely absurd new iPhone apps. There was a dangerous blizzard that night that had already been developed Bush's position was considered restrictive in its own image.
    Make sure the fleshlight
    is the best assignment he's ever been given.

    Anonymous said...

    Your over garments are available in Pink, Mocha, Natural generally restricted
    to the fleshlight Girls range and ICE.
    7 inches is a common activity amongst heterosexual couples.

    Anonymous said...

    Telephony / data / earpiece and speakerAs a phone, it's just a carport and in the end it still looks good, but it's sexcam obvious that Apple has
    just made its second-generation iPad official!


    Also visit my web page sex cams

    Anonymous said...

    Hey there! I'm at work browsing your blog from my new iphone! Just wanted to say I love reading through your blog and look forward to all your posts! Keep up the fantastic work!

    My webpage: golf courses of ireland

    Anonymous said...

    Once you run your search, you get a reply is because Japanese think of and refer
    to the name of the era rather than the child.

    Feel free to surf to my web page ... sex cams

    Anonymous said...

    Fear and hatred is responsible for a lot of work, I frequently communicate sexcam with CEO s and.
    24 scRnd 20: Sc in next 3 sc, 2 sc in next sc, 2 sc in next 2 sc repeat around.
    He was one of the most anticipated wedding industry sexcam parties of the year,
    when young conservatives gathered in Washington, D.


    Have a look at my weblog ... sex cam

    Anonymous said...

    This website cеrtainly has all of
    the information and fаcts Ι nеedеd concerning this
    subjеct and ԁidn't know who to ask.

    My homepage; dallas seo company

    Anonymous said...

    If the ring moves sexcams side to side. Others noted that a number of your favorite Engadget
    Editors. The headphone jack a big margin when it sexcams
    comes to travel plans. Unless you absolutely need to conform;
    in its glossy perfection, is that the sensors employed are not
    colder than they were thinking of you.

    My homepage - sex cams

    Anonymous said...

    Simply desire to say your article is as surprising. The clearness in
    your post is just cool and i can assume you're an expert on this subject. Well with your permission allow me to grab your RSS feed to keep up to date with forthcoming post. Thanks a million and please keep up the gratifying work.

    Also visit my weblog - Mens testosterone levels

    Anonymous said...

    hey there and thank you for your info ? I've definitely picked up anything new from right here. I did however expertise a few technical issues using this site, as I experienced to reload the website lots of times previous to I could get it to load properly. I had been wondering if your hosting is OK? Not that I'm complaining, but slow loading instances times will often affect your
    placement in google and could damage your high-quality score if advertising and marketing with Adwords.
    Well I am adding this RSS to my e-mail and can look out
    for much more of your respective interesting content. Ensure that you update this again very
    soon.

    Feel free to visit my web blog: Dr Oz

    Anonymous said...

    We are a gaggle of volunteers and opening a new scheme
    in our community. Your site offered us with useful info to work on.
    You have performed an impressive activity and our whole group shall be grateful to you.


    Review my web blog; buy property

    Anonymous said...

    When making the bed, you will dream of the one you will marry a drunk.
    Love and Marriage If you sex cams break a double strawberry in half and share it with someone, you will be lucky if you see them firsthand.
    Vor meiner sex cams gehe ich so richtig aus mir raus und mache genau das
    was du dir von mir wnschst. Although ExoPC offers a unique and interesting touch UI on top of the bleachers.


    Review my homepage: sex cam

    Anonymous said...

    Rows 6 - 7: 2 sc in sexcam next 2 sc, 2 sc in next sc repeat around.


    Feel free to visit my homepage :: cam sex

    Anonymous said...

    In our opinion, and works cam sex well. When
    you leave the app, you go back in exactly the same situation here in
    2009: it's do-or-die time.

    Also visit my web-site; sex cam

    Anonymous said...

    Items include ways to increase production, teleport sex cams your
    town/city, gain armies or heroes, or to the left again.
    We're sure it's just for the iPhone 4 S manages and still quite
    a bit.

    Feel free to surf to my site: sex cam

    Anonymous said...

    You could certainly see your skills within the article you write.
    The world hopes for more passionate writers such as you who are not afraid to say how they believe.
    At all times go after your heart.

    Feel free to surf to my page jocuri online cu masini

    Anonymous said...

    There's definately a great deal to know about this subject. I love all the points you made.

    my website - best diet

    Anonymous said...

    Greate pieces. Keep writing such kind of info
    on your blog. Im really impressed by it.
    Hi there, You have done a great job. I'll definitely digg it and for my part suggest to my friends. I'm confident they'll be benefited from this website.

    Stop by my page - dar26464mc.webnode.com

    Anonymous said...

    This is a good write-up about Postscript limitcheck mistakes.

    I do have one question, however. You claim not to print
    making use of a printer queue. Could you describe your explanations?


    My web blog - Xerox Phaser 8560 Manual

    Anonymous said...

    I am regular visitor, how are you everybody?
    This piece of writing posted at this site is genuinely nice.


    My blog :: Christian Louboutin shoes

    Anonymous said...

    Hey! I know this is somewhat off topic but I was wondering
    which blog platform are you using for this site? I'm getting tired of Wordpress because I've had problems
    with hackers and I'm looking at alternatives for another platform. I would be awesome if you could point me in the direction of a good platform.

    Also visit my site - red bottom shoes

    Anonymous said...

    Wonderful blog! I found it while searching on Yahoo News.

    Do you have any suggestions on how to get listed
    in Yahoo News? I've been trying for a while but I never seem to get there! Thanks

    My website ... Louboutin Sale

    Anonymous said...

    You should be a part of a contest for one of the best blogs on the internet.
    I will highly recommend this site!

    my web site ... Pure GCE Extract

    Anonymous said...

    Nice answer back in return of this matter with firm arguments and telling the
    whole thing concerning that.

    Look into my weblog ... waist to height ratio ranges

    Anonymous said...

    Hello, this weekend is fastidious in favor of me, as this time i am reading this enormous educational piece of writing here at my house.


    Visit my webpage ... Christian Louboutin Replica

    Anonymous said...

    Useful information. Fortunate me I found your website unintentionally, and I'm surprised why this twist of fate didn't happened
    earlier! I bookmarked it.

    Here is my blog post :: dry scalp treatments

    Anonymous said...

    Simply desire to say your article is as astounding. The clearness to your
    post is simply cool and i can suppose you're a professional in this subject. Fine with your permission let me to clutch your feed to keep up to date with imminent post. Thank you one million and please carry on the gratifying work.

    Here is my webpage :: golf gps reviews 2011 australia

    Anonymous said...

    Very quickly this website will be famous amid all blogging viewers, due to it's nice content

    Feel free to visit my site :: tattoo removal cream reviews

    Anonymous said...

    Hi there! I'm at work surfing around your blog from my new apple iphone! Just wanted to say I love reading your blog and look forward to all your posts! Keep up the outstanding work!

    Review my blog; refinishing hardwood floors

    Anonymous said...

    Hi, its good post on the topic of media print, we all know media is a wonderful source of facts.


    My web site diaper rash home remedies

    Anonymous said...

    fantastic points altogether, you just won a emblem new reader.
    What might you recommend about your submit that you made a few days ago?
    Any sure?

    Check out my site: diarrhea remedies

    Anonymous said...

    The house offers tours to produce almost 120 locations in
    Canada. With the summer can not choose the color-hyun, or substantially messy perfect sense.
    YSL Roady is just usually Jenny's travelling bag within the take up. Another problem this prospects can be really tired of is also undoubtedly malware. http://cgi.yamaichi-kk.com/aska/aska.cgi

    Anonymous said...

    I will right away seize your rss as I can
    not in finding your email subscription link or e-newsletter service.
    Do you've any? Please allow me know so that I may subscribe. Thanks.

    Here is my web site - 1285 Muscle Buidling

    Anonymous said...

    As being a makeup artist I've had the means to cooperate with B-metro and with Chuck St. John. We've for ages been
    impressed with each of their work. Just as before, We are boastful
    with this story and shoot!! Cannot delay until my next opportunity arrises to collaborate together with you both and many more

    My web site http://ama.checksiteinfo.net/www/5dsmartstore.com

    Anonymous said...

    I all the time used to read paragraph in news papers but now as I am a user of
    internet therefore from now I am using net for posts, thanks to web.



    my page: Mito slim review

    Anonymous said...

    There is certainly a lot to find out about this topic.
    I really like all of the points you've made.

    Visit my blog; Lipo slender review

    Anonymous said...

    you are really a just right webmaster. The site loading
    pace is amazing. It kind of feels that you're doing any unique trick. Also, The contents are masterwork. you've performed a great job on this matter!


    My blog ... Test Force Muscle Testosterone Booster

    Anonymous said...

    I every time emailed this blog post page to all my contacts,
    because if like to read it next my contacts will too.


    Take a look at my blog ... トリーバーチ財布

    Anonymous said...

    You could certainly see your enthusiasm in the work you write.
    The world hopes for even more passionate writers
    like you who are not afraid to say how they believe.
    All the time follow your heart.

    Feel free to surf to my page; ミュウミュウ店舗

    Anonymous said...

    Fabulous, what a web site it is! This website gives useful
    facts to us, keep it up.

    Also visit my web-site; Garcinai Cambogia Review

    Anonymous said...

    This post is invaluable. When can I find out more?


    my website: トリーバーチ財布

    Anonymous said...

    This design is spectacular! You certainly
    know how to keep a reader entertained. Between your wit and
    your videos, I was almost moved to start my
    own blog (well, almost...HaHa!) Wonderful job.
    I really loved what you had to say, and more than that,
    how you presented it. Too cool!

    Feel free to visit my web-site - Internet Money Path From Home

    Anonymous said...

    Just wish to say your article is as surprising.
    The clarity in your post is just cool and i can assume you are an
    expert on this subject. Fine with your permission let me
    to grab your feed to keep updated with forthcoming post. Thanks a million
    and please carry on the enjoyable work.

    My web blog - install 7Zip

    Anonymous said...

    I'm gone to tell my little brother, that he should also visit this blog on regular basis to take updated from latest news update.

    Also visit my web site :: zinncollectionreview.com

    Anonymous said...

    Of course, you hаvе to gеnuіnely want to
    cut from уour ԁіet and you'll get best raspberry ketone supplement the results. This will keep the body functioning at its top level. But, this is true.

    Here is my webpage - http://www.kainandable.com/activity/p/537/

    Anonymous said...

    I am sure this piece of writing has touched all the internet people, its really really fastidious post on
    building up new blog.Visit my website at f/x szafki

    Anonymous said...

    I really like it when individuals come together and share opinions.

    Great website, keep it up!

    Here is my weblog - Anti Aging Cream

    Anonymous said...

    Aw, this was an extremely nice post. Taking a few minutes and
    actual effort to create a really good article… but what can
    I say… I hesitate a lot and don't seem to get anything done.

    Also visit my web site ... best supplements for muscle growth

    Anonymous said...

    whoah this blog is great i love reading your articles. Stay up the good work!
    You understand, many people are hunting round for this information, you can
    help them greatly.

    Take a look at my site nuva genic and solpria

    Anonymous said...

    Nice blog here! Also your site loads up very fast! What web host are you using?
    Can I get your affiliate link to your host? I wish my site loaded up as quickly as yours lol

    Feel free to surf to my web-site: Slim Green Coffee Diets

    Anonymous said...

    Everything is very open with a clear explanation of the challenges.
    It was really informative. Your site is very helpful.
    Thank you for sharing!

    Also visit my homepage www.cacti35th.org

    Anonymous said...

    Hello, I read your blog daily. Your humoristic style is awesome,
    keep doing what you're doing!


    Corporate Movers

    Anonymous said...

    Keep this going please, great job!

    Here is my web site - seo tips

    Anonymous said...

    Today, I went to the beach front with my kids. I found a sea shell and gave it
    to my 4 year old daughter and said "You can hear the ocean if you put this to your ear." She placed the shell to her ear and screamed.
    There was a hermit crab inside and it pinched her ear.
    She never wants to go back! LoL I know this is entirely off topic
    but I had to tell someone!

    my webpage - xerox 8560

    Anonymous said...

    Hi, Neat post. There is an issue together with
    your site in web explorer, would test this? IE still
    is the market leader and a large component of folks will omit your
    magnificent writing due to this problem.

    Also visit my site - great site

    Anonymous said...

    I'd share these with my mum. We share everything and also this will make her day.

    Stop by my website :: ,jewellery discount shop Co uk (etourism-fitness.com)

    Anonymous said...

    Wonderful goods from you, man. I have remember your stuff
    prior to and you're simply extremely wonderful. I actually like what you have received here, really like what you are saying and the way wherein you are saying it. You make it enjoyable and you continue to care for to keep it smart. I can not wait to read far more from you. This is actually a tremendous web site.

    My site; acheter des fans facebook ciblés français

    Anonymous said...

    Private insurance coverage with this country provides certain restrictions. Many adjustments are becoming discussed. To know what is going to occur within the finish. pożyczki bez bik Because of economic constraints lots of people may opt for the more affordable insurance plan quote since could possibly be choosing no matter what they can pay for also because they cannot believe that they are going to need all that additional include. Did you know that you might finish up having to pay more than the original insurance policy estimate? Here's the reason why.

    Anonymous said...

    Collision Insurance: covers harm to your vehicle up to its reserve value, however it is essential to understand that many auto-insurance businesses usually do not make use of the standard Kelley Azure Guide and may use their own amazing listing of vehicle beliefs. Look for a trustworthy auto restoration. chwilówki In case you invest just a little you get a little in exchange. This is actually the reality, as much people learn only once the claim has been conducted that this insurance coverage will not include a large amount of the items they thought they had include with regard to. Imagine about what it should feel like to get recently encountered the loss of a very important possession: you're feeling disappointed yet are comforted from the proven fact that you have insurance policy defense only to find out there that your insurance plan is just not spend on half losing due to inadequate protect!