为什么单个Jedis实例不是线程安全的? [英] Why A single Jedis instance is not threadsafe?

查看:777
本文介绍了为什么单个Jedis实例不是线程安全的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

https://github.com/xetorthio/jedis/wiki/入门

在多线程环境中使用Jedis

using Jedis in a multithreaded environment

您不应使用来自不同线程的相同实例,因为您会遇到奇怪的错误.有时创建大量的Jedis实例还不够好,因为这意味着大量的套接字和连接,这也会导致奇怪的错误.

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.

单个Jedis实例不是线程安全的

A single Jedis instance is not threadsafe

!为避免这些问题,应使用JedisPool,它是网络连接的线程安全池.可以在完成后将Jedis实例返回到池中的情况下,使用该池可靠地创建多个Jedis实例.这样,您就可以克服那些奇怪的错误并获得出色的性能.

! 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

推荐答案

单个Jedis实例不是线程安全的,因为它是通过这种方式实现的.那是图书馆作者做出的决定.

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

您可以签入BindisJedis的源代码,它是Jedis的超级类型

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

例如这些行:

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

您可以看到,使用Jedis实例为所有线程共享了交易字段,并在此方法中对其进行了初始化.以后,可以在其他方法中使用此事务.想象两个线程同时执行事务性操作.结果可能是一个线程创建的事务被另一线程无意访问.在这种情况下,事务字段是不同步的共享状态访问.这使Jedis成为非线程安全的.

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.

作者之所以决定使Jedis为非线程安全的和JedisPool为线程安全的,可能是为了为客户端提供灵活性,这样,如果您具有单线程环境,则可以使用Jedis并获得更好的性能,或者如果您具有多线程环境,您可以使用JedisPool并获得线程安全.

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.

这篇关于为什么单个Jedis实例不是线程安全的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆