Java编写互斥锁的最快方法? [英] Fastest Way for Java to write mutexes?

查看:115
本文介绍了Java编写互斥锁的最快方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Mutexes 在许多编程语言中非常常见,例如: C / C ++。我在Java中想念他们。但是,我可以通过多种方式编写自己的类Mutex

Mutexes are pretty common in many programming languages, like e.g. C/C++. I miss them in Java. However, there are multiple ways I could write my own class Mutex:


  • 使用 Mutex 上的简单synchronized关键字。

  • 使用二进制信号量

  • 使用原子变量,如讨论的< a href =https://stackoverflow.com/questions/4938617/implement-a-mutex-in-java-using-atomic-variables>这里。

  • ...?

  • Using a simple synchronized keyword on Mutex.
  • Using a binary semaphore.
  • Using atomic variables, like discussed here.
  • ...?

什么是最快(最好的运行时)方式?我认为同步是最常见的,但性能呢?

What is the fastest (best runtime) way? I think synchronized is most common, but what about performance?

推荐答案


互斥锁在很多很常见编程语言,例如C / C ++。我想念他们用Java。

Mutexes are pretty common in many programming languages, like e.g. C/C++. I miss them in Java.

不确定我是否关注你(特别是因为你在问题中给出答案)。

Not sure I follow you (especially because you give the answer in your question).

public class SomeClass {
    private final Object mutex = new Object();

    public void someMethodThatNeedsAMutex() {
        synchronized(mutex) {
            //here you hold the mutex
        }
    }
}

或者,您可以简单地使整个方法同步,这相当于使用这个作为互斥对象:

Alternatively, you can simply make the whole method synchronized, which is equivalent to using this as the mutex object:

public class SomeClass {

    public synchronized void someMethodThatNeedsAMutex() {
        //here you hold the mutex
    }
}




什么是最快(最好的运行时)方式?

What is the fastest (best runtime) way?

获取/发布监视器本身不会成为重要的性能问题(您可以阅读此博客文章,以查看对影响的分析)。但是如果你有许多线程争夺锁,它会产生争用并降低性能。

Acquiring / releasing a monitor is not going to be a significant performance issue per se (you can read this blog post to see an analysis of the impact). But if you have many threads fighting for the lock, it will create contention and degrade performance.

在这种情况下,最好的策略是不要使用锁来使用互斥锁 - 免费算法,如果你主要是读取数据(正如Marko在评论中指出的那样,无锁使用CAS操作,如果你有很多写线程可能会涉及多次重写,最终导致性能更差)甚至更好的方法是避免跨线程分享太多东西。

In that case, the best strategy is to not use mutexes by using "lock-free" algorithms if you are mostly reading data (as pointed out by Marko in the comments, lock-free uses CAS operations, which may involve retrying writes many times if you have lots of writing threads, eventually leading to worse performance) or even better, by avoiding to share too much stuff across threads.

这篇关于Java编写互斥锁的最快方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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