Examples of Java concurrent programming variables

  • 2020-04-01 03:49:14
  • OfStack

Writing thread safety needs to be concerned with:

1. Shared variables
2. Variable variables

Sharing means that multiple threads can be accessed at the same time, and mutable means that its value can change over the life cycle.
For example, the following count variable:


//Thread-unsafe class
public class UnsafeCount {
    private int count = 0;    //This variable is the Shared
    public void increase() {    //There is no synchronization and multiple threads can access
at the same time         count++;    //The variable is variable
    }
    public int getCount() {
        return count;
    }
}

There are 4 ways to fix this problem:

1. If the state variable is not Shared in a thread, it can be encapsulated into a method (stateless objects must be thread-safe); Because variables in a method are exclusive to each thread, they are not Shared with other threads. Such as:


public int add(int count){
return ++count;//It can also be said that stateless objects must be thread-safe
}

2. Change the state variable to an immutable variable.

private final  int count = 0;

3. Use a synchronization policy when accessing state variables.

public synchronized  void increase() {
count++;
}

4. Use atomic variable classes.

 private AtomicInteger count;
 public void increase() {
  count.getAndAdd(1);
 }


Related articles: