Is it wise to sync a local variable?

From the java memory model, we know that each thread has its own thread stack, and local variables are placed in each thread's thread of its own threads.

And other threads cannot access these local variables.

So, in this case, should we synchronize the local variables?

+4
source share
4 answers

There are two situations:

  • A local variable has a primitive type of type intor double.
  • A local variable has a reference type type ArrayList

, ( )

, . , (), , .

: static , .

, , , , , .

+8

:

public class MyClass {
    public void myMethod() {
        //Assume Customer is a Class
        Customer customer = getMyCustomer();
        synchronized(customer) {
            //only one therad at a time can access customer object
              which ever holds the lock
        }
    }
}

customer , customer ( ).

Java ( , ), - .

, , (-), , , , . - , therad .

+8

, . , .

: , . , , -, .

, : , , .

, , "" . , :

void foo() {
  final Object lock = new Object();
  Thread a = new Thread() { uses lock
  Thread b = new Thread() { uses lock

, "" . : , . . .

+4

Yes, it makes sense when a local variable is used to synchronize access to a block of code from threads that are defined and created by the same method as the local variable.

+2
source

Source: https://habr.com/ru/post/1673686/


All Articles