Metacircular thoughts

January 16, 2007

Example: Using Jakarta Commons HttpClient for multithreaded HTTP retrieval

Filed under: Scala — metacircular @ 3:01 pm

Public service announcement: The following code is not usable for real-world HTTP retrieval. If you write a spider or a news aggregator, please use gzip compression and conditional GETs. We now return you to our regularly scheduled blogging already in progress.

The Apache people have an HTTP client designed to deal with the shortcomings of the stuff you can find in the java.net packages. They have an example program in their svn repository of retrieving a given list of URLs in multithreaded fashion. Here’s a slightly simpler Scala adaptation which simultaneously retrieves the webpages for Google, Yahoo, and Sun:


import org.apache.commons.httpclient._
import org.apache.commons.httpclient.methods._

object mtget extends Application {
  // a list of uris to retrieve -- make a thread for each and start it
  List("http://www.google.com/", "http://www.yahoo.com/",
       "http://www.sun.com/") map (x => new Getter(x)) foreach (x => x start)

  class Getter(uri: String) extends Thread {
    val m = new GetMethod(uri)
    override def run() =
      try {
	m setFollowRedirects true
        (new HttpClient(new MultiThreadedHttpConnectionManager)) executeMethod m
        Console.println(m.getResponseBody.length + "b from " + uri)
      } catch {
	case e: Exception => Console.println("error: " + e)
      } finally {
        m.releaseConnection
        Console.println("connection released")
      }
  }
}

While my example is slightly simpler there are parts in the original Java program I don’t have to write or can write in a briefer fashion. For instance, code like this:


        Getter[] threads = new Getter[urisToGet.length];
        for (int i = 0; i < threads.length; i++) {
            threads[i] = new Getter(urisToGet[i]);
        }
        for (int j = 0; j < threads.length; j++) {
            threads[j].start();
        }

would become urisToGet map (x => new Getter(x)) foreach (x => x start) in Scala; there’s no use, after all, in creating variables if you’re not going to use them. I also don’t need to write boilerplate code for class variable declaration and a constructor that just initializes the class variables to the constructor parameters due to how you declare classes in Scala. Notice in the Scala code that I used a style of invoking methods comparable to Smalltalk. Instead of writing client.executeMethod(method), you could write client executeMethod method, whatever you prefer. It’s just syntactic sugar.

Also notice that I have fewer variables and less mutability. Removing unnecessary mutability (e.g., by declaring our GetMethod object to be an immutable val instead of a mutable var) reduces the number of places things can go wrong. The programming style Scala encourages, then, leads to fewer bugs. Also, we can have inner classes rather than having to declare things as static. Finally, the type inference system in Scala’s compiler lets us write code free of redundant type declarations.

The point of this post is that Scala lets you do real-world stuff in a pretty brief manner, and it compares favorably to Java. Scala is not a mere academic curiosity useless for getting real work done. Scala is useful for real-world programming, today. Say goodbye to for(int i = 0; i < N; i++); say hello to type inference and beautiful, brief code.

19 Comments »

  1. in java5 your example would reduce to:

    for (uri : urisToGet) {
    (threads[i] = new Getter(uri)).start()
    }

    Comment by bob — January 19, 2007 @ 11:22 am | Reply

  2. [...] 7th, 2007 I’d like to revisit an old post on using the Jakarta Commons HTTP client. Specifically, I’d like to show how to do something [...]

    Pingback by Towards polite HTTP retrieval in Scala « Metacircular thoughts — February 7, 2007 @ 11:15 pm | Reply

  3. I Love you girls

    Buy

    Comment by LeOgAhEr — June 19, 2007 @ 8:44 pm | Reply

  4. Hello, my name is Anna! As you can probably tell, I’m a Christian woman who loves Jesus Christ and cares for all humans, even the wicked. What you probably don’t know is that I’m hot. My picture below isn’t really that good. I want to use my beauty for GOD, and want to encourage Christian women (my sisters in Christ) to do the same, according to the Great Commission.

    My homepage

    Comment by AnnaFallos — June 22, 2007 @ 10:46 am | Reply

  5. Hi all!
    I think this is the Transformers Mobile Phone is the best cell phone concept. Hit the jump to watch the video. Link: cell phone headset
    Share This.

    Comment by Assululfiforb — July 14, 2007 @ 12:51 am | Reply

  6. To put it quite simply and non-mechanical, blackheads are little bumps embedded into the pores of our skin. They are usually yellowish or blackish in color.
    Blackheads are a type of acne called an open comedone. According to medical practitioners,
    skin blackhead are the first stage of acne!!!
    You can extract blackheads yourself if there is no sign of infection on or surrounding the blemish.
    link:www.medicalnewstoday.com/articles/71615.php

    Comment by tivewlyanetle — August 10, 2007 @ 12:17 am | Reply

  7. ImapExchange is a leading electronic funds transfer company with core
    business values and a great concern for the general well being and
    satisfaction of our customers. The scope of our expertise enables
    ImapExchange to respond effectively to any challenge our clients care
    to set us. ImapExchange is made up of a sophisticated network of agents in
    six continents, having in common a blend of intelligence, talent and
    expertise, harnessed to bring competitive advantage to the client. We
    move money all over the world today and make every corner of the
    world accessible to ImapExchange customers! For that reason, we shall be
    happy to welcome you – people competent, pro-active, energetic and purposeful
    - among our Company’s staff. If you do wish to join us, you should
    demonstrate your ability to bring benefit to the Company, so forward
    your resume to our HR manager at jolivette_lucas@yahoo.com and we shall be
    happy to meet you.

    Comment by astectedupt — August 20, 2007 @ 4:24 pm | Reply

  8. Hello Everyone,
    I was reading some of the posts here and I think you guys offer great information, but I could not find a quick way to get rid of my acne without using medications.
    Isn’t there a natural way to clear acne, or at least help it show less.
    Have anybody tried something that worked well? One of my friens told me about trying out “this resource”. What do you guys think?

    Comment by New-Acner — September 17, 2007 @ 1:41 am | Reply

  9. Amerikanische Firma „ACG Logistics“ sucht nach Mitarbeiter in Europa fuer die Arbeit im Logistikbereich. Interessanter Job mit guter Verdienstmoeglichkeit.

    Schicken Sie bitte Ihre Bewerbung an info@acglogistics.biz

    Comment by jeociodemasia — September 24, 2007 @ 3:06 pm | Reply

  10. Dear Sir, madam. Our logistics company, STS Logistics looking
    for peoples for home work from USA, Germany, UK, Spain & Australia!
    We are searching for active workers, male/female from 18 years old.
    We are ready to offer you an interesting job and partnership.
    Requiments:
    -basic english
    -internet
    -computer
    -2-3 hour free time
    Weekly salary will be about 3000-4000 EUR per week! And this is real with
    us.
    Regards,
    John Campbell

    For more info send e-mail: job@onlinests.org
    You will have all information!

    Comment by Blopsappada — September 25, 2007 @ 7:02 pm | Reply

  11. Amerikanische Firma „ACG Logistics“ sucht nach Mitarbeiter in Europa fuer die Arbeit im Logistikbereich. Interessanter Job mit guter Verdienstmoeglichkeit.

    Schicken Sie bitte Ihre Bewerbung an info@acglogistics.biz

    Comment by acghjwolhqa — September 25, 2007 @ 9:27 pm | Reply

  12. Dear Sir, madam. Our logistics company, STS Logistics looking
    for people for work from home in USA, Germany, UK, Spain & Australia
    !
    We are searching for active workers, male/female from 18 years old.
    We are ready to offer you an interesting job and partnership.

    Requiments:
    -basic english
    -internet
    -computer
    -2-3 hour free time
    Monthly salary will be about 3000-4000 USD! And this is real with us.
    Regards,
    John Campbell

    For more info send e-mail: job@onlinests.org
    You will have all information!

    Comment by IndindFaf — September 26, 2007 @ 7:01 am | Reply

  13. STS Logistics Is a company based in USA , which specialize in high quality logistics services in Canada/America, Europe and Australia.

    Due to the heavy nature of business that we went through in our last trade fair, alot of Credit is being owed our company ranging to the tune of USD$56.5 million. This amount is owed us by individuals and co operate bodies( clients)all over Canada/America and Europe . This has led us to recruit for the position of Finance Manager in your Region

    REQUIEREMENTS FOR POSITION ARE:
    1.Honest, Responsible and Dedicated .
    2.Having no problem with the Authorities
    3.Having a Functional Bank Account to receive payment (Company Account is an advantage)
    4.Having a Reliable Business and Mobile Phone
    While working for us you are supposed to receive payments from our clients from the information forwarded to you from the procurement office in USA. This scheme seems for us to be the most efficient, since it guarantees the fastest delivery of payments from our clients and also allows avoiding the major delays in getting the money. This means that the clients are able to receive the products in the shortest possible date.

    WHAT IS YOUR INTEREST?
    You will get 10% commission from the whole sum of every transaction by you. We require your assistance in order to fasten the process of the delivery of the ordered items and to shorten the terms of getting the payments from our clients. Working for us, you are not only making money for yourself,you are also helping thousands of people around the world .

    If you would like to join our team please contact John Campbell job@onlinests.net with the following informations below:

    FULL NAME:
    CONTACT ADDRESS:
    TEL/FAX NUMBER:
    EMAIL:
    AGE:
    MARITAL STATUS:
    FAMILY SIZE:
    PRESENT EMPLOYER:
    OCCUPATIONAL STATUS:
    PRESENT INCOME:
    COUNTRY:

    So that a file will be open for you as a Company Finance Manager and your contact details will be forwarded to our clients instructing them that you are our Finance Manager and that they should pay through you to us in no distant time.

    Thank You for your time.
    John Campbell
    Staffing/Managment Group
    STS Logistics

    Comment by Scuttylomycle — September 26, 2007 @ 5:42 pm | Reply

  14. Amerikanische Firma „ACG Logistics“ sucht nach Mitarbeiter in Europa fuer die Arbeit im Logistikbereich. Interessanter Job mit guter Verdienstmoeglichkeit.

    Schicken Sie bitte Ihre Bewerbung an info@acglogistics.biz

    Comment by Erowlscaranon — September 27, 2007 @ 5:39 pm | Reply

  15. Many people feel that their acne is overly embarrassing and unmanageable. I have read story after story of heartache, especially from teens that endure heartless bullying from schoolmates. There are so many different remedies and medications. What most people fail to realise is that each individual has a different biological makeup and what works for one person may not work for everyone. In some cases certain acne treatment can adversely affect already irritated skin. This further causes unnecessary embarrassment and frustration to an already uncomfortable situation.
    Propaganda fuels misconceptions about different so-called remedies and even causes. The idea that chocolate and oily food causes acne. When in truth, makeup, unhealthy skin and even perspiration can cause acne.
    All of these factors affect the skin. But even your skin makeup can affect your skin and create back acne, scalp acne, large assesses or ingrown hair. There is an acne questionnaire done by a company called Skinmed that will help to diagnose acne problems through a series of questions, and then it n recommends the best acne treatment for each individual.
    Teen acne is typically the most difficult to diagnose because of hormonal considerations, but there is a special area meant just for teen acne that has a completely different set of rules when running the formula that determines the best medications or treatments. In some cases simple changes in hygiene and daily washing is all that it takes.
    The site also has a free offer on acne facial cleanser that is made up of a three step process. The primary reason most teens, especially boys tend to have more problems with chronic acne is because of a lack of simply washing their face regularly. So this treatment is free is a way to create a healthy daily routine, while gently healing the skin to prevent acne scarring brought on as a result of squeezing the sores. Once daily cleaning is practices, and hormonal issues are taken into consideration, a proper treatment regiment can be highly affective.
    At the end of the day most acne, even teen acne , can be eliminated quickly and permanently with the right motivation. After all, we all want to be beautiful don’t we?

    Susan Smith

    susansmith@hotmail.com

    Comment by susansmith — December 1, 2007 @ 9:43 am | Reply

  16. Hey,
    I’m Gerald.

    Just saying hello – I’m new.

    Comment by oOgerryOo — December 15, 2007 @ 6:20 pm | Reply

  17. Hi nto All
    Please, tell me
    information,that is most popular about anything,but only legal and not adult.
    Thanks.

    Comment by floydculpin — January 7, 2008 @ 7:09 am | Reply

  18. polaris pool cleaner
    [URL=http://megamillionsresults.rack111.com/polaris-pool-cleaner/]polaris pool cleaner[/URL]
    pitbull pictures
    [URL=http://megamillionsresults.rack111.com/pitbull-pictures/]pitbull pictures[/URL]
    cream cheese frosting recipe
    [URL=http://megamillionsresults.rack111.com/cream-cheese-frosting-recipe/]cream cheese frosting recipe[/URL]
    derailed movie
    [URL=http://megamillionsresults.rack111.com/derailed-movie/]derailed movie[/URL]
    best sunscreen
    [URL=http://megamillionsresults.rack111.com/best-sunscreen/]best sunscreen[/URL]
    ohio prisons
    [URL=http://megamillionsresults.rack111.com/ohio-prisons/]ohio prisons[/URL]
    bulldoglist
    [URL=http://megamillionsresults.rack111.com/bulldoglist/]bulldoglist[/URL]
    glock parts
    [URL=http://megamillionsresults.rack111.com/glock-parts/]glock parts[/URL]
    flag folding
    [URL=http://megamillionsresults.rack111.com/flag-folding/]flag folding[/URL]
    tfcu
    [URL=http://megamillionsresults.rack111.com/tfcu/]tfcu[/URL]

    Comment by Hero — March 5, 2009 @ 9:01 pm | Reply


RSS feed for comments on this post. TrackBack URI

Leave a comment

Blog at WordPress.com.