All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.sghd.common.utils.concurrent.DelayedElement Maven / Gradle / Ivy

The newest version!
package com.sghd.common.utils.concurrent;

import java.util.Date;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

/**
 * 延时元素对象
 */
public class DelayedElement implements Delayed {

	/** 元素内容 */
	private T content;
	/** 过期时间 */
	private Date end;

	public static  DelayedElement valueOf(T content, Date end) {
		return new DelayedElement(content, end);
	}

	public DelayedElement(T content, Date end) {
		this.content = content;
		this.end = end;
	}

	public T getContent() {
		return content;
	}

	public Date getEnd() {
		return end;
	}
	
	public void setContent(T content) {
		this.content = content;
	}

	public void setEnd(Date end) {
		this.end = end;
	}

	@Override
	public long getDelay(TimeUnit timeUnit) {
		long now = System.currentTimeMillis();
		long delay = end.getTime() - now;
		switch (timeUnit) {
		case MILLISECONDS:
			return delay;
		case SECONDS:
			return TimeUnit.MILLISECONDS.toSeconds(delay);
		case MINUTES:
			return TimeUnit.MILLISECONDS.toMinutes(delay);
		case HOURS:
			return TimeUnit.MILLISECONDS.toHours(delay);
		case DAYS:
			return TimeUnit.MILLISECONDS.toDays(delay);
		case MICROSECONDS:
			return TimeUnit.MILLISECONDS.toMicros(delay);
		case NANOSECONDS:
			return TimeUnit.MILLISECONDS.toNanos(delay);
		}
		return delay;
	}

	@Override
	public int compareTo(Delayed o) {
		long delay1 = this.getDelay(TimeUnit.MILLISECONDS);
		long delay2 = o.getDelay(TimeUnit.MILLISECONDS);
		int result = Long.valueOf(delay1).compareTo(Long.valueOf(delay2));
		if (result != 0) {
			return result;
		}
		// 时间判断无法区分时,执行如下判断(用于维持 compareTo 的使用约束)
		if (this.equals(o)) {
			return 0;
		} else {
			return this.hashCode() - o.hashCode();
		}
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((content == null) ? 0 : content.hashCode());
		return result;
	}

	@SuppressWarnings("rawtypes")
	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		DelayedElement other = (DelayedElement) obj;
		if (content == null) {
			if (other.content != null)
				return false;
		} else if (!content.equals(other.content))
			return false;
		return true;
	}
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy