java 内存可见性问题

问题描述:同一个对象,在多线程中进行操作,会出现内存可见性问题。

java 内存可见性问题_第1张图片

java 内存可见性问题_第2张图片

针对这种问题,我们做了一些应对措施

1. 加volatile, 结果发现没有效果

2. 加lock

修改代码如下:

package feedback.common.lock;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 所对象
 * Created by sff on 2018/5/8.
 */
public class FeedBackLock {
    private Lock lock = new ReentrantLock();
    private Condition done = lock.newCondition();
    private volatile AtomicBoolean finished = new AtomicBoolean(false);
    private volatile boolean success;
    private volatile Exception cause;

    public FeedBackLock(){
        success = false;
    }

    public void lock(long timeout) throws InterruptedException{
        lock.lock();
        try{
            if(!finished.get()){
                // 时间一到直接就过去了,不会抛异常的。
                done.await(timeout, TimeUnit.MILLISECONDS);
            }
        } catch (InterruptedException e) {
            throw e;
        } finally {
            lock.unlock();
        }
    }

    public void unLock() {
        lock.lock();
        try{
            this.success = cause == null;
            // 时间一到直接就过去了,不会抛异常的。
            done.signal();
            finished.set(true);
        } finally {
            lock.unlock();
        }
    }

    public boolean isSuccess() {
        lock.lock();
        try {
            return success;
        } finally {
            lock.unlock();
        }
    }

    public Exception getCause() {
        lock.lock();
        try {
            return cause != null ? cause : new TimeoutException("feedback timeout");
        } finally {
            lock.unlock();
        }
    }

    public void setCause(Exception cause) {
        this.cause = cause;
    }
}
 发现成功了。不会出现之前的那个问题。

你可能感兴趣的:(java)