alvinalexander.com | career | drupal | java | mac | mysql | perl | scala | uml | unix  

Java example source code file (RoundCount.java)

This example Java source code file (RoundCount.java) is included in the alvinalexander.com "Java Source Code Warehouse" project. The intent of this project is to help you "Learn Java by Example" TM.

Learn more about this Java project at its project page.

Java - Java tags/keywords

reentrantreadwritelock, roundcount

The RoundCount.java Java example source code

package org.deeplearning4j.models.glove.count;

import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * Simple circular counter, that circulates within 0...Limit, both inclusive
 *
 * @author raver119@gmail.com
 */
public class RoundCount {

    private  int limit = 0;
    private int lower = 0;
    private int value = 0;

    private ReentrantReadWriteLock lock = new ReentrantReadWriteLock();

    /**
     * Creates new RoundCount instance.
     *
     * @param limit Maximum top value for this counter. Inclusive.
     */
    public RoundCount(int limit) {
        this.limit = limit;
    }

    /**
     * Creates new RoundCount instance.
     *
     * @param lower - Minimum value for this counter. Inclusive
     * @param top - Maximum value for this counter. Inclusive.
     */
    public RoundCount(int lower, int top) {
        this.limit = top;
        this.lower = lower;
    }

    public int previous() {
        try {
            lock.readLock().lock();
            if (value == lower) return limit;
                else return value - 1;
        } finally {
            lock.readLock().unlock();
        }
    }

    public int get() {
        try {
            lock.readLock().lock();
            return value;
        } finally {
            lock.readLock().unlock();
        }
    }

    public void tick() {
        try {
            lock.writeLock().lock();
            if (value == limit) value = lower;
                else value++;
        } finally {
            lock.writeLock().unlock();
        }
    }
}

Other Java examples (source code examples)

Here is a short list of links related to this Java RoundCount.java source code file:

... this post is sponsored by my books ...

#1 New Release!

FP Best Seller

 

new blog posts

 

Copyright 1998-2021 Alvin Alexander, alvinalexander.com
All Rights Reserved.

A percentage of advertising revenue from
pages under the /java/jwarehouse URI on this website is
paid back to open source projects.