最近在看okhttp源码的时候,有个语法点我想吐槽一下,先看代码,代码在RealCall.java中
void executeOn(ExecutorService executorService) {
1 assert (!Thread.holdsLock(client.dispatcher()));
boolean success = false;
try {
executorService.execute(this);
success = true;
} catch (RejectedExecutionException e) {
InterruptedIOException ioException = new InterruptedIOException("executor rejected");
ioException.initCause(e);
transmitter.noMoreExchanges(ioException);
responseCallback.onFailure(RealCall.this, ioException);
} finally {
if (!success) {
client.dispatcher().finished(this); // This call is no longer running!
}
}
}
1 处用了assert 这个关键字,工作这么些年,很少使用这个关键字,查了下这个关键字的资料,assert 在java 虚拟机中默认不开启,如果要开启那么添加虚拟机参数-ea,如图:
查找诸多资料后,一致认为这个关键字最多在测试环境或者调试程序的时候,基本不用做业务流程。所以纵然okhttp是非常优秀的框架,基本上开发App用到的网络请求框架都是它,但这里用assert确实不合适。有可能android 虚拟机没开启过这个开关。其实这里应该是throws exception更加合理。