FileDocCategorySizeDatePackage
AtomicScoreAndCharacter.javaAPI DocExample3017Tue Apr 06 08:46:30 BST 2004javathreads.examples.ch05.example3

AtomicScoreAndCharacter

public class AtomicScoreAndCharacter extends Object

Fields Summary
private AtomicReference
value
Constructors Summary
public AtomicScoreAndCharacter()

        this(0, -1);
    
public AtomicScoreAndCharacter(int initScore, int initChar)

        value = new AtomicReference<ScoreAndCharacter>
                    (new ScoreAndCharacter(initScore, initChar));
    
Methods Summary
public intgetCharacter()

        return value.get().getCharacter();
    
public intgetScore()

        return value.get().getScore();
    
public booleanprocessCharacter(int typedChar)

        ScoreAndCharacter origVal, newVal;
        int origScore, origCharacter;
        boolean retValue;

        while (true) {
            origVal = value.get();
            origScore = origVal.getScore();
            origCharacter = origVal.getCharacter();

            if (typedChar == origCharacter) {
                origCharacter = -1;
                origScore++;
                retValue = true;
            } else {
                origScore--;
                retValue = false;
            }

            newVal = new ScoreAndCharacter(origScore, origCharacter);
            if (value.compareAndSet(origVal, newVal)) break;
        }
        return retValue;
    
public voidset(int newScore, int newChar)

        value.set(new ScoreAndCharacter(newScore, newChar));
    
public voidsetCharacter(int newCharacter)

        ScoreAndCharacter origVal, newVal;

        while (true) {
            origVal = value.get();
            newVal = new ScoreAndCharacter
                         (origVal.getScore(), newCharacter);
            if (value.compareAndSet(origVal, newVal)) break;
        }
    
public voidsetCharacterUpdateScore(int newCharacter)

        ScoreAndCharacter origVal, newVal;
        int score;

        while (true) {
            origVal = value.get();
            score = origVal.getScore();
            score = (origVal.getCharacter() == -1) ? score : score-1;

            newVal = new ScoreAndCharacter (score, newCharacter);
            if (value.compareAndSet(origVal, newVal)) break;
        }
    
public voidsetScore(int newScore)

        ScoreAndCharacter origVal, newVal;

        while (true) {
            origVal = value.get();
            newVal = new ScoreAndCharacter
                         (newScore, origVal.getCharacter());
            if (value.compareAndSet(origVal, newVal)) break;
        }