#How to close unused OkHttp threads?

1 messages · Page 1 of 1 (latest)

fallen birch
#

I did thread dump of my Discord bot that uses OkHttp and I figured out that there're over 200 OkHttp threads just a few moments after bot is started. How can I close them once they have been used?

jade bayBOT
#

<@&987246399047479336> please have a look, thanks.

#

Here is an AI assisted attempt to answer your question 🤖. Maybe it helps! In any case, a human is on the way 👍. To continue talking to the AI, you can use </chatgpt:1108714622413963314>.

#
TJ-Bot
I did thread dump of my Discord bot that uses OkHttp and I figured out that there're over 200 OkHttp threads just a few moments after bot is started. How can I close them once they have been used?

e these unused OkHttp threads to prevent resource wastage?

To close unused OkHttp threads in your Discord bot, you can try implementing a custom connection pool with a maximum number of idle connections and timeouts. This will help manage the number of threads created by OkHttp and clean up any unused connections.

You can do this by creating a new OkHttpClient instance with a custom connection pool:

ConnectionPool connectionPool = new ConnectionPool(5, 10, TimeUnit.MINUTES); // Customize the pool size and timeout as needed
OkHttpClient client = new OkHttpClient.Builder()
        .connectionPool(connectionPool)
        .build();

By setting a maximum number of idle connections and timeouts, you can control the number of threads created by OkHttp and close any unused connections after a certain period of inactivity.

Additionally, you can also manually close the OkHttpClient instance when your bot is shutting down to ensure all resources are properly cleaned up:

client.dispatcher().executorService().shutdown();
client.connectionPool().evictAll();

By implementing these changes, you should be able to effectively manage the number of OkHttp threads in your Discord bot and prevent resource wastage.

icy vigil
#

eh

#

is that causing an actual performance issue?

fallen birch
#

I mean not really but it seems very weird

#

Having 80% of threads be unused OkHttp threads

icy vigil
#

well it makes a thread pool

#

so presumably it just has them "just in case"

#

you can configure the size of the pool

#

or maybe even not pool

#

let me check the docs

fallen birch
#

sure

icy vigil
#

try configuring the connection pool for like 5 max idle connections

#

see if that is where your threads are coming from

fallen birch
#

Okay, will give it a try

#

thanks