import java.math.BigDecimal; import java.util.Collections; import java.util.LinkedHashSet; import java.util.Set; /** * Contains a method {@link ParallelIsOdd#isOdd} to determine if a number is odd using a safe * concurrent algorithm *
* The implementation is well commented */ public class ParallelIsOdd { /** * The is odd boolean * * @implNote volatile makes concurrency more reliable so this field is volatile */ // isOdd is flipped number times by the threads, to determine if number is odd static volatile boolean isOdd = true; /** * The is odd lock for safety * * @implNote volatile makes concurrency more reliable so this field is volatile */ /*package*/ static volatile Object theIsOddLock = new Object() { public String toString() { return "IsOddLock{isOdd: " + isOdd + "}"; } }; /** * Determines if a number is odd using an efficient and safe concurrent algorithm. *
* Runs in only O(n) time.
*
* @param number the number to determine if it is odd using an efficient and safe concurrent algorithm that runs
* in only O(n) time
* @return if the number parameter is odd, determined using an efficient and safe concurrent algorithm that runs
* in only O(n) time
*/
public static synchronized boolean isOdd(Number number) {
// un negate negative numbers
if (number.doubleValue() < 0) { // check if a number is negative
number = BigDecimal.valueOf(0 + -number.longValue()); //make the number non negative by negating the negative number
}
isOdd = false; //set the is odd boolean to false
// the collection to hold all the Threads, synchronized safely
Set