Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use ReentrantLock to realize long polling in Java

2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly introduces "how to use ReentrantLock to achieve long polling in Java". In daily operation, I believe many people have doubts about how to use ReentrantLock to achieve long polling in Java. The editor consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful to answer the doubts about "how to use ReentrantLock to achieve long polling in Java". Next, please follow the editor to study!

Java code 1. ReentrantLock

Lock blocking, a condition corresponds to a thread, so that when you wake up, using the condition must wake up the thread.

/ * obtain probe data and implement * @ param messageId * @ return * / public JSONObject getToutData (String messageId) {Message message = toutMessageCache.get (messageId); if (message = = null) {/ / wait for lock.lock (); try {Condition condition = lock.newCondition () ConditionMap.put (messageId + "_ data", condition); condition.await (CONNECTION_HOLD_TIMEOUT, TimeUnit.SECONDS); / / wait 60s} catch (InterruptedException e) {/ / wait timeout, do nothing} finally {lock.unlock () }} / / try to get message = toutMessageCache.get (messageId) again; if (message = = null) {/ / if not, return empty object return null;} byte [] bytes = message.getDataBytes (); if (bytes = = null) {return null } String resStr = new String (bytes, StandardCharsets.UTF_8); / / log.info ("resStr: {}", resStr); JSONObject resObj; try {resObj = new JSONObject (resStr); resObj.put ("invokeTime", DateUtil.format (new Date (resObj.getLong ("invokeTime")), DatePattern.NORM_DATETIME_MS_PATTERN)) } catch (Exception e) {resObj = new JSONObject ();} return resObj;} 2. Callback

When the asynchronous data is returned, wake up the thread using the condition in the previous step

Public void callback (Message message) {String messageId = message.getId (); toutMessageCache.put (message.getId (), message); String messageDataId = messageId + "_ data"; if (conditionMap.containsKey (messageDataId)) {lock.lock (); try {Condition condition = conditionMap.get (messageDataId); condition.signal ();} catch (Exception e) {e.printStackTrace () } finally {lock.unlock (); conditionMap.remove (messageDataId);}} 3. Awaken

Perform callback operation

Public void distribute (Message message, ChannelHandlerContext ctx) {MessageType messageType = message.getMessageType (); switch (messageType) {case TOUT_DATA_RESPONSE: / / data response toutService.callback (message); break;}} 4. Call

When calling, determine whether the returned value is empty, and if so, agree with the front end that when the status value is returned, the same request should be made again

/ * obtain probe data (implemented using long polling) * @ param linkId* @ return*/@GetMapping ("/ data") public ResultVO getToutData (String linkId) {JSONObject resObj = toutService.getToutData (linkId); if (resObj = = null | | resObj.isEmpty () {return ResultVOUtil.error (ResultEnum.NO_MESSAGE_HOLD_CONNECTION);} return ResultVOUtil.success (resObj);} 5. Front-end implementation

Simple use of recursion to initiate a request again when the data return is invalid

Let that = thisfunction getData () {if (toutStatus = statusEnum.start) {getToutData ({linkId}) .then (res = > {if (res.code = ERROR_CODE_OK) {that.toutData = res.data toutStatus = statusEnum.resData that._btnStatus ()} else { GetData ()})}} / / Recursive loop calls getData () to this point The study on "how to use ReentrantLock to achieve long polling in Java" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report