-
-
Save jwne/fd37b68704690635ce54 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 co.ryred.rybot; | |
import java.util.HashMap; | |
import java.util.Iterator; | |
import java.util.Map; | |
import java.util.concurrent.ConcurrentHashMap; | |
import java.util.concurrent.TimeUnit; | |
/** | |
* Created by rissa on 01/07/2015. | |
*/ | |
public class CooldownUtil { | |
private static CooldownUtil __INSTANCE__ = null; | |
private static long cooldownTime = TimeUnit.SECONDS.toMillis(500); | |
private final ConcurrentHashMap<String, Long> cooldownMap; | |
private long lastPurged = 0; | |
public static CooldownUtil getCooldown(){ | |
return __INSTANCE__ == null ? (__INSTANCE__ = new CooldownUtil()) : __INSTANCE__; | |
}; | |
public static void setCooldownTime(TimeUnit timeUnit, long cooldownTime){ | |
CooldownUtil.cooldownTime = timeUnit.toMillis(cooldownTime); | |
}; | |
public static String userStringPlease(String sender, String login, String hostname) { | |
return new StringBuilder(sender).append(login).append(hostname).toString(); | |
} | |
private CooldownUtil(){ | |
this.cooldownMap = new ConcurrentHashMap<String, Long>(); | |
} | |
public void chillBabes( String sender, String login, String hostname ) { | |
String user = userStringPlease(sender, login, hostname); | |
long time = System.currentTimeMillis() + cooldownTime; | |
cooldownMap.put(user, time); | |
} | |
public boolean isChilling( String sender, String login, String hostname ) { | |
String user = userStringPlease(sender, login, hostname); | |
long time = System.currentTimeMillis(); | |
long userTime = cooldownMap.getOrDefault(user, time - 300); | |
return (time - userTime) < 0; | |
} | |
public synchronized void purge() { | |
long time = System.currentTimeMillis(); | |
lastPurged = System.currentTimeMillis(); | |
if( time - lastPurged ) | |
Iterator<Map.Entry<String, Long>> iterator = cooldownMap.entrySet().iterator(); | |
while( iterator.hasNext() ) | |
if( (time - iterator.next().getValue()) < 0 ) iterator.remove(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment