How to implement synchronization lock based on string?, Introduction to Java foundation Second Edition PDF Baidu online disk

mb61ab40ce80d9c 2022-01-15 03:39:47 阅读数:427

implement synchronization lock based string

}??

}??

public?void?method2()?{??

String?str2?=?"a";??

synchronized?(str2)?{??

//?do?sync?b?things...??

}??

}??

At first glance , It's really convenient and simple . however , I said before. , "a" It may not be equal to "a" Of ( This is most of the case , Only when String Same value when stored in constant pool String Variables are equal ).[5 A tricky one String Interview questions ]( ), Let's see .

therefore , We can optimize it a little bit :

public?void?method3()?{??

String?str1?=?"a";??

synchronized?(str1.intern())?{??

//?do?sync?a?things...??

}??

}??

public?void?method4()?{??

String?str2?=?"a";??

《 A big factory Java Analysis of interview questions + Back end development learning notes + The latest architecture explanation video + Practical project source code handout 》

【docs.qq.com/doc/DSmxTbFJ1cmN1R2dB】 Full content open source sharing

synchronized?(str2.intern())?{??

//?do?sync?b?things...??

}??

}??

It seems very convenient and simple , The principle is to put String Object in constant pool . But there's a problem , How to clean up the data of these constant pools ?

Anyway , Can we base ourselves on String Implement a lock ? Pay attention to WeChat public number :Java Technology stack , Reply in the background :Java, I can get the N piece Java course , Is dry .

It must be possible ! Go straight to the code !

[import?org.slf4j.Logger;?? import?org.slf4j.LoggerFactory;?? import?java.util.concurrent.ConcurrentHashMap;?? import?java.util.concurrent.ConcurrentMap;?? import?java.util.concurrent.CountDownLatch;?? /**?? ?*? be based on string? Lock implementation ?? ?*/?? public?final?class?StringBasedMutexLock?{?? ????private?static?final?Logger?logger?=?LoggerFactory.getLogger(StringBasedMutexLock.class);?? ????/**?? ?????*? Character lock ? Manager ,? Put each string ? Convert to a ?CountDownLatch?? ?????*?? ?????*?????? That is, locks only happen when there are real concurrent updates ? The same ?String? Under the circumstances ?? ?????*?? ?????*/?? ????private?static?final?ConcurrentMap<String,?CountDownLatch>?lockKeyHolder?=?new?ConcurrentHashMap<>();?? ????/**?? ?????*? be based on lockKey? locked , Synchronous execution ?? ?????*?? ?????*?@param?lockKey? Character lock ?? ?????*/?? ????public?static?void?lock(String?lockKey)?{?? ????????while?(!tryLock(lockKey))?{?? ????????????try?{?? ????????????????logger.debug("【 Character lock 】 Concurrent update lock upgrade ,?{}",?lockKey);?? ????????????????blockOnSecondLevelLock(lockKey);?? ????????????}?catch?(InterruptedException?e)?{?? ????????????????Thread.currentThread().interrupt();?? ????????????????logger.error("【 Character lock 】 Interrupt exception :"?+?lockKey,?e);?? ????????????????break;?? ????????????}?? ????????}?? ????}?? ????/**?? ?????*? Release ?lockKey? Corresponding lock options , Make other threads executable ?? ?????*?? ?????*?@param?lockKey? To use mutually exclusive strings ?? ?????*?@return?true:? Release successful ,?false:? Release failed , May be released by other threads by mistake ?? ?????*/?? ????public?static?boolean?unlock(String?lockKey)?{?? ????????//? Delete the lock first , Release the lock again , This will lead to subsequent concurrent priority execution , No influence ?? ????????CountDownLatch?realLock?=?getAndReleaseLock1(lockKey);?? ????????releaseSecondLevelLock(realLock);?? ????????return?true;?? ????}?? ????/**?? ?????*? Try to lock the specified string ?? ?????*?? ?????*?@param?lockKey? To use mutually exclusive strings ?? ?????*?@return?true:? Locked successfully ,?false:? Lock failed ?? ?????*/?? ????private?static?boolean?tryLock(String?lockKey)?{?? ????????//? There will be a lot of ReentrantLock Object creation ??? ????????//? Not really , The maximum number is equal to the number of external concurrent , Just for ?gc? Not very friendly , Will create and destroy repeatedly y?? ????????return?lockKeyHolder.putIfAbsent(lockKey,?new?CountDownLatch(1))?==?null;?? ????}?? ????/**?? ?????*? Release 1 Level lock ( Delete )? And return the heavyweight lock ?? ?????*?? ?????*?@param?lockKey? Character lock ?? ?????*?@return? A real lock ?? ?????*/?? ????private?static?CountDownLatch?getAndReleaseLock1(String?lockKey)?{?? ????????return?lockKeyHolder.remove(lockKey);?? ????}?? ????/**?? ?????*? Secondary lock lock ( Lock escalation )?? ?????*?? ?????*?@param?lockKey? Lock string ?? ?????*?@throws?InterruptedException? Throw an exception on interrupt ?? ?????*/?? ????private?static?void?blockOnSecondLevelLock(String?lockKey)?throws?InterruptedException?{?? ????????CountDownLatch?realLock?=?getRealLockByKey(lockKey);?? ????????//? by ?null? Indicates that the lock has been deleted at this time ,??next?race?? ????????if(realLock?!=?null)?{?? ????????????realLock.await();?? ????????}?? ????}?? ????/**?? ?????*? Secondary lock unlocking ( If necessary, )?? ?????*?? ?????*?@param?realLock? Lock instance ?? ?????*/?? ????private?static?void?releaseSecondLevelLock(CountDownLatch?realLock)?{?? ????????realLock.countDown();?? ????}?? ????/**?? ?????*? adopt key? Get the corresponding lock instance ?? ?????*?? ?????*?@param?lockKey? String lock ?? ?????*?@return? Lock instance ?? ?????*/?? ????private?static?CountDownLatch?getRealLockByKey(String?lockKey)?{?? ????????return?lockKeyHolder.get(lockKey);?? ????}?? }]( )??

When using , Just incoming lockKey that will do .?

Is there any advantage in doing so ?

  1. Use ConcurrentHashMap Achieve lock acquisition , The performance is still good ;

  2. Each string corresponds to a lock , Delete... After use , It will not cause memory overflow ;

Last

There is also a way to brush questions in the interview , It's better to follow the topic , And then from basic to advanced , From the shallow to the deep , It works better . Of course , I also put all these contents in one copy pdf In the document , It is divided into the following major topics :

  • Java Base part

 How to base on String Realize synchronous lock ?,java Basic introduction Second Edition pdf Baidu SkyDrive

  • Algorithms and programming

 How to base on String Realize synchronous lock ?,java Basic introduction Second Edition pdf Baidu SkyDrive

  • Database part

 How to base on String Realize synchronous lock ?,java Basic introduction Second Edition pdf Baidu SkyDrive

  • Popular framework and new technology (Spring+SpringCloud+SpringCloudAlibaba)

 How to base on String Realize synchronous lock ?,java Basic introduction Second Edition pdf Baidu SkyDrive

This interview document is more than that , It's actually like JVM、 Design patterns 、ZK、MQ、 Data structure and other parts of the interview content are involved in , Because of the length of the article , It's not all here .

As a programmer , Periodic learning is essential , And it needs to be sustained , This time at this stage , I have systematically reviewed some key knowledge points , On the one hand, they have consolidated their own foundation , On the other hand, it also improves the breadth and depth of their knowledge .

This article has been  CODING Open source project :【 A big factory Java Analysis of interview questions + Core summary learning notes + The latest explanation video + Actual project source code 】 Included

版权声明:本文为[mb61ab40ce80d9c]所创,转载请带上原文链接,感谢。 https://javamana.com/2021/12/202112122318461801.html