const{createApp}=Vue const{createVuetify,useGoTo,useDisplay}=Vuetify var data={alert:{show:false,color:'success',text:'',timeout:0,},theme:{dark:false,},nav:{showDrawer:false,showTOC:true,tocPanel:0,tab:'account',post:{discussionId:1005,currentPage:1,targetPage:1,total:8,anchor:0,goToOptions:{container:null,duration:0,easing:'easeInOutCubic',offset:-100,},worker:null,task:[],active:[],apiLock:[],originLike:new Map([]),},related:{block:1,}},search:{width:80,text:null,loading:false,},tags:[{id:28,url:'/t/3d104b0f6a045c7568772c310313',name:'Java',color:'#FFA726',icon:'mdi-language-java',},],posts:[{id:12390,num:0,uid:4645,content:'背景\u003Cp\u003E偶然看到了一篇 ReentrantLock 的源码分析文章,自己便去学习了一下源码。核心思想是如果被请求的共享资源空闲,那么就将当前请求资源的线程设置为有效的工作线程,将共享资源设置为锁定状态;如果共享资源被占用,就需要一定的阻塞等待唤醒机制来保证锁分配。\u003C/p\u003E问题\u003Cp\u003EReentrantLock 的 lock 方法在入队之前直接获取锁,是否冗余设计,存在冗余的代码执行?\u003C/p\u003E我的观点\u003Cp\u003E进行了冗余设计,理解如下。\u003C/p\u003Ejdk8\u003Cp\u003Elock 简化代码如下,我的观点是:非公平锁(NofairSync) lock 方法,有两次尝试直接获取锁,是否冗余设计了?\u003C/p\u003E\u003Ccode\u003Estatic final class NonfairSync extends Sync { final void lock() { // 直接尝试获取锁,不公平表现 if (compareAndSetState(0, 1)) setExclusiveOwnerThread(Thread.currentThread()); else acquire(1); // acquire 方法中首先会调用 tryAcquire ,会第二次尝试获取锁 } protected final boolean tryAcquire(int acquires) { // 如果资源空闲,直接尝试获取锁 // 如果资源不空闲,判断是否当前线程占有,进行重入锁 }}static final class FairSync extends Sync { final void lock() { acquire(1); } protected final boolean tryAcquire(int acquires) { // 如果资源空闲,判断是否已经入队,进行公平处理 // 如果资源不空闲,判断是否当前线程占有,进行重入锁 }}class AbstractQueuedSynchronizer { public final void acquire(int arg) { if (!tryAcquire(arg) \u0026amp;\u0026amp; acquireQueued(addWaiter(Node.EXCLUSIVE), arg)) selfInterrupt(); }}\u003C/code\u003Ejdk17\u003Cp\u003Elock 简化代码如下,我的观点是:lock 方法,有两次尝试直接获取锁,是否冗余设计了?对于公平锁,均会判断当前线程是否已经入队,是冗余的尝试;对于非公平锁,连续两次尝试直接获取锁,也是冗余的尝试\u003C/p\u003E\u003Ccode\u003Eabstract static class Sync extends AbstractQueuedSynchronizer { abstract boolean initialTryLock(); final void lock() { if (!initialTryLock()) // 首次尝试获取锁 acquire(1); // acquire 方法中首先会调用 tryAcquire ,会第二次尝试获取锁 }}static final class NonfairSync extends Sync { final boolean initialTryLock() { // 如果资源空闲,直接尝试获取锁 // 如果资源不空闲,判断是否当前线程占有,进行重入锁 } protected final boolean tryAcquire(int acquires) { // 如果资源空闲,直接尝试获取锁 }}static final class FairSync extends Sync { final boolean initialTryLock() { // 如果资源空闲,判断是否已经入队,进行公平处理 // 如果资源不空闲,判断是否当前线程占有,进行重入锁 } protected final boolean tryAcquire(int acquires) { // 如果资源空闲,判断是否已经入队,进行公平处理 }}\u003C/code\u003E我认为的不冗余的方式\u003Ccode\u003Estatic class Sync extends AbstractQueuedSynchronizer { final void lock() { acquire(1); }}static final class NonfairSync extends Sync { protected final boolean tryAcquire(int acquires) { // 如果资源空闲,直接尝试获取锁 // 如果资源不空闲,判断是否当前线程占有,进行重入锁 }}static final class FairSync extends Sync { protected final boolean tryAcquire(int acquires) { // 如果资源空闲,判断是否已经入队,进行公平处理 // 如果资源不空闲,判断是否当前线程占有,进行重入锁 }}\u003C/code\u003E',ipRegion:'',updatedByUid:0,createdAt:'2025-03-10 12:33:59',updatedAt:'2025-03-12 13:23:13',mentionNum:0,mentionedBy:[],mentionUsers:[],likeUsers:[],},{id:12391,num:1,uid:2671,content:'不算设计冗余,两次调用 compareAndSetState 都是为了在无竞争时快速成功。第一次调用返回 false 意味着有竞争,此时进入 acquire 。在 acquire 里会根据 state 的值判断是否调用 compareAndSetState ,原因是这中间有可能从有竞争变为无竞争( volatile ),此时快速成功就行了。state 的值\u0026gt;0 才是可重入锁/其它线程占用的情况,最后再做其它处理。',ipRegion:'',updatedByUid:0,createdAt:'2025-03-10 14:52:02',updatedAt:'2025-03-12 13:23:13',mentionNum:0,mentionedBy:[],mentionUsers:[],likeUsers:[],},{id:12392,num:2,uid:472,content:'你的疑问算是一个面试题了',ipRegion:'',updatedByUid:0,createdAt:'2025-03-10 14:55:23',updatedAt:'2025-03-12 13:23:13',mentionNum:0,mentionedBy:[],mentionUsers:[],likeUsers:[],},{id:12393,num:3,uid:223,content:'经典面试题。跟一楼说的一样,大部分时候资源是不上锁的,一般能快速拿到锁就拉倒了没必要再去 AQS 里面拐一圈。\u003Cbr\u003E这也算是并发编程里面的“快慢路径”的一种体现。',ipRegion:'',updatedByUid:0,createdAt:'2025-03-10 15:47:16',updatedAt:'2025-03-12 13:23:13',mentionNum:0,mentionedBy:[],mentionUsers:[],likeUsers:[],},{id:12394,num:4,uid:4646,content:'学到了',ipRegion:'',updatedByUid:0,createdAt:'2025-03-10 15:54:00',updatedAt:'2025-03-12 13:23:13',mentionNum:0,mentionedBy:[],mentionUsers:[],likeUsers:[],},{id:12395,num:5,uid:4647,content:'其实把你的问题直接问 AI ,都有答案了。\u003Cbr\u003E1. 非公平锁的“两次尝试”设计\u003Cbr\u003E在非公平锁中,lock() 方法在入队前先尝试直接获取锁(通过 initialTryLock() 或 CAS 操作),若失败再调用 acquire(),而在 acquire() 中又会调用 tryAcquire() 再次尝试。这看似重复,实为优化:\u003Cbr\u003E\u003Cbr\u003E减少线程挂起/唤醒的开销:当锁被释放时,新线程可能直接抢占锁(插队),而无需等待队列中的线程被唤醒,提高了吞吐量。\u003Cbr\u003E避免不必要的队列操作:若首次尝试成功,线程直接获取锁,无需进入队列,减少了入队、出队和上下文切换的开销。',ipRegion:'',updatedByUid:0,createdAt:'2025-03-10 16:19:40',updatedAt:'2025-03-12 13:23:13',mentionNum:0,mentionedBy:[],mentionUsers:[],likeUsers:[],},{id:12396,num:6,uid:4648,content:'并发编程的经典优化方式:快慢路径\u003Cbr\u003E\u003Cbr\u003E一般先走 Fast Path ,用 CAS 尝试快速获取资源;失败后,走 Slow Path ,可能会涉及到一些阻塞、沉睡、排队之类的操作',ipRegion:'',updatedByUid:0,createdAt:'2025-03-10 20:18:07',updatedAt:'2025-03-12 13:23:13',mentionNum:0,mentionedBy:[],mentionUsers:[],likeUsers:[],},{id:12397,num:7,uid:1131,content:'我觉得要重点提出 1 楼说的“这中间有可能从有竞争变为无竞争( volatile )”,我觉了楼主可能犯了并发编程里一个常见是思维错误就是我“刚刚” 判断了一个条件,后面就不用判断了。',ipRegion:'',updatedByUid:0,createdAt:'2025-03-11 00:05:19',updatedAt:'2025-03-12 13:23:13',mentionNum:0,mentionedBy:[],mentionUsers:[],likeUsers:[],},],usersMap:new Map([[4647,{uid:4647,url:'/u/081800056a045c73666e516f2f050b14',avatar:'/a/081800056a045c73666e516f2f050b14',username:'JoJoWuBeHumble🤖',}],[4645,{uid:4645,url:'/u/3171615d6a045c73666e536f2d0e117f',avatar:'/a/3171615d6a045c73666e536f2d0e117f',username:'HowieWang🤖',}],[223,{uid:223,url:'/u/1e716b276a045c776268556f365b2902',avatar:'/a/1e716b276a045c776268556f365b2902',username:'kandaakihito🤖',}],[1131,{uid:1131,url:'/u/0a3d01236a045c766169576f4f251100',avatar:'/a/0a3d01236a045c766169576f4f251100',username:'billccn🤖',}],[472,{uid:472,url:'/u/3f3b40356a045c77646d546f03041724',avatar:'/a/3f3b40356a045c77646d546f03041724',username:'Rickkkkkkk🤖',}],[4648,{uid:4648,url:'/u/6c2a79356a045c73666e5e6f2d5d1916',avatar:'/a/6c2a79356a045c73666e5e6f2d5d1916',username:'gitrebase🤖',}],[4646,{uid:4646,url:'/u/192a670c6a045c73666e506f24310516',avatar:'/a/192a670c6a045c73666e506f24310516',username:'mamumu🤖',}],[2671,{uid:2671,url:'/u/1c0276066a045c75666d576f26081d2c',avatar:'/a/1c0276066a045c75666d576f26081d2c',username:'herm2s🤖',}],]),related:[{title:'有在 vscode 上写 Java 的么?一个非常简单的扩展:可以一键复制 arthas 的 watch 命令。',url:'/d/0b26510b6a045c77606a567a455e606a5f011624',},{title:'「郑州」招聘高级 Java 15K 上下,看个人水平',url:'/d/6a2d46346a045c77606a56754e58616a0e216467',},{title:'技术栈选择: Java 还是 Python',url:'/d/2878683b6a045c77606a5675475d616a083a1603',},{title:'Java 开发,接下来的路咋走啊?',url:'/d/1f78462e6a045c77606a5675475b656a1c37230a',},{title:'windsurf 和 cursor 用来写 kotlin 后端还是不太行',url:'/d/2b780b5e6a045c77606a5674425a656a2d103a64',},{title:'Java 后端开发 , macbookAir m4 16+256G 入门款值得入手不,pdd6199 元,(之前那个 MacBookpro 2018 32G+512G 电脑坏了修起来要 4k 以上,没什么维修价值了)另外问一下够用不',url:'/d/200d00356a045c77606a5674435b6b6a0d276310',},{title:'C++ 开发不想 996,如何跳槽转到 Java ?',url:'/d/09207c086a045c77606a56744358646a1f292613',},{title:'Java 和 go 都会,以后找工作偏向哪个方面好呢',url:'/d/000b7b1b6a045c77606a5674445e656a1977262a',},{title:'作为一个传统开发者,如何使用 ai 或者机器学习实现一些简单事情',url:'/d/34015f186a045c77606a5674445e626a25016611',},{title:'Java 生态下想搞大流量下的 ws,是不是暂时只能 netty?',url:'/d/6c7f0b1a6a045c77606a56774251626a5b761219',},{title:'为什么很多人喷 Java 开发者离了 spring 框架就不会写代码了',url:'/d/2c795a5c6a045c77606a56764051666a58303c13',},{title:'Java 找工作有感,行业经验大于一切',url:'/d/3d06072a6a045c77606a5676405c616a050b2611',},{title:'小白发问,都说 C++开发效率比 Java 低,但 C++的 hello world 也没多几行代码啊',url:'/d/6f7157036a045c77606a5676425b616a342a1235',},{title:'作为 Java 狗的我,学习 rust 的时候为啥总念着 go 的好呢?',url:'/d/6f2a02176a045c77606a5671435d636a2f121465',},{title:'原 Java 刚学习 go, 自己在写项目, 针对 go 日志方面的疑惑',url:'/d/6b2c02596a045c77606a56714359626a0f361626',},{title:'主力开发工具不是 VS 的比如 Java ,如何使用大模型辅助开发呢?转到 VS 或者 IDEA 有什么可以使用大模型 API 的插件?',url:'/d/332c065d6a045c77606a56734759676a2a021e61',},],} const App={setup(){const goTo=useGoTo() const{mdAndUp}=useDisplay() return{goTo,mdAndUp}},data(){return data;},mounted(){const themeDark=localStorage.getItem("themeDark") if(themeDark!==null){this.theme.dark=JSON.parse(themeDark)} if(this.nav.post.total>(this.nav.post.currentPage-1)*100+20){let moreLen=100 if(this.nav.post.total({id:null,num:(this.nav.post.currentPage-1)*100+v,uid:null,content:null,ipRegion:null,updatedByUid:null,createdAt:null,updatedAt:null,mentionNum:null,mentionedBy:null,mentionUsers:null,likeUsers:null,})) this.posts.push(...morePosts.slice(20))} this.workerStart() const hash=window.location.hash const match=hash.match(/#(\d+)/) if(match){const n=parseInt(match[1],10) if(n>=(this.nav.post.currentPage-1)*100&&n{this.jumpTo(n)})}} this.$nextTick(()=>{this.addHeadingIds() tocbot.init({tocSelector:'.toc',contentSelector:'#post-content-0',headingSelector:'h2, h3, h4',headingsOffset:100,scrollSmoothOffset:-100,scrollSmooth:true,collapseDepth:6,onClick:function(e){setTimeout(()=>{history.replaceState(null,'',window.location.pathname+window.location.search)},0)},}) tocbot.refresh()});},beforeUnmount(){this.workerStop() if(this.quill){this.quill.destroy() this.quill=null}},computed:{dposts(){return this.posts.slice(20);},},created(){},methods:{successAlert(msg){this.alert={show:true,color:'success',text:msg,timeout:1500,}},failureAlert(msg){this.alert={show:true,color:'error',text:msg,timeout:5000,}},flipThemeDark(){this.theme.dark=!this.theme.dark localStorage.setItem("themeDark",JSON.stringify(this.theme.dark))},toSearch(){if(!this.search.text){this.failureAlert('搜索词不能为空') return} let keywords=this.search.text.trim() if(keywords.length<1){this.failureAlert('搜索词不能为空') return} if(keywords.length>100){this.failureAlert('搜索词过长') return} this.doSearch(keywords)},toReg(){window.location.href="/reg"},toLogin(){window.location.href="/login"},toPage(){let url=window.location.href url=url.replace(/(\/\d+)?(#[0-9]+)?$/,this.nav.post.targetPage>1?`/${this.nav.post.targetPage}`:'') window.location.href=url},toLoadRelated({done}){if(this.my&&this.my.uid){this.apiLoadRelated({done})}else{done('ok')}},workerStart(){this.nav.post.worker=setInterval(()=>{this.workerLoad()},500);},workerStop(){if(this.nav.post.worker){clearInterval(this.nav.post.worker);this.nav.post.worker=null;}},async jumpTo(num){const page=Math.floor(num/100)+1 const i=num-(page-1)*100 if(page===this.nav.post.currentPage){this.goTo("#post-"+num,this.nav.post.goToOptions) if(!this.posts[i].id){const block=Math.floor(num/20)+1 this.nav.post.apiLock[block]=true await this.apiLoadPosts(block) this.$nextTick(()=>{this.goTo("#post-"+num,this.nav.post.goToOptions)})}}else{let url=window.location.href url=url.replace(/(\/\d+)?(#[0-9]+)?$/,page>1?`/${page}`:'') url=url+"#"+num window.location.href=url}},postIntersect(num){return(isIntersecting,entries,observer)=>{if(isIntersecting){this.nav.post.task.push(num) this.nav.post.active.push(num) this.nav.post.active=this.nav.post.active.filter(item=>Math.abs(item-num)<=5) this.nav.post.active.sort((a,b)=>a-b)}else{this.nav.post.active=this.nav.post.active.filter(item=>item!==num)} if(this.nav.post.active[0]){this.nav.post.anchor=this.nav.post.active[0]}else{this.nav.post.anchor=0}}},async apiLoadPosts(block){try{const response=await axios.post('/fapi/v1/post/block/'+block,{discussionId:this.nav.post.discussionId,}) if(response.data.code===0){response.data.data.posts.forEach(post=>{const i=post.num%100 Object.assign(this.posts[i],post)}) response.data.data.users.forEach(user=>{this.usersMap.set(user.uid,user)})}else{this.failureAlert('回帖数据加载失败: '+response.data.msg)}}catch(error){this.failureAlert('回帖数据加载失败: '+error)} this.nav.post.apiLock[block]=false},workerLoad(){while(this.nav.post.task.length){const num=this.nav.post.task.pop() const i=num-(this.nav.post.currentPage-1)*100 if(!this.posts[i].id){const block=Math.floor(num/20)+1 if(!this.nav.post.apiLock[block]){this.nav.post.apiLock[block]=true this.apiLoadPosts(block)}}}},getTimeInfo(t){if(!t){return ""} const now=new Date();const then=new Date(t);const diff=now-then;const minute=60*1000;const hour=minute*60;const day=hour*24;const month=day*30;const year=month*12;if(diffpost.num===num) if(!post){return "#"+num} const uid=post.uid const username=this.usersMap.get(uid)?.username if(!username){return "#"+num} return username},getUsernameByPostId(id){const post=this.posts.find(post=>post.id===id) if(!post){return "#"+this.getPostNumByPostId(id)} const uid=post.uid const username=this.usersMap.get(uid).username if(!username){return "#"+this.getPostNumByPostId(id)} return username},getPostNumByPostId(id){const post=this.posts.find(post=>post.id===id) return post.num},getPostById(id){const post=this.posts.find(post=>post.id===id) return post},getPostByNum(num){const post=this.posts.find(post=>post.num===num) return post},getAvatarByUid(uid){const avatar=this.usersMap.get(uid)?.avatar if(!avatar){return this.getRandomAvatar()} return avatar},getAvatarByPostNum(num){const post=this.posts.find(post=>post.num===num) if(!post){return this.getRandomAvatar()} const uid=post.uid return this.getAvatarByUid(uid)},getRandomAvatar(){const num=Math.floor(Math.random()*100) return "https://randomuser.me/api/portraits/men/"+num+".jpg"},getUrlByUid(uid){const url=this.usersMap.get(uid)?.url if(!url){return ""} return url},getTextByPostNum(num){const post=this.posts.find(post=>post.num===num) if(!post||!post.content){return '点击跳转到#'+num+'查看'} const parser=new DOMParser() const doc=parser.parseFromString(post.content,'text/html') const text=doc.body.textContent||'' return text.slice(0,100)},addHeadingIds(){const content=document.getElementById('post-content-0') if(!content){this.nav.showTOC=false return} const headings=content.querySelectorAll('h2, h3, h4') headings.forEach((heading,index)=>{if(!heading.id){heading.id=`toc-nav-${index}`}}) if(headings.length==0){this.nav.showTOC=false}},async doSearch(keywords){this.search.loading=true try{const response=await axios.post('/fapi/v1/search',{keywords:keywords,}) if(response.data.code===0){if(response.data.data.hash&&response.data.data.hash.length===32){window.location.href="/s/"+response.data.data.hash}else{this.failureAlert('搜索失败: 搜索服务异常')}}else{this.failureAlert('搜索失败: '+response.data.msg)}}catch(error){this.failureAlert('搜索失败: '+error)} this.search.loading=false},debounce(fn,delay){let timer=null return function(...args){if(timer)clearTimeout(timer) timer=setTimeout(()=>{fn.apply(this,args)},delay);};},},watch:{'nav.post.targetPage':{handler:async function(newV,oldV){this.toPage()},immediate:false},},} const vuetify=createVuetify({defaults:{global:{ripple:true,},},}) const app=createApp(App) app.use(vuetify).mount("#app")