-
-
Save andrewgazelka/b8170e452fa3dd0c0fb6d3875dc502ee to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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