有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java ConcurrentLinkedQueue是否定期清空?

我的类中有一个ConcurrentLinkedQueue字段,在使用JUnit在Eclipse中运行简单的单线程测试时,我的行为非常不稳定

我的班级:

public class ArchiverData
{
/** The pricing API records */
private ConcurrentLinkedQueue<ArchiverApiResponseDTO> pricingQueue =
        new ConcurrentLinkedQueue<ArchiverApiResponseDTO>();
[...]
public int getApiResponseCount()
{
    return pricingQueue.size();
}

public void addApiResponseDTO(ArchiverApiResponseDTO dto)
{
    pricingQueue.add(dto);
}

public ArchiverApiResponseDTO pollApiResponseDTO()
{
    return pricingQueue.poll();
}
[...]
}

我的测试:

public class ArchiverDataTest {
@Test
public void test() {
    ArchiverData archiverData = new ArchiverData();
    ArchiverApiResponseDTO dto = new ArchiverApiResponseDTO([...]);
    archiverData.addApiResponseDTO(dto);
    archiverData.addApiResponseDTO(dto);
    System.out.println(":" + archiverData.getApiResponseCount());
}
}

正如您所看到的,在测试用例中没有其他任何东西在运行。ArchiverApiResponseDTO对象是一组简单的字段

我的结果:

  • 运行测试::2(这很好)
  • IDE中的逐步调试::0archiverData.pricingQueue对象看起来总是空的
  • 第二次addApiResponseDTO调用上的断点:archiverData.pricingQueue空;然后运行::1
  • sysoutarchiverData.pricingQueue上的断点为空,然后运行::0

值得注意的是,每次都有一位同事尝试了同样的方法并得到了正确的结果(:2)!我在同一时间没有别的东西在跑。在给定的时间内,似乎有什么东西正在清空我的队列。到底发生了什么事


共 (1) 个答案

  1. # 1 楼答案

    我现在最好的猜测是,您在pollApiResponseDTO()或poll()上有一个手表,实际上是您的调试器清空了队列