Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

In the following code, consider the method decide, which is intended to be used

ID: 3564678 • Letter: I

Question

In the following code, consider the method decide, which is intended to be used by two threads. a) Does it satisfy the consensus and validity conditions of the consensus problem for two threads? Explain clearly. b) Is this a consensus protocol? Explain clearly.

import java.util.concurrent.atomic.AtomicInteger;
public class Consensus {
private boolean[] test = new boolean[2];
private int who;
private boolean set = false;
private boolean result;


public boolean decide(boolean value) {
int myId = ThreadId.get();
int otherId = 1 - myId;
test[myId] = true;
who = myId;
if (!(test[otherId] && who == myId)) {
if (set) {
return result;
}
set = true;
result = value;
test[myId] = false;
return value;
}
return value;
}
}

class ThreadId {
private static final AtomicInteger nextId = new AtomicInteger(0);
private static final ThreadLocal<Integer> threadId =
new ThreadLocal<Integer>() {
@Override protected Integer initialValue() {
return nextId.getAndIncrement();
}
};
public static int get() {
return threadId.get();
}
}

Explanation / Answer

It satisfies Consensus protocol for two threads, as its clearly mentioned in code, 1 thread id is generated in class ThreadId, and the other thread id is specified by Otherid = 1 - myId;
Answering the second question - this is consensus protocol, and we check this by using a Check class -

public class Check {

   public static void main(String[] args) {
       Consensus obj = new Consensus();
       Consensus obj1 = new Consensus();

       System.out.println(obj.decide(true) && obj.decide(true));
       System.out.println(obj.decide(false));
       System.out.println(true);
       System.out.println(obj.decide(true) && obj.decide(false));
      
       System.out.println(obj1.decide(false) && obj1.decide(true));
       System.out.println(obj1.decide(true));
       System.out.println(false);
       System.out.println(obj1.decide(false) && obj1.decide(false));

   }

}


The output for the first object obj is-
true
true
true
true

The output for second object obj1 is -
false
false
false
false

Decide class creates a new thread each time the System.out.print statement is run, and all statements for an object gets same output - Showing a consensus.

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote