未处理的Java BlockingQueue消息未完整处理

时间:2016-03-20 21:26:10

标签: java multithreading blockingqueue

我正在尝试处理来自文本文件的几百万条记录(即,使用一个线程顺序读取文件,并尝试使用多个线程处理检索到的行)。 ' queue.take();'之后的方法调用只执行等于分配给BlockingQueue的初始容量的次数(在本例中为100),然后该过程不再拾取记录。

您能帮忙调试或发现问题吗?

Main Method:
############
final int threadCount = 10;
BlockingQueue<String> queue = new ArrayBlockingQueue<String>(100);
ExecutorService service = Executors.newFixedThreadPool(threadCount);

for (int i = 0; i < (threadCount - 1); i++) {
    service.submit(new EvaluateLine(queue));
}
service.submit(new ProcessFile(queue)).get();
service.shutdownNow();
service.awaitTermination(365, TimeUnit.DAYS);


EvaluateLine:
#############
private final BlockingQueue<String> queue;

public EvaluateLine(BlockingQueue<String> queue){
    this.queue = queue;
}

@Override
public void run() {
    String line;
    while(true) {
        try {
            line = queue.take();
            SyncOutput.Process(line);
        } catch (InterruptedException ex) {
            break;
        }
    }
}

ProcessFile:
############
private final BlockingQueue<String> queue;

public ProcessFile(BlockingQueue<String> queue) {
    this.queue = queue;
}

@Override
public void run() {
    Path path = Paths.get("C:\\Desktop\\testdata.txt");
    BufferedReader br = null;

    try {
        br =Files.newBufferedReader(path, StandardCharsets.UTF_8);
        for (String line; (line = br.readLine()) != null; ) {
            queue.put(line);
        }
    } catch(IOException e){
        e.printStackTrace();
    } catch(InterruptedException e){
        e.printStackTrace();
    } finally{
        try {
            if (br != null) br.close();
        }catch(IOException e){
            e.printStackTrace();
        }
    }

编辑:

 SyncOutput
 ##########
 class SyncOutput{
    public static void ProcessExpression(String inputLine) {
        evalExpression(inputLine);
    }
    public static double evalExpression(String s){
        Expression e = new ExpressionBuilder(s)
                       .build();
        return e.evaluate();
    }
 }

1 个答案:

答案 0 :(得分:0)

以下代码段(使用Expression评估库:exp4j)阻止了多线程执行,不确定原因。但我用不同的库(parsii)替换了这个代码块,现在一切都很好。

public static void ProcessExpression(String inputLine) {
    evalExpression(inputLine);
}
public static double evalExpression(String s){
    Expression e = new ExpressionBuilder(s)
                   .build();
    return e.evaluate();
}