So I am using a fixed sized BlockingQueue [ArrayBlockingQueue] in a producer/consumer type application, but I want the user to be able to change the queue size on the fly. Problem is there is not a BlockingQueue implementation that allows changing capacity after creation. Anyone ever come across this before? Any ideas?
Asked
Active
Viewed 5,315 times
2 Answers
2
The most obvious solution (may or may not be appropriate depending on your circumstances) would be to simply instantiate a new queue with the updated capacity you want. Then push everything from the old queue into the new queue.

Dan Tao
- 125,917
- 54
- 300
- 447
-
3If you do that, then all threads with a reference to the old queue will be blocked waiting for new contents on the old queue rather than new contents on the new queue. – Brett Kail Jul 06 '11 at 17:54
-
3@bkail: That's why I said "depending on your circumstances." If the OP has numerous references to the blocking queue, then he'll need to refactor to make this solution work (e.g., by wrapping the queue itself within a container object that acts as a queue externally but performs new allocations internally when the capacity is changed). – Dan Tao Jul 06 '11 at 17:57
1
You could extend LinkedBlockingQueue. Its limit is is a soft limit (i.e. just an additional check) and you could make this something you can change (by disabling the built in one and putting in your own)

Peter Lawrey
- 525,659
- 79
- 751
- 1,130
-
This is not possible without copy/pasting a lot of the internal code. You'd really have to take a chainsaw to a separate implementation, e.g., the one in Apache Harmony. – jbellis Sep 06 '13 at 21:47
-
3You can't get the desired functionality here by subclassing; too much is final/private. – jbellis Sep 18 '13 at 15:45
-
i have to agree with @jbellis, subclassing the `LinkedBlockingQueue` is highly impractical in this case. – thrau Dec 28 '13 at 19:54
-
@thrau You just need to override `offer()` and `put()` and these are not final. – Peter Lawrey Dec 28 '13 at 21:00
-
2All access and manipulation functions of the queue interface implementation in `LinkedBlockingQueue` use the `private final int capacity` field, also, the entire locking mechanism is held in private functions and would have to be re-implemented. You'd basically be re-writing most of the class. – thrau Dec 28 '13 at 21:53
-
@thrau I don't see why this is a problem. You would add a field you can access and perform the check before adding. You don't need access to the locks. There is a small risk you could exceed the capacity, but this would be momentary. – Peter Lawrey Dec 29 '13 at 08:46
-
You absolutely need access to the locks if you're going to preserve correctness wrt all the other methods you don't override. I don't think you've actually taken a serious look at this. – jbellis Jan 01 '14 at 22:59