Harry Muscle
Harry Muscle

Reputation: 2387

Groovy: Multi-Threaded use of the RESTClient class from Codehaus

I'm using the RESTClient class from Codehaus (http://groovy.codehaus.org/modules/http-builder/apidocs/index.html?groovyx/net/http/RESTClient.html) in my application, however, I'm running into issues when multiple threads try to use the client at the same time. After some reading I found out that this is because the RESTClient class by default uses a single connection that cannot be shared by multiple threads. The answer seems to be to use a different connection class that allows concurrent use from multiple threads (as mentioned here: Groovy RestClient with many connections). However, I can't seem to find anywhere how to tell the RESTClient class to use these other types of connections. Is this even possible? I'm hoping to keep the advantage of the RESTClient, so using just a generic HTTPBuilder or AsyncHTTPBuilder class instead of the RESTClient sort of defeats the purpose of the RESTClient class (unless it's possible to have the HTTPBuiler/AsyncHTTPBuilder class spit out a RESTClient connection).

Alternatively, should I be just creating a new RESTClient for each thread?

Upvotes: 1

Views: 2054

Answers (2)

jerryb
jerryb

Reputation: 1639

Here is some code for a subclass of HttpBuilder which will create a thread-safe pool of client connections for a single instance of ThreadSafeHTTPBuilder.

import groovyx.net.http.HTTPBuilder
import org.apache.http.impl.client.AbstractHttpClient
import org.apache.http.impl.client.DefaultHttpClient
import org.apache.http.impl.conn.PoolingClientConnectionManager
import org.apache.http.params.HttpParams

class ThreadSafeHTTPBuilder extends HTTPBuilder {

    protected AbstractHttpClient createClient(HttpParams params) {
        PoolingClientConnectionManager cm = new PoolingClientConnectionManager()
        cm.setMaxTotal(200) // Increase max total connection to 200
        cm.setDefaultMaxPerRoute(20) // Increase default max connection per route to 20
        new DefaultHttpClient(cm, params)
    }
}

Usage:

def client = new ThreadSafeHTTPBuilder()

Upvotes: 4

injecteer
injecteer

Reputation: 20707

Alternatively, should I be just creating a new RESTClient for each thread?

yes, it's the easiest way

Upvotes: 0

Related Questions