簡體   English   中英

記憶計算的這種實現是否正確?

[英]Is this implementation of memoized computation correct?

我需要為計算備忘錄實現一個簡單的通用包裝,並能夠按需重置備忘錄的值。 計算可能會長時間運行,因此reset不應阻塞太長時間-理想情況下,它只是將當前狀態標記為“臟”並返回。

這是我所做的:

import java.util.concurrent.Callable;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class CachedValue<A> {
    private Callable<A> creator;
    private Lock computationLock = new ReentrantLock();
    private Lock resultLock = new ReentrantLock();
    private volatile A cached = null;
    private volatile boolean wasCleared = false;

    public CachedValue(Callable<A> creator) {
        this.creator = creator;
    }

    public A get() {
        if (cached != null) {
            return cached;
        } else {
            computationLock.lock();
            try {
                if (cached != null) {
                    return cached;
                } else {
                    while (true) {
                        wasCleared = false;
                        A computed = creator.call();
                        resultLock.lock();
                        try {
                            if (!wasCleared) {
                                cached = computed;
                                return cached;
                            }
                        } finally {
                            resultLock.unlock();
                        }
                    }
                }
            } finally {
                computationLock.unlock();
            }
        }
    }

    public void reset() {
        resultLock.lock();
        try {
            cached = null;
            wasCleared = true;
        } finally {
            resultLock.unlock();
        }
    }
}

它似乎可行,但是我對並行編程沒什么期望,所以我也許錯過了一些死鎖或效率問題?

您必須保護已cachedwasCleared變量,因為可以使用一個線程的reset方法將其重置,而從另一個線程調用的get方法將對相同的變量集起作用,從而reset它們。

您可以在重置方法中使用與以下相同的可重入鎖:

public void reset() {
    lock.lock();
    try {
        cached = null;
        wasCleared = true;
    } finally {
         lock.unlock();
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM