java - 在 Java 中如何更改 ArrayBlockedQueue 的长度?

标签 java android concurrency

我正在为 Android 创建一个媒体播放器应用程序。我有两个线程:一个生成音频帧,另一个消耗这些帧。

我希望我的客户能够尝试使用不同大小的 ArrayBlockedQueue,从“无”缓冲(实际上是 1)到最多 10 个缓冲 block 。

我似乎在 Java 中找不到任何提供与 ArrayBlockedQueue 类似功能的类,但允许我动态地使项目列表更长/更短。

问题 1)有谁知道有一个类,其功能类似于 ArrayBlockedQueue,但允许我更改要保存的项目数量?

然后我有一个奇怪的想法:我能捏造它吗?我可以创建一个具有新大小的新 ArrayBlockedQueue,然后逐步复制旧 ArrayBlockedQueue 中当前的 1-10 个项目并将它们放入新的 ArrayBlockedQueue 中,然后将指向新 ArrayBlockedQueue 的指针存储在旧的 ArrayBlockedQueue 上吗?/p>

由于永远不会超过 10 个(或无论我的缓冲区限制是多少),因此将项目复制到新数组不会花费太多时间。

问题 2)这是一种“合理”的方法来实现 ArrayBlockedQueue 实现,并且仍然给我带来灵 active 吗?

问题3)有更好的方法来解决这个问题吗?

-肯

最佳答案

您可能需要创建自己的 BlockingQueue 实现来包装旧队列和新队列 - 从旧队列进行轮询,直到它为空,然后将其设置为 null 以防止任何内存泄漏。这样您就不会丢失旧队列上任何待处理的 put

MyBlockingQueue {
  private MyBlockingQueue oldQueue
  private ArrayBlockingQueue newQueue

  ArrayBlockingQueue(int newCapacity, MyBlockingQueue _oldQueue) {
    oldQueue = _oldQueue
    newQueue = new ArrayBlockingQueue(newCapacity)
    E oldVal = null
    while(newQueue.remainingCapacity() > 0 && 
         (oldVal = oldPoll) != null)
      newQueue.put(oldVal)
  }

  boolean isEmpty() {
    (oldQueue == null || oldQueue.isEmpty) && newQueue.isEmpty 
  }

  void put(E e) {
    newQueue.put(e)
  }

  E take() {
    E oldVal = oldPoll
    if(oldVal != null) oldVal else newQueue.take
  }

  E poll() {
    E oldVal = oldPoll
    if(oldVal != null) oldVal else newQueue.poll
  }

  private E oldPoll() {
    // If you have more than one consumer thread, then use a temporary variable
    // for oldQueue - otherwise it might be set to null between the null check
    // and the call to poll
    if(oldQueue == null) null
    else {
      E oldVal = oldQueue.poll
      if(oldVal != null) oldVal
      else {
        oldQueue = null
        null
      }
    }
  }
}

关于java - 在 Java 中如何更改 ArrayBlockedQueue 的长度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25249480/

相关文章:

java - 使用 JDBC Java 字符串,在 PHP 中连接到 mysql 数据库

Java:控制台跳过输入

java - 如何使用 Java Tree Compiler API 查找标识符的类型声明?

android - Android Application Context 会被破坏吗?

Android如何重新启动我的应用程序以前运行的 Activity

android - 如何创建具有自定义 ID 值的微调器?

python - Python shelve.open 上的资源暂时不可用

java - 是否有使用当前线程的 ExecutorService?

并发模式帮助 - 扇入并返回结果?

java - Android-RxJava : Update UI from background thread using observable