Skip to content

Instantly share code, notes, and snippets.

@SilverCory
Created July 2, 2015 19:24
Show Gist options
  • Save SilverCory/48070b7f193448efbcf5 to your computer and use it in GitHub Desktop.
Save SilverCory/48070b7f193448efbcf5 to your computer and use it in GitHub Desktop.
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