Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java MultiThreading - One thread enters critical section twice before other thread

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;
        }
    }
}
like image 534
Nati Avatar asked Mar 06 '26 11:03

Nati


1 Answers

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.

like image 176
Sleiman Jneidi Avatar answered Mar 08 '26 01:03

Sleiman Jneidi