Why is one instance of Jedis not thread safe?


using Jedis in a multithreaded environment

You cannot use the same instance from different threads because you will have weird errors. And sometimes making many Jedis instances is not good enough because it means a lot of sockets and connections, which also leads to weird errors.

One instance of Jedis is not thread safe

! To avoid these problems, you should use JedisPool, which is a streaming pool of network connections. You can use a pool to reliably create multiple Jedis instances if you return the Jedis instance to the pool when you're done. This way you can overcome these strange errors and achieve great performance.

=============================================== ==

I want to know why? Can anyone help me?


source to share

1 answer

One Jedis instance is not thread safe because it was implemented that way. This is the decision taken by the author of the library.

You can check the source code of BinaryJedis which is Jedis super type https://github.com/xetorthio/jedis/blob/master/src/main/java/redis/clients/jedis/BinaryJedis.java

For example, these lines:

public Transaction multi() {
    client.getOne(); // expected OK
    transaction = new Transaction(client);
    return transaction;


As you can see, the transaction field is shared across all threads using the Jedis instance and is initialized in this method. Later this transaction can be used in other ways. Imagine that two threads are simultaneously performing transactional operations. The result could be that a transaction created by one thread is inadvertently opened by another thread. The transaction field in this case is shared and is not synchronized. This makes Jedis non-threading.

The reason the author chose to make Jedis non-threadsafe and JedisPool threadsafe can provide flexibility for clients so that if you have a single threaded environment you can use Jedis and get better performance, or if you have a multi threaded environment you can use JedisPool and ensure thread safety.



All Articles