diff --git a/src/main/kotlin/org/phoenixframework/Socket.kt b/src/main/kotlin/org/phoenixframework/Socket.kt index 4d3ddef..a954121 100644 --- a/src/main/kotlin/org/phoenixframework/Socket.kt +++ b/src/main/kotlin/org/phoenixframework/Socket.kt @@ -199,6 +199,7 @@ class Socket( * that contain the ref of the message to send and the callback that will send the message. */ internal var sendBuffer: MutableList Unit>> = ArrayList() + private val sendBufferLock = Any() /** Ref counter for messages */ internal var ref: Int = 0 @@ -415,7 +416,9 @@ class Socket( } else { // If the socket is not connected, add the push to a buffer which will // be sent immediately upon connection. - sendBuffer.add(Pair(ref, callback)) + synchronized(sendBufferLock) { + sendBuffer.add(Pair(ref, callback)) + } } } @@ -464,17 +467,21 @@ class Socket( /** Send all messages that were buffered before the socket opened */ internal fun flushSendBuffer() { - if (isConnected && sendBuffer.isNotEmpty()) { - this.sendBuffer.forEach { it.second.invoke() } - this.sendBuffer.clear() + synchronized(sendBufferLock) { + if (isConnected && sendBuffer.isNotEmpty()) { + this.sendBuffer.forEach { it.second.invoke() } + this.sendBuffer.clear() + } } } /** Removes an item from the send buffer with the matching ref */ internal fun removeFromSendBuffer(ref: String) { - this.sendBuffer = this.sendBuffer - .filter { it.first != ref } - .toMutableList() + synchronized(sendBufferLock) { + this.sendBuffer = this.sendBuffer + .filter { it.first != ref } + .toMutableList() + } } internal fun leaveOpenTopic(topic: String) {