Skip to content

Instantly share code, notes, and snippets.

@andrewgazelka
Created December 26, 2018 15:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andrewgazelka/b8170e452fa3dd0c0fb6d3875dc502ee to your computer and use it in GitHub Desktop.
Save andrewgazelka/b8170e452fa3dd0c0fb6d3875dc502ee to your computer and use it in GitHub Desktop.
package com.simplyservers.simplerestartbukkit.threads
import com.simplyservers.simplerestartbukkit.SimpleRestartBukkit
import org.apache.commons.collections4.queue.CircularFifoQueue
import java.util.concurrent.TimeUnit
class MemoryThread(
private val thresholdMemmory: Double,
memorySamples: Int,
val delaySampleSeconds: Long,
val onActivation: MemoryThread.() -> Unit
) : Thread() {
private val memoryPercents = CircularFifoQueue<Double>(memorySamples)
override fun run() {
while (!isInterrupted) {
val memoryUsed = getMemoryUsed()
if (memoryUsed > thresholdMemmory) {
SimpleRestartBukkit.instance.logger.warning("Memory used: $memoryUsed is over the threshold $thresholdMemmory")
}
memoryPercents.add(memoryUsed)
try {
TimeUnit.SECONDS.sleep(delaySampleSeconds)
} catch (e: InterruptedException) {
return
}
if (memoryPercents.isFull && memoryPercents.min() ?: 0.0 > thresholdMemmory) {
onActivation()
break
}
}
}
}
fun getMemoryUsed(): Double {
val max = Runtime.getRuntime().maxMemory()
val free = Runtime.getRuntime().freeMemory()
val used = max - free
return used.toDouble() / max.toDouble()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment