summaryrefslogtreecommitdiffstats
path: root/vespalog/src/main/java/com/yahoo/log/LogMessageTimeComparator.java
blob: f11dc9ec139d35920156fe7898e32a8ef270a1a7 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
// Copyright 2016 Yahoo Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.log;

import java.io.Serializable;
import java.util.Comparator;

/**
 * Order LogMessage instances based on timestamp. The default ordering is ascending.
 * This may be reversed by the constructor argument.
 *
 * Note: this comparator imposes orderings that are inconsistent with equals.
 * This is due to only looking at the timestamp, so two different messages with
 * the same timestamp would appear "equal" to this comparator.
 *
 * @author vlarsen
 *
 */
public class LogMessageTimeComparator implements Comparator<LogMessage>, Serializable {
	private static final long serialVersionUID = 1L;

	/** Indicate the ordering of the timecomparison */
	private boolean ascending = true;

	/**
	 * Create a Time comparator for logmessages. Order is ascending.
	 *
	 */
	public LogMessageTimeComparator() {}

	/**
	 * Create a Time comparator for logmessages. The chronological order is dependent
	 * on the argument to the constructor.
	 *
	 * @param ascending true if you want LogMessages ordered ascending according to timestamp.
	 */
	public LogMessageTimeComparator(boolean ascending) {
		this.ascending = ascending;
	}

	public int compare(LogMessage message1, LogMessage message2) {
		return ascending ?
				Long.valueOf(message1.getTime()).compareTo(Long.valueOf(message2.getTime()))
				: Long.valueOf(message2.getTime()).compareTo(Long.valueOf(message1.getTime()));
	}
}