Field synchronizer technical improvements

This commit is contained in:
DBotThePony 2022-10-03 18:27:14 +07:00
parent 04c9d8ddfe
commit f586f12b90
Signed by: DBot
GPG Key ID: DCC23B5715498507

View File

@ -242,7 +242,8 @@ class FieldSynchronizer(private val callback: Runnable, private val alwaysCallCa
) )
} }
private val endpoints = ArrayList<WeakReference<Endpoint>>() private var endpointsMaxCapacity = 1
private val endpoints = ArrayList<WeakReference<Endpoint>>(1)
val defaultEndpoint = Endpoint() val defaultEndpoint = Endpoint()
private var lastEndpointsCleanup = System.nanoTime() private var lastEndpointsCleanup = System.nanoTime()
@ -270,17 +271,23 @@ class FieldSynchronizer(private val callback: Runnable, private val alwaysCallCa
execute.invoke(endpoint) execute.invoke(endpoint)
} }
} }
if (endpoints.size < endpointsMaxCapacity / 2) {
endpoints.trimToSize()
endpointsMaxCapacity = endpoints.size
}
} }
} }
inner class Endpoint { inner class Endpoint {
init { init {
synchronized(endpoints) {
endpoints.add(WeakReference(this)) endpoints.add(WeakReference(this))
endpointsMaxCapacity = endpointsMaxCapacity.coerceAtLeast(endpoints.size)
if (System.nanoTime() - lastEndpointsCleanup >= 60_000_000_000) { if (System.nanoTime() - lastEndpointsCleanup >= 60_000_000_000) {
lastEndpointsCleanup = System.nanoTime() lastEndpointsCleanup = System.nanoTime()
synchronized(endpoints) {
val iterator = endpoints.listIterator() val iterator = endpoints.listIterator()
for (value in iterator) { for (value in iterator) {
@ -288,6 +295,11 @@ class FieldSynchronizer(private val callback: Runnable, private val alwaysCallCa
iterator.remove() iterator.remove()
} }
} }
if (endpoints.size < endpointsMaxCapacity / 2) {
endpoints.trimToSize()
endpointsMaxCapacity = endpoints.size
}
} }
} }
} }
@ -515,6 +527,7 @@ class FieldSynchronizer(private val callback: Runnable, private val alwaysCallCa
if (!isDirty && !codec.compare(remote, value)) { if (!isDirty && !codec.compare(remote, value)) {
notifyEndpoints(this) notifyEndpoints(this)
isDirty = true isDirty = true
remote = codec.copy(value)
} }
} }
@ -534,7 +547,6 @@ class FieldSynchronizer(private val callback: Runnable, private val alwaysCallCa
val value = value val value = value
codec.write(stream, value) codec.write(stream, value)
isDirty = false isDirty = false
remote = codec.copy(value)
} }
override fun read(stream: DataInputStream) { override fun read(stream: DataInputStream) {