Home >Java >javaTutorial >Introduction to thread safety implementation ideas in Java

Introduction to thread safety implementation ideas in Java

WBOY
WBOYforward
2023-07-01 14:54:16977browse


In Java multi-threaded programming, thread safety is a very important concept. A program that maintains correct behavior when multiple threads execute concurrently is said to be thread-safe. In this article, we will introduce several common implementation ideas that can ensure thread safety in Java.

Introduction to thread safety implementation ideas in Java

1. Use the synchronized keyword

The synchronized keyword is the most basic way to solve thread safety problems in Java. It can ensure that code blocks are atomically way to execute. The synchronized keyword can be used to modify instance methods, static methods, and code blocks. This is an instance method sample code, modified using synchronized

public class Counter {
    private int count;
    public synchronized void increment() {
        count++;
    }
    public synchronized int getCount() {
        return count;
    }
}

In the above code, the increment() and getCount() methods are modified by synchronized, which ensures that only one thread can access them at a time . Although this approach is simple, it is relatively inefficient because only one thread is allowed to access these methods at a time.

2. Use the ReentrantLock class

The ReentrantLock class in Java provides a more flexible thread synchronization mechanism than synchronized. ReentrantLock is reentrant, can interrupt threads waiting for the lock, and can try to acquire the lock through the tryLock() method. This is a sample code for achieving thread safety by using ReentrantLock:

import java.util.concurrent.locks.ReentrantLock;
public class Counter {
    private int count;
    private ReentrantLock lock = new ReentrantLock();
    public void increment() {
        lock.lock();
        try {
            count++;
        } finally {
            lock.unlock();
        }
    }
    public int getCount() {
        lock.lock();
        try {
            return count;
        } finally {
            lock.unlock();
        }
    }
}

In the above code, the lock is acquired by calling the lock.lock() method and the lock is released by calling the lock.unlock() method. What needs to be noted when using ReentrantLock is that the logic of acquiring and releasing the lock must be placed in a try-finally block to ensure that the lock can be released correctly.

3. Use the ConcurrentHashMap class

In Java, ConcurrentHashMap is an implementation of a thread-safe hash table. ConcurrentHashMap uses a segment lock mechanism to divide the entire hash table into multiple segments. Elements in different segments can be accessed by multiple threads at the same time. The following is a sample code that uses ConcurrentHashMap to achieve thread safety:

import java.util.concurrent.ConcurrentHashMap;
public class Counter {
    private ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<>();
    public void increment(String key) {
        map.put(key, map.getOrDefault(key, 0) + 1);
    }
    public int getCount(String key) {
        return map.getOrDefault(key, 0);
    }
}

In the above code, ConcurrentHashMap is used to store the value of the counter, and the map.put() and map.getOrDefault() methods are used to update and obtain the counter's value. value. Since ConcurrentHashMap is thread-safe, this implementation ensures that the counter value is correct when multiple threads access it at the same time.

4. Use the Atomic class

In Java, the Atomic class provides a series of atomic operations to ensure that the operations are performed in an atomic manner. Atomic classes include AtomicBoolean, AtomicInteger, AtomicLong, etc. The following is a sample code that demonstrates the use of AtomicInteger to achieve thread safety:

import java.util.concurrent.atomic.AtomicInteger;
public class Counter {
    private AtomicInteger count = new AtomicInteger();
    public void increment() {
        count.incrementAndGet();
    }
    public int getCount() {
        return count.get();
    }
}

In the above code, use AtomicInteger to store the value of the counter, and use the count.incrementAndGet() method to update the value of the counter. Since AtomicInteger is thread-safe, this implementation ensures that the counter value is correct when multiple threads access it at the same time.

5. Use the ThreadLocal class

The ThreadLocal class allows each thread to have its own copy of variables. When multiple threads execute concurrently, each thread can independently operate its own copy of variables. , thus avoiding thread safety issues. The following is a sample code that uses ThreadLocal to achieve thread safety:

public class Counter {
    private ThreadLocal<Integer> threadLocal = ThreadLocal.withInitial(() -> 0);
    public void increment() {
        threadLocal.set(threadLocal.get() + 1);
    }
    public int getCount() {
        return threadLocal.get();
    }
}

In the above code, the ThreadLocal class is used to store the value of the counter, and the threadLocal.set() and threadLocal.get() methods are used to update and obtain the counter value. . Set each thread to have an independent copy of the variable to ensure that the counter value is accurate when multiple threads access it at the same time.

Summary

This article introduces several methods to achieve thread safety in Java, including the synchronized keyword, ReentrantLock class, ConcurrentHashMap class, Atomic class, ThreadLocal class, etc. According to actual needs, you need to choose a suitable method. Each method has its own characteristics and applicable scenarios. To optimize system performance and concurrency, thread safety can be achieved by combining multiple methods.

The above is the detailed content of Introduction to thread safety implementation ideas in Java. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete