Skip to content

Instantly share code, notes, and snippets.

@gyakkun
Last active January 29, 2023 07:48
Show Gist options
  • Save gyakkun/0269aab594f843782c699179d5b71cd9 to your computer and use it in GitHub Desktop.
Save gyakkun/0269aab594f843782c699179d5b71cd9 to your computer and use it in GitHub Desktop.
NavigableSet.POC.java
import java.time.Instant;
import java.util.*;
import java.util.concurrent.ConcurrentSkipListSet;
class Scratch {
public static void main(String[] args) throws InterruptedException {
for (int i = 0; ; i++) {
NavigableSet<IssuedPassword> goodSet = goodNavigableSet();
NavigableSet<IssuedPassword> badSet = badNavigableSet();
NavigableSet<IssuedPassword> pwset = badSet;
String pw = UUID.randomUUID().toString();
String component = UUID.randomUUID().toString();
IssuedPassword a = IssuedPassword.of(pw, component);
Thread.sleep(500);
IssuedPassword c = IssuedPassword.of(UUID.randomUUID().toString(), UUID.randomUUID().toString());
Thread.sleep(500);
IssuedPassword b = IssuedPassword.of(pw, component);
pwset.add(a);
pwset.add(c);
pwset.add(b);
if (pwset.size() == 3) {
System.err.println("Hit!: " + i);
goodSet.add(a);
goodSet.add(c);
goodSet.add(b);
if (goodSet.size() == 2) {
System.err.println("Good set wins!");
} else {
System.err.println("Good set loses!");
}
return;
}
}
}
private static Comparator<IssuedPassword> cpr = (a, b) -> a.pw.equals(b.pw) ? 0 : a.timestamp.compareTo(b.timestamp);
private static NavigableSet<IssuedPassword> badNavigableSet() {
// The latest pw should be first iterated
return new ConcurrentSkipListSet<>(cpr);
}
private static NavigableSet<IssuedPassword> goodNavigableSet() {
return Collections.synchronizedNavigableSet(new TreeSet(cpr));
}
}
class IssuedPassword {
public final String pw;
public final String component;
public final Instant timestamp;
private IssuedPassword(String pw, String component, Instant timestamp) {
this.pw = pw;
this.component = component;
this.timestamp = timestamp;
}
public static IssuedPassword of(String pw, String component) {
return new IssuedPassword(pw, component, Instant.now());
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
IssuedPassword that = (IssuedPassword) o;
return pw.equals(that.pw) && component.equals(that.component);
}
@Override
public int hashCode() {
return Objects.hash(pw, component);
}
@Override
public String toString() {
return "IssuedPassword{" +
"pw='" + pw + '\'' +
", component='" + component + '\'' +
", timestamp=" + timestamp +
'}';
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment