与条件同步工作?如何使此代码具有高性能和线程安全性? [英] Synchronization work with conditionals? How can I make this code performant and thread safe?

查看:23
本文介绍了与条件同步工作?如何使此代码具有高性能和线程安全性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定以下代码:

public class SomeClass {

  private boolean shouldBlock = false;
  private Object resource;

  public void handleDrawRequest(Canvas canvas) {
    if (!shouldBlock && resource == null)
    {
       shouldBlock = true;
       loadTheResource();  //which takes awhile
       shouldBlock = false;
    }
    else if (shouldBlock && resrouce == null)
    {
       return;  //another thread is taking care of the loading of the resource
                //and its not ready yet, so just ignore this request
    }

    drawResourceOn(canvas);
  }
}

我怎样才能使这段代码线程安全?我想要完成的是让一个且只有一个线程加载资源,而同时尝试访问此代码的任何其他线程都将被丢弃(例如,遵循else if"逻辑),直到加载资源.可能有许多线程试图同时访问此代码,我不想同步整个方法并堆积一整堆线程.

How can I make this code thread safe? What I'm trying to accomplish is for one and only one thread to load the resource while any other thread attempting access this code at the same time to be discarded (e.g. follow the 'else if' logic) until the resource is loaded. There could be many threads trying to access this code at the same time and I don't want to synchronize the entire method and have a whole stack of threads pile up.

推荐答案

您正在寻找 AtomicBoolean

public class SomeClass {
  // AtomicBolean defaults to the value false.
  private AtomicBoolean loadingResource = new AtomicBoolean();
  private volatile Object resource;

  public void handleDrawRequest(Canvas canvas) {
    if (resource == null) {
      if (loadingResource.compareAndSet(false, true)) {
        loadTheResource();  //which takes awhile
      } else {
        //another thread is taking care of the loading of the resource
        //and its not ready yet, so just ignore this request
        return;  
      }
    } else {
      drawResourceOn(canvas);
    }
  }
}

这篇关于与条件同步工作?如何使此代码具有高性能和线程安全性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆