暂无图片
暂无图片
暂无图片
暂无图片
暂无图片

Guarded Suspension 设计模式

Alleria Windrunner 2020-05-25
480

什么是 Guarded Suspension 设计模式

Suspension 是“挂起”、“暂停”的意思,而 Guarded 则是“担保”的意思,连在一起就是确保挂起。当线程在访问某个对象时,发现条件不满足,就暂时挂起等待条件满足时再次访问,这一点和 Balking 设计模式刚好相反(Balking 在遇到条件不满足时会放弃)。
Guarded Suspension 设计模式是很多设计模式的基础,比如生产者消费者模式,Worker Thread 设计模式,等等,同样在 Java 并发包中的 BlockingQueue 中也大量使用到了 Guarded Suspension 设计模式。


Guarded Suspension 的示例

我们来看一个比较简单的示例,在学习生产者消费者模式以及 BooleanLock 时都曾写过类似的代码,代码如下所示。
    public class GuardedSuspensionQueue
    {
    //定义存放 Integer 类型的 queue
    private final LinkedList<Integer> queue = new LinkedList<>();


    //定义 queue 的最大容量为100
    private final int LIMIT = 100;


    //往 queue 中插入数据,如果 queue 中的元素超过了最大容量,则会陷入阻塞
    public void offer(Integer data) throws InterruptedException
    {
    synchronized (this)
    {
    //判断 queue 的当前元素是否超过了 LIMIT
    while (queue.size() >= LIMIT)
    {
    //挂起当前线程,使其陷入阻塞
    this.wait();
    }
    //插入元素并且唤醒 take 线程
    queue.addLast(data);
    this.notifyAll();
    }
    }


    //从队列中获取元素,如果队列此时为空,则会使当前线程阻塞
    public Integer take() throws InterruptedException
    {
    synchronized (this)
    {
    //判断如果队列为空
    while (queue.isEmpty())
    {
    //则挂起当前线程
    this.wait();
    }
    //通知 offer 线程可以继续插入数据了
    this.notifyAll();
    return queue.removeFirst();
    }
    }
    }
    在 GuardedSuspensionQueue 中,我们需要保证线程安全的是 queue,分别在 take 和 offer 方法中对应的临界值是 queue 为空和 queue 的数量>=100,当 queue 中的数据已经满时,如果有线程调用 offer 方法则会被挂起(Suspension),同样,当 queue 没有数据的时候,调用 take 方法也会被挂起。
    Guarded Suspension 模式是一个非常基础的设计模式,它主要关注的是当某个条件(临界值)不满足时将操作的线程正确地挂起,以防止出现数据不一致或者操作超过临界值的控制范围。
    文章转载自Alleria Windrunner,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。

    评论