when to use reentrant lock

本文探讨了ReentrantLock与内置同步块(synchronized)之间的选择依据,指出ReentrantLock适用于需要高级同步功能的情况,如定时锁等待、可中断锁等待等。建议开发者先使用简单的同步机制,在证实其不足后再考虑采用更复杂的工具。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

The answer is pretty simple -- use it when you actually need something it provides that synchronized doesn't,

like timed lock waits, interruptible lock waits, non-block-structured locks, multiple condition variables, or lock polling.

ReentrantLock also has scalability benefits, and you should use it if you actually have a situation that exhibits high contention,

but remember that the vast majority of synchronized blocks hardly ever exhibit any contention, let alone high contention.

I would advise developing with synchronization until synchronization has proven to be inadequate,

rather than simply assuming "the performance will be better" if you use ReentrantLock. Remember, these are advanced tools for advanced users.

(And truly advanced users tend to prefer the simplest tools they can find until they're convinced the simple tools are inadequate.)

As always, make it right first, and then worry about whether or not you have to make it faster.

转载于:https://www.cnblogs.com/glf2046/p/4740568.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值