OiRc
OiRc

Reputation: 1622

return a syncrhonized value from a syncrhonized block

if i have a map of objects and each threads can go inside each buckets concurrently,resulting a block like

syncrhonized(values.get(ObjectToLock)){
    int sum = 0;
    for(int i = 0; i< new Random().nextInt(1000)+2; i++)
    sum+=i;
    return sum;
}

UPDATE

 syncrhonized(values.get(ObjectToLock)){
        int sum = 0;
        for(int i = 0; i< new Random().nextInt(1000)+2; i++)
        sum+=i;
        for(int i = 0; i < 10; i++)
         for( int j = 0; j < 10 ; j++)
            System.out.println(*);
        return sum;
    }

in this piece of code, each thread can interfere between them resulting in a sum distorted?

Upvotes: 0

Views: 36

Answers (1)

Sotirios Delimanolis
Sotirios Delimanolis

Reputation: 280102

No, sum is a local variable. Each thread will have its own copy.

Declaring it outside of the synchronized block doesn't make it any less of a local variable, it just makes its scope larger.

Upvotes: 1

Related Questions