Bob
Bob

Reputation: 8504

Making Apache http client threadsafe

I am on Scala 2.10.2 and want to implement a thread-safe http provider using Apache http client 4.2.5, here's what I have done

import net.liftweb.json._
import net.liftweb.json.JsonDSL._
import scala.concurrent.Future

object AsyncHttpProvider {
  import org.apache.http.client._
  import org.apache.http.client.methods._
  import org.apache.http.impl.client._

  val httpclient = new DefaultHttpClient

  private def get(query: String) = {
    val httpget = new HttpGet(query)
    val brh = new BasicResponseHandler
    httpclient.execute(httpget, brh)
  }

  def getResponseBodyAsJValue(query: String): Future[JValue] = Future(parse(get(query)))
  def getResponseBodyAsJsonString(query: String): Future[String] = Future(get(query))
}

Since I am using Future, I want to make sure that the code is thread-safe, is it?

Upvotes: 0

Views: 1307

Answers (1)

kdrakon
kdrakon

Reputation: 172

It's documented that the DefaultHttpClient is threadsafe (http://hc.apache.org/httpcomponents-client-ga/tutorial/html/httpagent.html), but you don't need to recreate it inside your 'get' function. Usually, client creation is quite expensive and it can be more efficient to instantiate one or more pooled instances to be shared across threads. In this case, you could create or inject the instance into your object and reference it within the Future. The only new thing to create would be the Method and response handler.

Speaking of async calls, you may also consider looking athttp://hc.apache.org/httpcomponents-asyncclient-dev/examples.html

Upvotes: 1

Related Questions