简体   繁体   中英

Inaccessible variable declared in synchronized block - Java

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?

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.)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM