首页 \ 问答 \ 处理多个线程使用的实例中的状态(Handling state in an instance that is used by multiple threads)

处理多个线程使用的实例中的状态(Handling state in an instance that is used by multiple threads)

让我们考虑遵循可变的Java类(取自Brian Goetz的“Java Concurrency in Practice”):

@ThreadSafe
public class SynchronizedInteger {
  @GuardedBy("this") private int value;

  public synchronized int get() { return value; }
  public synchronized void set(int value) { this.value = value; }
}

假设此类具有多个线程使用的单个实例,添加到类中的以下哪些方法不会破坏其线程安全性?

解决方案#1:

public boolean isPositive() { return value > 0; }

解决方案#2:

public synchronized boolean isPositive() { return value > 0; }

解决方案#3:

public boolean isPositive() { return get() > 0; }

我的理解是,为了确保可见性,我需要确保在CPU /核心缓存中正确刷新字段 ,因此解决方案#2和#3是可行的方法。 谁能证实这一点?

第二个问题:让我们假设我们有一个Java Spring单例,它在私有字段中保存了一些状态。 这个单例由一些请求范围的bean使用。 现在,每个请求都有自己的线程(使用它自己的调用堆栈,但共享堆)。 由于单例的状态驻留在堆上,因此单例中定义的任何方法都应该以某种方式同步访问它的私有成员(=其状态)以确保可见性,例如使用lock,volatile,ReentrantLock等。我得到对的?


Let's consider following mutable Java class (taken from "Java Concurrency in Practice" by Brian Goetz):

@ThreadSafe
public class SynchronizedInteger {
  @GuardedBy("this") private int value;

  public synchronized int get() { return value; }
  public synchronized void set(int value) { this.value = value; }
}

Assuming that this class has a single instance that is used by multiple threads, which of the following methods added to the class does NOT break its thread-safety?

Solution #1:

public boolean isPositive() { return value > 0; }

Solution #2:

public synchronized boolean isPositive() { return value > 0; }

Solution #3:

public boolean isPositive() { return get() > 0; }

My understanding is that, in order to ensure visibility, I need to make sure that the field value is properly refreshed in the CPU/core cache, so Solution #2 and #3 are the way to go. Can anyone confirm this?

Second question: Let's assume we have a Java Spring singleton that has some state held in a private field. This singleton is used by some request-scoped beans. Now, each request has it's own thread (with it's own call stack, but shared heap). Since the state of the singleton resides on the heap, any method defined in the singleton should somehow synchronize access to it's private member (= its state) in order to ensure the visibility, e.g. using lock, volatile, ReentrantLock, etc. Do I get it right?


原文:https://stackoverflow.com/questions/37845710
更新时间:2022-01-30 11:01

最满意答案

你可以这样使用boost:

std::sort(a.begin(), a.end(), 
          boost::bind(&std::pair<int, int>::second, _1) <
          boost::bind(&std::pair<int, int>::second, _2));

我不知道一个标准的方法来做同样的简短和简洁,但你可以抓住boost::bind它都由头组成。


EDIT: using c++14, the best solution is very easy to write thanks to lambdas that can now have parameters of type auto. This is my current favorite solution

std::sort(v.begin(), v.end(), [](auto &left, auto &right) {
    return left.second < right.second;
});

Just use a custom comparator (it's an optional 3rd argument to std::sort)

struct sort_pred {
    bool operator()(const std::pair<int,int> &left, const std::pair<int,int> &right) {
        return left.second < right.second;
    }
};

std::sort(v.begin(), v.end(), sort_pred());

If you're using a C++11 compiler, you can write the same using lambdas:

std::sort(v.begin(), v.end(), [](const std::pair<int,int> &left, const std::pair<int,int> &right) {
    return left.second < right.second;
});

EDIT: in response to your edits to your question, here's some thoughts ... if you really wanna be creative and be able to reuse this concept a lot, just make a template:

template <class T1, class T2, class Pred = std::less<T2> >
struct sort_pair_second {
    bool operator()(const std::pair<T1,T2>&left, const std::pair<T1,T2>&right) {
        Pred p;
        return p(left.second, right.second);
    }
};

then you can do this too:

std::sort(v.begin(), v.end(), sort_pair_second<int, int>());

or even

std::sort(v.begin(), v.end(), sort_pair_second<int, int, std::greater<int> >());

Though to be honest, this is all a bit overkill, just write the 3 line function and be done with it :-P

相关问答

更多

相关文章

更多

最新问答

更多
  • 如何在Laravel 5.2中使用paginate与关系?(How to use paginate with relationships in Laravel 5.2?)
  • linux的常用命令干什么用的
  • 由于有四个新控制器,Auth刀片是否有任何变化?(Are there any changes in Auth blades due to four new controllers?)
  • 如何交换返回集中的行?(How to swap rows in a return set?)
  • 在ios 7中的UITableView部分周围绘制边界线(draw borderline around UITableView section in ios 7)
  • 使用Boost.Spirit Qi和Lex时的空白队长(Whitespace skipper when using Boost.Spirit Qi and Lex)
  • Java中的不可变类(Immutable class in Java)
  • WordPress发布查询(WordPress post query)
  • 如何在关系数据库中存储与IPv6兼容的地址(How to store IPv6-compatible address in a relational database)
  • 是否可以检查对象值的条件并返回密钥?(Is it possible to check the condition of a value of an object and JUST return the key?)
  • GEP分段错误LLVM C ++ API(GEP segmentation fault LLVM C++ API)
  • 绑定属性设置器未被调用(Bound Property Setter not getting Called)
  • linux ubuntu14.04版没有那个文件或目录
  • 如何使用JSF EL表达式在param中迭代变量(How to iterate over variable in param using JSF EL expression)
  • 是否有可能在WPF中的一个单独的进程中隔离一些控件?(Is it possible to isolate some controls in a separate process in WPF?)
  • 使用Python 2.7的MSI安装的默认安装目录是什么?(What is the default installation directory with an MSI install of Python 2.7?)
  • 寻求多次出现的表达式(Seeking for more than one occurrence of an expression)
  • ckeditor config.protectedSource不适用于editor.insertHtml上的html元素属性(ckeditor config.protectedSource dont work for html element attributes on editor.insertHtml)
  • linux只知道文件名,不知道在哪个目录,怎么找到文件所在目录
  • Actionscript:检查字符串是否包含域或子域(Actionscript: check if string contains domain or subdomain)
  • 将CouchDB与AJAX一起使用是否安全?(Is it safe to use CouchDB with AJAX?)
  • 懒惰地初始化AutoMapper(Lazily initializing AutoMapper)
  • 使用hasclass为多个div与一个按钮问题(using hasclass for multiple divs with one button Problems)
  • Windows Phone 7:检查资源是否存在(Windows Phone 7: Check If Resource Exists)
  • 无法在新线程中从FREContext调用getActivity()?(Can't call getActivity() from FREContext in a new thread?)
  • 在Alpine上升级到postgres96(/ usr / bin / pg_dump:没有这样的文件或目录)(Upgrade to postgres96 on Alpine (/usr/bin/pg_dump: No such file or directory))
  • 如何按部门显示报告(How to display a report by Department wise)
  • Facebook墙贴在需要访问令牌密钥后无法正常工作(Facebook wall post not working after access token key required)
  • Javascript - 如何在不擦除输入的情况下更改标签的innerText(Javascript - how to change innerText of label while not wiping out the input)
  • WooCommerce / WordPress - 不显示具有特定标题的产品(WooCommerce/WordPress - Products with specific titles are not displayed)