Search code examples
javamultithreadingnetwork-programmingdistributed-computing

How to make Thread constructor take values from LinkedHashMap


I am working on an assignment for a Distributed Systems module which involves simulating a push gossiping protocol with multiple threads in Java.

My program takes a .txt file in adjacency list format ("node: neighbour1, neighbour2, etc."):

1:2,4,6
2:1,3,4,5
.
.
.

And creates a LinkedHashMap with K = node, V = String(of all neighbors), which looks like:

{1=2,4,6, 2=1,3,4,5 ...}

To be more specific the LinkedHashMap has K = String, V = String.

From this map I can create a List with nodes with the Map method map.keySet(), and a separate list with neighbors with the map.values() method. I can also create an Array of type String, or String[] of neighbours.

Each node can only communicate with its neighbors which are defined as values in the LinkedHashMap.

Gossip (push) protocol: Assume one node has the information initially. The informed node sends the info to a randomly selected neighbor, drawn from it's set of neighbors (with replacement). The initial node has to send the information via a separate interconnect thread. When the neighbor receives the information from the interconnect, it does the same thing as the initial node. In other words, it randomly selects a neighbor from its own set of neighbors and sends the info further via the interconnect. Eventually, everyone has the information and the protocol terminates.

My problem is the following: Given the LinkedHashMap, how can I instantiate a node on a key basis such that each node knows who is it neighbors? More directly, how can the constructor for the Node Thread take a specific Key with a specific Value from the LinkedHashMap?

When I try something like this, it gives me the entire list of neighbors, and not those specific to the node.

public Node extends Thread {
    public Node(Integer ID, List<String> neighbors){
    }
}

*Addition:**

I was asked to clarify what "communicate" implies. Please see this video from Coursera:

https://www.coursera.org/learn/cloud-computing/lecture/5AOex/1-2-the-gossip-protocol


Solution

  • If you want to pass a key-value pair from a Map to a constructor or a method, you can do this:

    public Node extends Thread {
        public Node(Map.Entry<String, String> entry) {
            String id = entry.getKey();
            String neighbors = entry.getValue();
    
            // ...
        }
    }
    

    And then you can call it the way you want.

    for (Map.Entry<String, String> entry : map.entrySet()) {
        Node node = new Node(entry);
    }
    

    Map.entrySet

    Map.Entry