public int getDistance ( Node node1 , Node node2 ) { if ( node1 == node2 ) { return 0 ; } Node n1 = node1 , n2 = node2 ; int dis = 0 ; netlock . readLock ( ) . lock ( ) ; try { int level1 = node1 . getLevel ( ) , level2 = node2 . getLevel ( ) ; while ( n1 != null && level1 > level2 ) { n1 = n1 . getParent ( ) ; level1 -- ; dis ++ ; } while ( n2 != null && level2 > level1 ) { n2 = n2 . getParent ( ) ; level2 -- ; dis ++ ; } while ( n1 != null && n2 != null && n1 . getParent ( ) != n2 . getParent ( ) ) { n1 = n1 . getParent ( ) ; n2 = n2 . getParent ( ) ; dis += 2 ; } } finally { netlock . readLock ( ) . unlock ( ) ; } if ( n1 == null ) { LOG . warn ( "The cluster does not contain node: " + NodeBase . getPath ( node1 ) ) ; return Integer . MAX_VALUE ; } if ( n2 == null ) { LOG . warn ( "The cluster does not contain node: " + NodeBase . getPath ( node2 ) ) ; return Integer . MAX_VALUE ; } return dis + 2 ; }
Return the distance between two nodes It is assumed that the distance from one node to its parent is 1 The distance between two nodes is calculated by summing up their distances to their closest common ancestor .