A few generic notes:
PrimeReserveInt
: I think it could be smaller with separated responsibilities. I would put the prime generation (and related) logic to a separate class and put the (prime)state reference and thread handling to another one. (What would you extract out if you wanted to change prime generation to another algorithm?)
I don't see any reason to use AtomicBoolean
instead of ReentrantLock
for locking. It supports tryLock
. (If there is a reason you should document it somehow.)
You could use a CountDownLatch
instead of the wait
/notify
.
private final CountDownLatch replaced = new CountDownLatch(1);
synchronized void waitReplaced() {
try {
replaced.await();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
synchronized void replaced() {
replaced.countDown();
}
See: Effective Java, 2nd edition, Item 69: Prefer concurrency utilities to wait and notify
containsPrime
could be containsNthPrime
(for consistency with getNthPrime
).
-
if (to <= 1) {
throw new IllegalArgumentException("Illegal range to " + to);
}
if (to > MAX_PRIME_ALLOWED) {
throw new IllegalArgumentException("Memory-limited to the largest prime " + MAX_PRIME_ALLOWED
+ " (which is the " + MAX_PRIME_NTH + "th prime)");
}
Validation would be readable with Guava's Preconditions
:
checkArgument(to > 1, "Illegal range to %s", to);
checkArgument(to <= MAX_PRIME_ALLOWED,
"Memory-limited to the largest prime %s (which is the %sth prime)",
MAX_PRIME_ALLOWED, MAX_PRIME_NTH);
(It could also save you a few string unnecessary string concatenation.)
In System.out.printf
use %n
instead of \n
. The former outputs the correct platform-specific line separator.
-
* NEVER Violate the prime directive!
It's not unambiguous who is this comment for. The client or the developer of PrimeReserveInt
? It's on a private field but sounds like a warning to clients of the class. As a client, what should I do?
This comment should be on the class declaration instead of the constructor:
/**
* ...
* This class is fully thread-safe.
* ...
*/
public PrimeReserveInt() {
...
}