Question

This piece of code will not compile:

    synchronized( obj ) {
        Object a = new Object()
    }

    System.out.println( a.toString() );

Yet I don't know why.. My understanding was that a synchronized block was always eventually executed, so I would expect code following the synchronized block to be aware of any new declared variables. Where am I wrong?

Was it helpful?

Solution

It's not the synchronization, it's the {} symbols. They define a scope, no matter whether there's an if, for, synchronized, or even nothing at the beginning of them. So the a goes out of scope once the block finishes, because it was declared within it. (Also there's a missing semicolon at the end of the Object a declaration but I suspect you just forgot to copy that.)

OTHER TIPS

Variable scope is not determined by what gets executed. Variables are visible only inside the block they are declared in. You probably want to do something like this:

Object a;
synchronized( obj ) {
    a = new Object()
}

System.out.println( a.toString() );

Variables defined inside a block don't live outside the block.

From the Java Language Specification:

The scope of a local variable declaration in a block (§14.2) is the rest of the block in which the declaration appears, starting with its own initializer (§14.4) and including any further declarators to the right in the local variable declaration statement.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top