Nat*_*ati 3 java multithreading thread-safety
我有一个关键代码,包裹在里面synchronized (this) {}.
在日志中,我看到线程#1进入临界区,然后线程#2到达那里,然后等待,然后,线程#1离开临界区,再次进入它(2ms之后)!甚至在其他线程进入之前.
这怎么可能 ?没有线程#2应该进入临界区?
编辑:
添加我班级的一部分......
@Service
public class RequestService {
Logger logger = LoggerFactory.getLogger(RequestService.class);
public HttpResponse executeRequest(HttpClient httpClient, HttpGet request) throws IOException, InterruptedException {
logger.info("About to enter critical code");
synchronized (this) {
logger.info("executing http request");
HttpResponse response = httpClient.execute(request);
logger.info("got http response");
return response;
}
}
}
Run Code Online (Sandbox Code Playgroud)
同步块不"公平".当可用时,无法保证哪个线程能够进入同步块.
如果你想引入公平,你可以使用ReentrantLock,
Lock lock = new ReentrantLock(true);
Run Code Online (Sandbox Code Playgroud)
等待进入临界区的线程将按照它们排队的顺序以"公平"的顺序输入.
默认的公平性策略是"不公平的",因为公平性带来了大多数应用程序不需要的性能开销.
| 归档时间: |
|
| 查看次数: |
89 次 |
| 最近记录: |