我想迭代我的DelayQueue中未过期的元素。事务类实现Delayed,并有一个字段时间戳,表示事务以UTC(而不是当前时间戳)发起时的时间戳
public class Transaction implements Delayed {
private final Double amount;
private final Long timestamp; //timestamp of a time when the item was created and send here
public Transaction(double amount, long timestamp) {
this.amount = amount;
this.timestamp = timestamp;
}
@Override
public long getDelay(TimeUnit unit) {
long delay = unit.convert(ONEMINUTE - (System.currentTimeMillis() - timestamp), TimeUnit.MILLISECONDS);
return delay;
}
@Override
public int compareTo(Delayed delayed) {
if (delayed == this) {
return 0;
}
if (delayed instanceof Transaction) {
return 0;
}
long diff = (getDelay(TimeUnit.MILLISECONDS) - delayed.getDelay(TimeUnit.MILLISECONDS));
return ((diff == 0) ? 0 : ((diff < 0) ? -1 : 1));
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + timestamp.hashCode();
return result;
}
@Override
public boolean equals( Object obj ) {
if( this == obj ) {
return true;
}
if( obj == null ) {
return false;
}
if( !( obj instanceof Transaction ) ) {
return false;
}
final Transaction other = ( Transaction )obj;
return timestamp.equals(other.timestamp);
}
}
如果新来的事务小于1分钟,则下面的TransactionManager类将传入事务添加到队列中。在getStatistics上,旧的事务应该从队列中删除,队列应该只包含1分钟以内的事务
public class TransactionManager {
private DelayQueue<Transaction> transactions;
public TransactionManager() {
transactions = new DelayQueue<>();
System.setProperty("user.timezone", "UTC");
}
public Object createTransaction(String json) {
JSONObject jsonObject = null;
try {
jsonObject = JsonValidator.validateTransactionJson(json);
} catch (Exception ex) {
return new ResponseEntity(HttpStatus.UNPROCESSABLE_ENTITY);
}
long delay = System.currentTimeMillis() - ((Long) jsonObject.get(TIMESTAMP));
if (delay > ONEMINUTE) {
return new ResponseEntity(HttpStatus.NO_CONTENT);
}
transactions.add(new Transaction((Double) jsonObject.get(AMOUNT), (Long) jsonObject.get(TIMESTAMP)));
return new ResponseEntity(HttpStatus.OK);
}
public long getStatistics() {
List<Transaction> tempForCleaning = new ArrayList<>();
transactions.drainTo(tempForCleaning);
tempForCleaning.clear();
StatisticJSON statistics = new StatisticJSON();
transactions.stream().forEach(transaction -> {
statistics.setCount(statistics.getCount() + 1);
});
return statistics.getCount();
}
}
在这个测试中,我创建了5个事务,时间为40秒之前,以及之前10秒的3个事务。因此,在等待45秒后,应排空前5个,并且队列应仅包含3个事务,但是,方法drainTo仅删除1个旧事务。
@Test
public void test() {
DateTime dateTime = new DateTime(DateTimeZone.UTC);
long fortyMilliSecondsAgo = dateTime.minusSeconds(40).getMillis();
long twentyMilliSecondsAgo = dateTime.minusSeconds(10).getMillis();
for (int i = 0; i < 5; i++) {
createTransaction(fortyMilliSecondsAgo);
}
for (int i = 0; i < 3; i++) {
createTransaction(twentyMilliSecondsAgo);
}
Assert.assertTrue(transactionManager.getStatistics() == 8);
try {
TimeUnit.SECONDS.sleep(45);
System.out.println("\n\n\n");
Assert.assertTrue(transactionManager.getStatistics() == 3);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private void createTransaction(long timestamp) {
transactionManager.createTransaction("{\"amount\":100.0,\"timestamp\":" + timestamp + "}");
}
我错过了什么,为什么drainTo只删除一个过期的项目,即使剩下4个,但无法捕捉到...
if (delayed instanceof Transaction) { return 0; }
看起来不对 - 如果你想让compareTo
与getDelay()
保持一致,你应该删掉那一点。所以你的方法可能看起来像这样(使用静态导入):
public int compareTo(Delayed delayed) {
return delayed == this
? 0
: Long.compare(getDelay(MILLISECONDS), delayed.getDelay(MILLISECONDS));
}