您正在以比执行更快的速度发出异步插入,因此它们最终会超过队列大小并失败。您可以增加队列大小,这会起作用,但之后您只会对内存施加背压,而不是对生产者施加背压,并且仍然可能遇到问题。尝试限制飞行中的查询,如:
public static void main2(String[] args) {
FileReader fr = null;
int permits = 256;
Semaphore l = new Semaphore(permits);
try {
fr = new FileReader("the-file-name.txt");
BufferedReader br = new BufferedReader(fr);
String sCurrentLine;
long time1 = System.currentTimeMillis();
while ((sCurrentLine = br.readLine()) != null) {
l.acquire();
session.executeAsync(sCurrentLine)
.addListener(()->l.release(), MoreExecutors.directExecutor());
}
l.acquire(permits);
System.out.println(System.currentTimeMillis() - time1);
fr.close();
br.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
它可能会运行得同样快,只需要找到合适大小的信号量。还要注意阻塞,直到所有许可都返回为止(在末尾获取max),否则您可以在发送所有可能在队列中的请求之前关闭jvm。
免责声明:我没有测试上述代码