Skip to content

Instantly share code, notes, and snippets.

@cesclong
Last active May 12, 2023 01:44
Show Gist options
  • Save cesclong/c83ddd81aa12611cdedd9027c55f20c5 to your computer and use it in GitHub Desktop.
Save cesclong/c83ddd81aa12611cdedd9027c55f20c5 to your computer and use it in GitHub Desktop.
ConcurrentHashMap日常使用的例子
/**
* 当有很多用户同时登入和登出时,
* 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