Kounavi
Kounavi

Reputation: 1121

Phaser issues (using JSR166y with latest JDK of version 6)

So, I've got this Phaser that is really flexible but it seems I am missing something.
I have successfully used CyclicBarrier but now I also want something more flexible as I said. So here is the code:

Declarations:

private static final CountDownLatch synchronizer = new CountDownLatch(1);
private static AtomicBoolean HAS_TIMED_OUT = new AtomicBoolean(false);


Code:

try {
    logger.INFO("CONNECTED - Peer ID properties: " + SYS_NEWLINE + peerSocket + SYS_NEWLINE + pID, true);

    final int peerKQueries = sp.getInteger(peerSocket);
    peerObjects = new String[peerKQueries];
    peerValues = new BigDecimal[peerKQueries];
    for ( int i = 0; i < peerObjects.length; i++ )
       peerObjects[i] = sp.getString(peerSocket);
    for ( int i = 0; i < peerValues.length; i++ )
       peerValues[i] = sp.getBigDecimal(peerSocket);

    final int phase1a = htPhaser1a.arrive();
    if ( phase1a < 0 ) {
        logger.ERROR("Rejecting Super Peer thread " + THREAD_ID + " because it arrived lately for Phase 1a!", true);
        sp.close(peerSocket);
        throw new IllegalThreadStateException();
    } else {
        logger.INFO(pID + " -> Arrived in HT phase 1a. Total arrivals: "+htPhaser1a.getArrivedParties(), true);
        logger.INFO("Super Peer thread " + THREAD_ID + " will advance to HT Phase 1b/2 (phase number is "+phase1a+").", true);
        // The last peer should also unblock the barrier.
        if ( htPhaser1a.getArrivedParties() == TOTAL_PEERS.get() ) {
          htPhaser1a.arrive();
          synchronizer.countDown();
        }
            htPhaser1a.awaitAdvanceInterruptibly(phase1a, 30, TimeUnit.SECONDS);
    }

} catch (IOException e) {
    logger.ERROR("Super Peer thread " + THREAD_ID + " encountered an I/O error.", true);
    sp.close(peerSocket);
    throw new IllegalThreadStateException();
} catch (TimeoutException e) {
    logger.INFO("Super Peer thread " + THREAD_ID + " timed out but will advance to HT Phase 1b/2.", true);
    if ( HAS_TIMED_OUT.compareAndSet(false, true) ) {
        logger.INFO("Parties NOT arrived in the timeout: "+(htPhaser1a.getUnarrivedParties()-1), true);
        resetCriticalData(htPhaser1a.getArrivedParties());
        htPhaser1a.forceTermination();
        instantiateHTPhase1b();
        instantiateHTPhase2();
        instantiateHTPatch();
        synchronizer.countDown();
    }
} finally {
    logger.INFO("Super Peer thread "+THREAD_ID+" is blocked!", true);
    synchronizer.await();
    logger.INFO("Super Peer thread's "+THREAD_ID+" blocking waived!", true);
}

sp.getSomething(); are I/O calls.
Take into consideration this code sample is being runned by multiple threads.

Here is my problem: I have ensured that no more than MAX_CLIENTS will arrive at phaser so if MAX_CLIENTS arrive all is well. However, I got an issue with TimeoutException. The first is a time window (aka race condition) that a client (say Thread A) will be able to arrive the phase, then a TimeoutException occurs in Thread B, I am instantiating dynamically another phaser in Thread B with the number of arrived parties (say 5), but then Thread A has already arrived at the phase (aka phase1a was not found to be < 0). How can I correct that? I was thinking of using a semaphore but I think it's not worth the effort because then I will problably need to rethink the way I do this. I've also thought about using a Timer and incrementing an AtomicInteger variable and when the timer expires instantiating dynamically the Phaser. Any ideas of how you would approach this problem?

EDIT:
The documentation has a bulkRegister(int parties) method but it is kind of oddly worded:

Adds the given number of new unarrived parties to this phaser. If an ongoing invocation of onAdvance(int, int) is in progress, this method may await its completion before returning. If this phaser has a parent, and the given number of parties is greater than zero, and this phaser previously had no registered parties, this child phaser is also registered with its parent. If this phaser is terminated, the attempt to register has no effect, and a negative value is returned.

Question:The word "may" confuses me! "May" as in might or "may" as in will?

EDIT:
Solved. Check my answer below.

Upvotes: 1

Views: 327

Answers (1)

Kounavi
Kounavi

Reputation: 1121

Declarations:

private static final CountDownLatch PEER = new CountDownLatch(1);
private static AtomicBoolean HAS_TIMED_OUT = new AtomicBoolean(false);
htPeerPhaser = new Phaser();


Code:

...
htPeerPhaser.register(); // Called only once.
...
// Note: Server application has guaranteed that no more than the maximum number of peers will arrive.
try {
    logger.INFO("CONNECTED - Peer ID properties: " + SYS_NEWLINE + peerSocket + SYS_NEWLINE + pID, true);
    final int peerKQueries = sp.getInteger(peerSocket);
    peerObjects = new String[peerKQueries];
    peerValues = new BigDecimal[peerKQueries];
    for ( int i = 0; i < peerObjects.length; i++ )
        peerObjects[i] = sp.getString(peerSocket);
    for ( int i = 0; i < peerValues.length; i++ )
        peerValues[i] = sp.getBigDecimal(peerSocket);
    final int registrationID = htPeerPhaser.bulkRegister(1);
    if ( registrationID < 0 ) {
        logger.ERROR("Rejecting Super Peer thread " + THREAD_ID + " because peer registration has stopped!", true);
        sp.close(peerSocket);
        throw new IllegalThreadStateException();
    }
    logger.INFO(pID + " -> Registered for HT phase 1.", true);
    logger.INFO("Super Peer thread " + THREAD_ID + " will advance to HT Phase 1/2.", true);
    // The last peer should also unblock the barrier.
    if ( htPeerPhaser.getRegisteredParties() == TOTAL_PEERS.get()+1 ) {
        htPeerPhaser.forceTermination();
        PEER.countDown();
    }
    htPeerPhaser.awaitAdvanceInterruptibly(registrationID, 30, TimeUnit.SECONDS);

} catch (IOException e) {
    logger.ERROR("Super Peer thread " + THREAD_ID + " encountered an I/O error.", true);
    sp.close(peerSocket);
    throw new IllegalThreadStateException();
} catch (TimeoutException e) {
    htPeerPhaser.forceTermination();
    logger.INFO("Super Peer thread " + THREAD_ID + " timed out but will advance to HT Phase 1b/2.", true);
    if ( HAS_TIMED_OUT.compareAndSet(false, true) && htPeerPhaser.getRegisteredParties() < TOTAL_PEERS.get()+1 ) {
        final int arrivedPeers = htPeerPhaser.getRegisteredParties()-1;
        logger.INFO("Parties that arrived before timeout: "+arrivedPeers, true);
        final int unarrivedPeers = TOTAL_PEERS.get()-arrivedPeers;
        logger.INFO("Parties NOT arrived due to timeout: "+unarrivedPeers, true);
        resetCriticalData(arrivedPeers);
        instantiateHTPhase1b();
        instantiateHTPhase2();
        instantiateHTPatch();
        PEER.countDown();
        logger.INFO("Super Peer thread " + THREAD_ID + " re-instantiated critical data.", true);
    }
}
logger.INFO("Super Peer thread "+THREAD_ID+" is blocked!", true);
PEER.await();
logger.INFO("Super Peer thread's "+THREAD_ID+" blocking waived!", true);

Upvotes: 1

Related Questions