0

i am currently working on optimizing my code and i have this breadth-first search algorithm but it is a sequential one , i am wondering if i can make it run in parallel using an executor service , yet keeping the algorithm simple. thank you in advance

here is my sequential BFS

public void bfs(int rootNode, isvisited visitor)
{
    // BFS uses Queue data structure
    Queue<Integer> q = new LinkedList<Integer>();
    int currentLevel = 0;

    q.add(rootNode);
    visitor.visit(rootNode, currentLevel);

    while (!q.isEmpty())
    {
        currentLevel++;
        Set<Integer> nextNodes = new LinkedHashSet<Integer>();
        q.forEach(currNode ->nextNodes.addAll(outgoingNeighbors(currNode)));
        q.clear();

        for (int child : nextNodes) 
        {
            visitor.visit(child, currentLevel);
            q.add(child);
        }
    } 
}
  • For recurcively-natured tasks the [Fork-Join thread pool](https://docs.oracle.com/javase/tutorial/essential/concurrency/forkjoin.html) is the best choice. Try to rewrite your code using this approach. – rvit34 Mar 02 '17 at 14:46
  • i am not very familiar with the forkjoin framework , any idea where to start – user7562445 Mar 02 '17 at 14:51
  • I hope [this](http://www.oracle.com/technetwork/articles/java/fork-join-422606.html) and [this](http://supertech.csail.mit.edu/papers/pbfs.pdf) articles help you – rvit34 Mar 02 '17 at 15:13
  • And see the parallel DFS implemented in forkjoin framework [here](http://stackoverflow.com/questions/40324333/depth-first-search-in-parallel) – rvit34 Mar 02 '17 at 15:23

0 Answers0