0

This is not a question about method synchronisation, only to statement synchronisation. Please do not incorrectly mark as duplicate.

Is this code:

synchronized (this) if (something)
{
    somecode();
    somemorecode();
}

equivalent to this code:

if (something)
{
    synchronized (this)
    {
        somecode();
        somemorecode();
    }
}
Cœur
  • 37,241
  • 25
  • 195
  • 267
Steve Waring
  • 2,882
  • 2
  • 32
  • 37
  • 2
    My IDE tells me that your first form (once typos corrected) is not valid syntax - `synchronized` requires a block I think: a single statement is not allowed. `synchronized (this) { if (something) { ... } }` is valid (braces added) and it is now clear that the `if` is in the sync block, rather than attaching a condition to it - i.e. Java is not Ruby! – Paul May 21 '15 at 10:47
  • 3
    Even if it's valid, don't ever do it. Just don't. Please. – biziclop May 21 '15 at 10:47
  • So does mine, I had not noticed the tiny red squiggle. And yes, I was bringing the question with me from another languqage. – Steve Waring May 21 '15 at 10:51
  • @Paul: Not just your IDE, the JLS requires it. Nice catch! I've updated my answer to say that. – T.J. Crowder May 21 '15 at 10:52

1 Answers1

2

Is this code...equivalent to this code

No, it isn't. In your first example, the if test is might be inside the synchronized section. In your second example, the if is outside the synchronized section.

This is a syntax error:

synchronized (this) if (something)
{
    somecode();
    somemorecode();
}

synchronized requires a block, per JLS§14.19:

SynchronizedStatement:
synchronized ( Expression ) Block

If it were valid, it would probably be equivalent to:

synchronized (this)
{
    if (something)
    {
        somecode();
        somemorecode();
    }
}

...but that's pure speculation; if it's not defined by the JLS, who knows what it would be. :-)


Side note: It's synchronized, not syncronized or syncronised.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875