Last active
May 12, 2023 01:44
-
-
Save cesclong/c83ddd81aa12611cdedd9027c55f20c5 to your computer and use it in GitHub Desktop.
ConcurrentHashMap日常使用的例子
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 当有很多用户同时登入和登出时, | |
* onUserSignIn() 和 onUserSignOut() 就会有很多线程同时调用 | |
*/ | |
class UserMgr private constructor() { | |
private val userMap: ConcurrentHashMap<String, User> = ConcurrentHashMap<String, User>() | |
companion object { | |
private val instance by lazy(LazyThreadSafetyMode.SYNCHRONIZED) { UserMgr() } | |
fun Get() = instance | |
} | |
// 当用户登入时调用 | |
fun onUserSignIn(sessionId: String, user: User) { | |
userMap[sessionId] = user | |
} | |
// 当用户登出或超时时调用 | |
fun onUserSignOut(sessionId: String) { | |
userMap.remove(sessionId) | |
} | |
fun getUser(sessionId: String): User? = userMap[sessionId] | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment