Home  >  Article  >  Java  >  How to implement double-checked locking in Java functions to achieve thread safety?

How to implement double-checked locking in Java functions to achieve thread safety?

WBOY
WBOYOriginal
2024-05-03 11:48:01935browse

Double check locking is a design pattern that ensures thread safety through double checking. It can be implemented in Java functions as follows: define a static volatile variable storage instance; if the instance is empty, check again in the synchronization block , if empty, create an instance; return the instance. Practical case: In scenarios where resources are shared (such as cache classes), double-check locking can ensure that all threads use the same shared instance, avoiding data competition and ensuring data integrity.

Java 函数中的双重检查加锁如何实现线程安全?

Double-checked locking in Java functions: a practical case for achieving thread safety

Double-checked locking is a design pattern , which uses double checking to ensure that an instance is only created once, thus achieving thread safety in multiple threads. The following is how to implement double-check locking in Java functions:

public class Singleton {
    private static volatile Singleton instance;

    private Singleton() {
        // ...省略构造函数逻辑
    }

    public static Singleton getInstance() {
        if (instance == null) {
            synchronized (Singleton.class) {
                if (instance == null) {
                    instance = new Singleton();
                }
            }
        }
        return instance;
    }
}

Practical case: Thread shared resources

Consider a scenario where threads share resources, such as a cache class , where multiple threads can access cached data simultaneously. To avoid data race conditions, we need to ensure that the cache object is only created once and that all threads can safely access it:

public class Cache {
    private static volatile Cache instance;

    public static Cache getInstance() {
        if (instance == null) {
            synchronized (Cache.class) {
                if (instance == null) {
                    instance = new Cache();
                }
            }
        }
        return instance;
    }

    // 此处省略缓存逻辑
}

// 使用缓存
List<String> sharedData = new ArrayList<>();
sharedData.add("Item 1");
sharedData.add("Item 2");

for (int i = 0; i < 10; i++) {
    new Thread(() -> {
        Cache cache = Cache.getInstance();
        // 使用共享数据,例如将它添加到缓存中
        cache.put("Key" + i, sharedData);
        cache.get("Key" + i);
    }).start();
}

In the above example, the Cache class uses double-checked locking , ensuring that all threads use the same shared instance. This avoids the creation of multiple cache instances, ensuring thread safety and data integrity.

The above is the detailed content of How to implement double-checked locking in Java functions to achieve thread safety?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn