Reputation: 1032
I have a critical code, wrapped inside synchronized (this) {}
.
In the logs I see thread #1 enters critical section, then thread #2 reaches there, and waits, then, Thread #1 leaves critical section, and enters it again (2ms later) ! even before the other thread entered.
How is it possible ? didn't thread #2 should have entered the critical section ?
EDIT:
adding part of my class...
@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;
}
}
}
Upvotes: 3
Views: 128
Reputation: 53694
synchronized blocks are not "fair". There's no guarantee which thread will be able to enter a synchronized block when it becomes available.
Upvotes: 5
Reputation: 23329
You can use a ReentrantLock if you want to introduce fairness,
Lock lock = new ReentrantLock(true);
Threads waiting to enter the critical section will enter in a "fair" order, in the order they were queued.
The default fairness policy is "unfair" because fairness comes with a performance overhead that most applications don't need.
Upvotes: 5