博客
关于我
java中的synchronized和linux系统的futex到底什么个关系?
阅读量:89 次
发布时间:2019-02-25

本文共 1397 字,大约阅读时间需要 4 分钟。

Linux futex与Java中的synchronized锁

Linux Futex的基础知识

Futex(Fiber mutex)并非传统意义上的锁,而是锁实现中的一个基础组件。它允许在用户态完成锁的部分操作,而不需要所有操作都在内核态完成。这通过两个系统调用:futex_waitfutex_wake实现。这些系统调用帮助用户空间实现锁的机制,减少了内核态的参与,从而提升了性能。

锁的工作原理

传统锁在内核态完成所有操作,然而这可能导致频繁的上下文切换,影响性能。现代锁设计通过将部分操作移至用户态实现,减少了内核态的负担。通过CAS算法,在用户态完成抢锁的尝试,大部分情况下抢锁成功,竞争激烈时则进入内核态等待或唤醒。

Java中的Synchronized锁

Java的synchronized锁依赖于JVM的monitor机制,实际上使用了glibc中的pthread_mutexpthread_cond。这些接口基于Futex实现,用户态部分由JVM管理,内核态部分由Futex系统调用完成。这种设计使得Java在Linux上的多线程实现高效。

示例分析

以下Java代码展示了synchronized锁在多线程环境中的行为:

public class TestFutex {    private Integer a = new Integer(1);    synchronized void showA() {        System.out.println(a);        try {            Thread.sleep(3000);        } catch (InterruptedException e) {        }    }    class T extends Thread {        @Override        public void run() {            showA();        }    }    public T newThread() {        return new T();    }    public static void main(String[] args) {        TestFutex tf = new TestFutex();        T t1 = tf.newThread();        T t2 = tf.newThread();        t1.start();        t2.start();    }}

在这个例子中,两个线程同时启动,试图进入synchronized方法。当第一个线程进入方法时,其他线程进入futex_wait等待状态,直到锁被释放。

JUC中的ReentrantLock和Semaphore

JUC中的ReentrantLockSemaphore也基于Futex实现。LockSupport.park方法使用Futex进行parkunpark操作,这是实现可重入锁和信号量机制的基础。

总结

Futex作为锁实现的基础组件,在用户态和内核态都发挥着重要作用。Java的synchronized锁和JUC组件利用Futex实现了高效的多线程锁机制,这在Linux环境中得到了广泛应用。

转载地址:http://gan.baihongyu.com/

你可能感兴趣的文章
org.apache.http.conn.HttpHostConnectException: Connection to refused
查看>>
org.apache.ibatis.binding.BindingException: Invalid bound statement错误一例
查看>>
org.apache.ibatis.exceptions.PersistenceException:
查看>>
org.apache.ibatis.exceptions.TooManyResultsException: Expected one result (or null) to be returned
查看>>
org.apache.ibatis.type.TypeException: Could not resolve type alias 'xxxx'异常
查看>>
org.apache.poi.hssf.util.Region
查看>>
org.apache.xmlbeans.XmlOptions.setEntityExpansionLimit(I)Lorg/apache/xmlbeans/XmlOptions;
查看>>
org.apache.zookeeper.KeeperException$ConnectionLossException: KeeperErrorCode = ConnectionLoss for /
查看>>
org.hibernate.HibernateException: Unable to get the default Bean Validation factory
查看>>
org.hibernate.ObjectNotFoundException: No row with the given identifier exists:
查看>>
org.springframework.boot:spring boot maven plugin丢失---SpringCloud Alibaba_若依微服务框架改造_--工作笔记012
查看>>
SQL-CLR 类型映射 (LINQ to SQL)
查看>>
org.springframework.orm.hibernate3.support.OpenSessionInViewFilter
查看>>
org.springframework.orm.hibernate3.support.OpenSessionInViewFilter
查看>>
org.springframework.web.multipart.MaxUploadSizeExceededException: Maximum upload size exceeded
查看>>
org.tinygroup.serviceprocessor-服务处理器
查看>>
org/eclipse/jetty/server/Connector : Unsupported major.minor version 52.0
查看>>
org/hibernate/validator/internal/engine
查看>>
Orleans框架------基于Actor模型生成分布式Id
查看>>
SQL-36 创建一个actor_name表,将actor表中的所有first_name以及last_name导入改表。
查看>>