从不拥有它的线程中释放锁,还是重新设计以避免这种情况? [英] Unlocking a lock from a thread which doesn't own it, or redesigning to avoid this?

查看:72
本文介绍了从不拥有它的线程中释放锁,还是重新设计以避免这种情况?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个归档对象,该对象管理各种字节数组并分发 OutputStream 用于读取和写入它们.每个字节数组都有一个关联的 .

I have an archive object which manages various byte arrays and hands out InputStreams and OutputStreams for reading and writing them. Each byte array has an associated ReentrantReadWriteLock.

档案生成的InputStream子类的构造函数获取相关数据的锁,而close()释放该锁.现在,问题所在:

The constructor of the subclass of InputStream which the archive produces acquires the lock for the relevant data, while close() releases the lock. Now, the problem:

假设我有一个任务将在需要从归档文件输入的另一个线程上运行,在启动前给它InputStream作为参数,并负责在完成流后关闭该流.这些要求似乎与我的数据档案所使用的锁定机制不兼容,因为

Suppose that I have a task which will run on another thread which needs input from the archive, is given the InputStream as an argument before it starts, and is responsible for closing the stream when it's finished. These requirements appear to be incompatible with the locking mechanism used by my data archive, because

  1. InputStream是在与关闭它的线程不同的线程上创建的.
  2. ReentrantReadWriteLock必须由拥有它的线程释放.
  1. The InputStream is created on a different thread from the one on which it is closed.
  2. A ReentrantReadWriteLock must be released by the thread which owns it.

为了避免#1重写期望将InputStream作为输入的程序部分,这会带来不便,并且使这些部分的灵活性降低.使用一种可以改变所有权的锁可以避免#2的发生,但是我看不到Java API中可以处理此锁的任何锁,如果我不愿意,我也不会非常希望将定制锁组合在一起不必.

Rewriting the parts of the program which expect an InputStream as input in order to avoid #1 is inconvenient and makes those parts less flexible. Using a kind of lock which permits change of ownership would let me avoid #2, but I don't see any locks in the Java API which can handle that and I'm not terribly keen on knocking together a custom lock if I don't have to.

对此问题有什么解决方案?

What solutions are there to this problem?

推荐答案

最干净的方法是为客户端提供除InputStream子类之外的其他内容,即使这意味着稍微多一点的重构也是如此.在您当前的设计中,您不能指望客户端释放锁,如果其中一个没有释放怎么办?这不是很好的封装.

The cleanest way to do this is to give the clients something other than a subclass of InputStream, even if this means slightly more refactoring. In your current design, you can't count on your clients releasing the lock, what if one of them does not? This is not good encapsulation.

让存档对象管理锁,并为您的客户端提供一个简单的API来获取数据.即使这意味着更改某些API.

Have the archive object manage the locks, and provide an easy API for your clients to get the data. Even if this means changing some APIs.

不同线程锁定和释放同一对象的问题清楚地表明,您在当前设计中有一些错误.进行上述重构工作,将为您做很多进一步的工作.

The problem of different threads locking and releasing the same object is a clear sign that you got something slightly wrong in your current design. Work on the refactoring aforementioned, it will do you a great deal further on.

这篇关于从不拥有它的线程中释放锁,还是重新设计以避免这种情况?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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