ArrayBlockingQueue:应该使用来创建Pool吗?
我正在尝试创建一个 Pool
对象来保留旧对象,以便再次使用它们(以避免实例化新对象)。我在谷歌上搜索了ArrayBlockingQueue
,有些人用它来创建Pool
。但有一个问题我不知道:当对象插入其中时,它是否会重新创建一个新实例。
例如:ArrayBlockingQueue
短时间后: pool = (3,4,5);
pool.take(5); ==> pool = (3,4);
pool.put(6); ==>pool = (6,3,4);
所以,我想知道 6 是否分配给旧的 Integer 对象(与值 5),还是 Java 创建一个新值并将其值指定为 6?
谢谢 :)
I'm trying to create a Pool
object to reserve old objects in case of use them again (to avoid instantiation of new objects). I google that ArrayBlockingQueue
and some people use it to create Pool
. But there is one question I don't know: does it recreate a new instance when an object insert to it.
For example: ArrayBlockingQueue<Integer> pool = new ArrayBlockingQueue<Integer>(3);
after short time: pool = (3,4,5);
pool.take(5); ==> pool = (3,4);
pool.put(6); ==>pool = (6,3,4);
So, I wonder is 6 assigned to the old Integer object (with value 5), or does Java create a new one and assign it's value as 6?
thanks :)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

发布评论
评论(4)
我严重怀疑在这种情况下任何值的替换都是真实的。此外,我不确定此类对象池的自定义实现是否有用,除非您的代码生成并丢弃了大量对象。
更有趣的是,您在问题中没有提及任何有关线程安全或多线程的内容,但您使用了这些标签。您到底想通过这样一个池实现什么目标? ArrayBlockingQueue 旨在作为一种线程安全的集合,其中一个(或多个)线程转储对象,同时一个(或多个)线程删除对象。有很多方法可以提供不同的行为,以防队列中需要对象但没有对象,或者添加对象但队列中没有容量。您应该查看 javadoc 看看它是否真的是你想要的 ArrayBlockingQueue 。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
ArrayBlockingQueue
由参数类型的数组支持。所以在内部它看起来像这样:并在您的情况下实例化为
根据 源码,
put
方法实际上调用了这个insert
方法:那么当你调用
时会发生什么>pool.put(6)
是int
6 被装箱到Integer
对象中并传递给该方法(因为E
现在是Integer
)。因此可以肯定地说,它确实创建了Integer
的新实例。The
ArrayBlockingQueue
is backed by an array of the parameter type. So internally it would look something like this:and instantiated in your case as
According to the source code of
ArrayBlockingQueue
, theput
method actually calls thisinsert
method:So what happens when you call
pool.put(6)
is that theint
6 is boxed into anInteger
object and passed to the method (sinceE
is nowInteger
). So it's safe to say that indeed it does create a new instance ofInteger
.