简体   繁体   中英

ArrayBlockingQueue: should use to create Pool?

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 :)

See you shouldn't worry about the underlying implementation, that is what is intended in java by "encapsulation". According to the Oracle docs, "put" actually "inserts" the element at the tail. So there isn't any replacement of "old objects", i suppose.

The ArrayBlockingQueue is backed by an array of the parameter type. So internally it would look something like this:

E[] items;

and instantiated in your case as

Integer[] items;

According to the source code of ArrayBlockingQueue , the put method actually calls this insert method:

private void insert(E x) {
    items[putIndex] = x;
    putIndex = inc(putIndex);
    ++count;
    notEmpty.signal();
}

So what happens when you call pool.put(6) is that the int 6 is boxed into an Integer object and passed to the method (since E is now Integer ). So it's safe to say that indeed it does create a new instance of Integer .

I would seriously doubt that any replacing of values would be actual in this case. Furthermore, I am not sure having a custom implementation of such an object pool would be useful, unless your code generates and trashes an immense number of objects.

What's more interesting is that you do not mention anything about thread safety or multithreading in your question, but you have used these tags. What exactly is it that you want to achieve with such a pool? ArrayBlockingQueue is intended as a thread-safe collection where one (or many) threads dump in objects while one (or many) threads remove objects out. There are quite a few methods to supply different behaviors in case an objects is required from the queue but there is none, or when an objects is added but there is no capacity in the queue. You should check out the javadoc and see if it's really ArrayBlockingQueue you want.

The new object was created right here:

pool.put(6);

It's more obvious when you think what autoboxing is converting that to:

pool.put(new Integer(6));

The queue neither creates nor reuses these objects, it stores the ones you give it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM