ClientHolder.kt 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. package co.id.datacomsolusindo.ipphonebridge
  2. import kotlinx.coroutines.*
  3. import kotlinx.coroutines.sync.Mutex
  4. import kotlinx.coroutines.sync.withLock
  5. import java.time.LocalDateTime
  6. import java.time.format.DateTimeFormatter
  7. import java.util.concurrent.ConcurrentHashMap
  8. import java.util.concurrent.ConcurrentMap
  9. import kotlin.system.measureTimeMillis
  10. object ClientHolder {
  11. private val mutexSucReq = Mutex()
  12. private val clientMap: ConcurrentMap<String, Client> by lazy { ConcurrentHashMap() }
  13. private suspend fun massiveRun(action: suspend () -> Unit) {
  14. measureTimeMillis {
  15. coroutineScope { // sc
  16. launch {
  17. action()
  18. }
  19. }
  20. }
  21. }
  22. fun removeBySessionId(sessionId: String?) {
  23. clientMap.entries.filter { it.value.sessionId == sessionId }.forEach {
  24. clientMap.remove(it.key)
  25. //unsubscribe incoming data
  26. }
  27. }
  28. fun put(key: String, client: Client) {
  29. clientMap.getOrPut(key) { client }
  30. //subscribe incoming data
  31. }
  32. fun get() = clientMap
  33. fun addFailedRequest(clNum: String) {
  34. runBlocking {
  35. withContext(Dispatchers.Default) {
  36. massiveRun {
  37. mutexSucReq.withLock {
  38. val cl = clientMap[clNum]
  39. if (cl != null) {
  40. cl.lastRequest =
  41. LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS"))
  42. cl.reqFailed += 1
  43. }
  44. }
  45. }
  46. }
  47. }
  48. }
  49. fun addSuccessRequest(clNum: String, duration: Double) {
  50. runBlocking {
  51. withContext(Dispatchers.Default) {
  52. massiveRun {
  53. // protect each increment with lock
  54. mutexSucReq.withLock {
  55. val cl = clientMap[clNum]
  56. if (cl != null) {
  57. cl.lastRequest =
  58. LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS"))
  59. cl.avgReqSuccessTime =
  60. ((cl.avgReqSuccessTime * cl.reqSuccess) + duration) / (cl.reqSuccess + 1)
  61. cl.reqSuccess += 1
  62. }
  63. }
  64. }
  65. }
  66. }
  67. }
  68. }