Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java synchronized method with expensive parameters

I have a synchronized method that appears to be 'using' the synchronization for significantly longer than it should. It looks something like;

public static synchronized void myMethod(MyParameter p) {
    //body (not expensive)
}

The call looks like;

myMethod(generateParameter());

Where generateParameter() is known to be a very expensive (takes a long time) call. My thinking is that the mutex on the myMethod class is blocked during the execution of generateParameter() is this what happens? I'm finding it a different problem to debug but this is what appears to be going on.

like image 566
lynks Avatar asked Nov 29 '13 14:11

lynks


2 Answers

That can't be it; the generateParameter() call is executed first, and its results are then given as an argument to the myMethod call, which then grabs the mutex.

Is it taking long, or is it indefinitely blocked? (a deadlock)

like image 144
Miquel Avatar answered Sep 30 '22 19:09

Miquel


No it is not what happens.

Method generateParameter is executed before call to myMethod.

In Java, all method arguments are always evaluated before method call.

The specification of method call explains it in detail (thanks to Victor Sorokin).

At run time, method invocation requires five steps. First, a target reference may be computed. Second, the argument expressions are evaluated. Third, the accessibility of the method to be invoked is checked. Fourth, the actual code for the method to be executed is located. Fifth, a new activation frame is created, synchronization is performed if necessary, and control is transferred to the method code.

Your code is the same as the one below, except of new variable:

MyParameter p = generateParameter();
myMethod(p);
like image 36
Grzegorz Żur Avatar answered Sep 30 '22 20:09

Grzegorz Żur