Search code examples
okhttpcodahale-metrics

Instrumenting OkHttpClient


I'm writing a small wrapper library that'll allow me to monitor the internals of an OkHttpClient using Dropwizard Metrics: https://github.com/raskasa/metrics-okhttp.

I'm having some trouble properly instrumenting the ConnectionPool - specifically, periodically calling getConnectionCount() to monitor the number of open TCP connections.

When an instance of OkHttpClient is initially created, getConnectionPool() is null - which I'm expecting. But also, subsequent attempts to access the pool still return null even during/after executing some network requests.

I'm assuming there is proper way to monitor the ConnectionPool because it is a part of the public API, but I'm just not seeing it clearly at the moment.

So:

  • Is there way to access the ConnectionPool at the point where OkHttpClient.getConnectionPool() is not null?
  • If this isn't the best approach, any advice for going about this a better way?

Solution

  • Try this:

    OkHttpClient client = ...
    client.setConnectionPool(ConnectionPool.getDefault());
    

    That'll give you the same connection pool you'll get anyway, but it'll give it to you sooner.