diff --git a/src/main/kotlin/ru/dbotthepony/mc/otm/compat/mekanism/Power.kt b/src/main/kotlin/ru/dbotthepony/mc/otm/compat/mekanism/Power.kt index 563cf18a8..17759e270 100644 --- a/src/main/kotlin/ru/dbotthepony/mc/otm/compat/mekanism/Power.kt +++ b/src/main/kotlin/ru/dbotthepony/mc/otm/compat/mekanism/Power.kt @@ -17,28 +17,54 @@ import java.util.WeakHashMap private val LOGGER = LogManager.getLogger() -// TODO: those are cached indefinitely, when, in fact, they can easily change +private class LazyCache(private val provider: () -> O, private val computer: (O) -> T) : Lazy { + private var cache: T? = null + private var observed: O? = null -private val mekanism2MtJ by lazy { + override fun isInitialized(): Boolean { + return cache != null + } + + override val value: T get() { + if (cache == null || observed == null || observed != provider.invoke()) { + observed = provider.invoke() + cache = computer.invoke(observed ?: throw ConcurrentModificationException()) + } + + return cache ?: throw ConcurrentModificationException() + } +} + +private class DoubleLazy(onion: () -> Lazy) : Lazy { + private val onion = lazy(onion) + override val value: T + get() = onion.value.value + + override fun isInitialized(): Boolean { + return onion.isInitialized() && onion.value.isInitialized() + } +} + +private val mekanism2MtJ by DoubleLazy lazy@{ try { val conf = MekanismConfig.general - return@lazy ImpreciseFraction.ONE / conf.forgeConversionRate.get().toImpreciseFraction() + return@lazy LazyCache(conf.forgeConversionRate::get) { ImpreciseFraction.ONE / it.toImpreciseFraction() } } catch(err: Throwable) { LOGGER.error("Unable to get Forge Energy to Mekanism Joules's conversion rate! Expect issues", err) } - return@lazy ImpreciseFraction.ONE + return@lazy lazyOf(ImpreciseFraction.ONE) } -private val mtj2Mekanism by lazy { +private val mtj2Mekanism by DoubleLazy lazy@{ try { val conf = MekanismConfig.general - return@lazy conf.forgeConversionRate.get().toImpreciseFraction() + return@lazy LazyCache(conf.forgeConversionRate::get) { it.toImpreciseFraction() } } catch(err: Throwable) { LOGGER.error("Unable to get Mekanism Joules's to Forge Energy conversion rate! Expect issues", err) } - return@lazy ImpreciseFraction.ONE + return@lazy lazyOf(ImpreciseFraction.ONE) } class Mekanism2MatteryEnergyWrapper(private val power: IStrictEnergyHandler) : IMatteryEnergyStorage {