【问题标题】:Implementing a consensus protocol using a FIFO queue and peek() method使用 FIFO 队列和 peek() 方法实现共识协议
【发布时间】:2015-12-18 20:40:15
【问题描述】:

我需要实现一个使用带有 peek() 方法的队列的共识协议,以表明可以为任意数量的线程达成共识,即带有 peek() 方法的队列具有无限共识编号

这是我的代码

import java.util.LinkedList;
import java.util.Queue;
public class PeekConsensus extends ConsensusProtocol<Integer>   
{
    Queue<Integer> queue ;
    public PeekConsensus(int threadCount)   
    {
        super(threadCount); //threadCount is a command line argument from the main class specifying the number of threads to handle this process 
        queue = new LinkedList<Integer>() //FIFO queue
    }

    public Integer decide(Integer value)    
    {
        this.propose(value); // stores "value" in a vector named proposed, at index ThreadID.get()  
        int i = ThreadID.get() ;
        queue.add(i) 
        System.out.println("Thread " + i + " : " + i) ; // Required by specifications to print thread id and the value added when an item is enqueued 
        System.out.println("Thread " + i + " : " + queue.peek()) ; // Required by specifications to print thread id and the value of peek() when when peek() is called
        return proposed.elementAt(queue.peek()) ;

    }   
}

据我了解,这应该可行,因为如果两个线程返回不同的值,peek() 将不得不返回不同的线程 ID,并且确保有效性,因为每个线程在推送其线程 ID 之前将其自己的值写入提议。

是否有人能够找出我哪里出错并指导我纠正我的代码

【问题讨论】:

  • 我们必须先知道它有什么问题。
  • 不清楚您看到的是什么错误,但一个问题可能是 LinkedList 不是线程安全的。使用 Queue 的线程安全变体可能会有所帮助。
  • 将新的 LinkedList 更改为新的 LinkedBlockingQueue() 可能会让你走到一半……

标签: java multithreading fifo consensus


【解决方案1】:

协议对我来说看起来不错。但是你有没有想过peek()是如何实现的? 由于peek() 实际上是pop() 后跟push(),因此我们在这段代码中可能存在错误的交错。 假设peek() 可以原子地执行,则此共识协议将起作用。

如何改变它?

为了让您的代码运行,您可以将synchronized 添加到peek(),但这会破坏共识协议的目的,因为持有锁的线程可能会死亡。

尝试使用AtomicReference。这使您可以原子地获取,甚至设置一个值。在这种情况下,指针将是head

现在问题来了:AtomicReference 是如何在 Java 中实现的。不幸的是,它是使用CAS 实现的,这再次违背了仅使用 FIFO 队列的共识协议的目的。

最后:正式而言,FIFO 队列的共识编号为 2。假设 peek() 以原子方式执行,您的协议是有效的。但是,正确的实现需要某种CASsynchronized

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-04-03
    • 2020-03-09
    • 2012-04-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多