6

https://github.com/xetorthio/jedis/wiki/Getting-started

using Jedis in a multithreaded environment

You shouldn't use the same instance from different threads because you'll have strange errors. And sometimes creating lots of Jedis instances is not good enough because it means lots of sockets and connections, which leads to strange errors as well.

A single Jedis instance is not threadsafe

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

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

I want to know why? Can anyone help me please

BoTaoLiu
  • 65
  • 1
  • 5

1 Answers1

7

A single Jedis instance is not threadsafe because it was implemented this way. That's the decision that the author of the library made.

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

For example these lines:

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

As you can see the transaction field is shared for all threads using Jedis instance and initialized in this method. Later this transaction can be used in other methods. Imagine two threads perform transactional operations at the same time. The result may be that a transaction created by one thread is unintentionally accessed by another thread. The transaction field in this case is shared state access to which is not synchronized. This makes Jedis non-threadsafe.

The reason why the author decided to make Jedis non-threadsafe and JedisPool threadsafe might be to 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 multithreaded environment you can use JedisPool and get thread safety.

medvedev1088
  • 3,645
  • 24
  • 42
  • This should happen when we use same Jedis instance across all threads. Can't we initialize different instances of Jedis for different thread? – Aashish Katta Aug 06 '18 at 07:13
  • @medvedev a jedispool would still limit it to one request out, one response in. is there anwyway you can get around this limitation? in theory? redisson uses netty and channels for this purpose they claim. I am not sure that redis can be sent multiple concurrent requests from the same connection. is that possible in theory? the way jedis is implemented won't work since it sends a command and then waits globally on an inputstream from the connection meaning if two requests are sent, the response might be a mix of the two. is that a jedis limitation or a redis one per se? – mjs Sep 05 '20 at 05:59