Convert TimeLimitedCache to Kotlin

This commit is contained in:
tzugen 2021-05-27 11:13:23 +02:00
parent 38c1480f77
commit aa1c0d8baa
No known key found for this signature in database
GPG Key ID: 61E9C34BC10EC930
2 changed files with 31 additions and 61 deletions

View File

@ -1,61 +0,0 @@
/*
This file is part of Subsonic.
Subsonic is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Subsonic is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Subsonic. If not, see <http://www.gnu.org/licenses/>.
Copyright 2009 (C) Sindre Mehus
*/
package org.moire.ultrasonic.util;
import java.lang.ref.SoftReference;
import java.util.concurrent.TimeUnit;
/**
* @author Sindre Mehus
* @version $Id$
*/
public class TimeLimitedCache<T>
{
private SoftReference<T> value;
private final long ttlMillis;
private long expires;
public TimeLimitedCache(long ttl, TimeUnit timeUnit)
{
this.ttlMillis = TimeUnit.MILLISECONDS.convert(ttl, timeUnit);
}
public T get()
{
return System.currentTimeMillis() < expires ? value.get() : null;
}
public void set(T value)
{
set(value, ttlMillis, TimeUnit.MILLISECONDS);
}
public void set(T value, long ttl, TimeUnit timeUnit)
{
this.value = new SoftReference<T>(value);
expires = System.currentTimeMillis() + timeUnit.toMillis(ttl);
}
public void clear()
{
expires = 0L;
value = null;
}
}

View File

@ -0,0 +1,31 @@
/*
* TimeLimitedCache.kt
* Copyright (C) 2009-2021 Ultrasonic developers
*
* Distributed under terms of the GNU GPLv3 license.
*/
package org.moire.ultrasonic.util
import java.lang.ref.SoftReference
import java.util.concurrent.TimeUnit
class TimeLimitedCache<T>(expiresAfter: Long = 60L, timeUnit: TimeUnit = TimeUnit.MINUTES) {
private var value: SoftReference<T>? = null
private val expiresMillis: Long = TimeUnit.MILLISECONDS.convert(expiresAfter, timeUnit)
private var expires: Long = 0
fun get(): T? {
return if (System.currentTimeMillis() < expires) value!!.get() else null
}
@JvmOverloads
fun set(value: T, ttl: Long = expiresMillis, timeUnit: TimeUnit = TimeUnit.MILLISECONDS) {
this.value = SoftReference(value)
expires = System.currentTimeMillis() + timeUnit.toMillis(ttl)
}
fun clear() {
expires = 0L
value = null
}
}