public void await ( int ID ) throws InterruptedException { if ( parties == 1 ) //what are you doing?! return ; final boolean startCondition = competitionCondition ; int competingFor = ( locks . length * 2 - 1 - ID ) / 2 ; while ( competingFor >= 0 ) { final Lock node = locks [ competingFor ] ; if ( node . tryLock ( ) ) //we lose, must wait { synchronized ( node ) //ignore warning, its correct. We are using the lock both for competition AND to do an internal wait { while ( competitionCondition == startCondition ) node . wait ( ) ; } node . unlock ( ) ; wakeUpTarget ( competingFor * 2 + 1 ) ; wakeUpTarget ( competingFor * 2 + 2 ) ; return ; } else //we win, comete for another round! { if ( competingFor == 0 ) break ; //we have won the last round! competingFor = ( competingFor - 1 ) / 2 ; } } //We won! Inform the losers competitionCondition = ! competitionCondition ; wakeUpTarget ( 0 ) ; //biggest loser }
Waits for all threads to reach this barrier .