Home Java javaTutorial Simple code example for Java thread-safe counter

Simple code example for Java thread-safe counter

Oct 12, 2017 am 09:59 AM
java Simple counter

This article mainly introduces Java thread-safe counter simple implementation code examples, which has certain reference value. Friends who need it can learn about it.

A piece of business code I was working on a few days ago required a variable to increment from 1 every day. For this purpose, I simply encapsulated a thread-safe counter, which allows a variable to increment from 1 every day. Of course, if the project is restarted during operation, even if the date is still the same day, the count will still start from 1. Therefore, it is more reliable to store the counter value in the database, but this does not affect the value of this code. It is posted now for the reference of those in need.


package com.hikvision.cms.rvs.common.util;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
/**
 * Created by lihong10 on 2017/8/9.
 * 一个循环计数器,每天从1开始计数,隔天重置为1。
 * 可以创建一个该类的全局对象,然后每次使用时候调用其get方法即可,可以保证线程安全性
 */
public class CircularCounter {
  private static final AtomicReferenceFieldUpdater<CircularCounter, AtomicInteger> valueUpdater =
      AtomicReferenceFieldUpdater.newUpdater(CircularCounter.class, AtomicInteger.class, "value");
  //保证内存可见性
  private volatile String key;
  //保证内存可见性
  private volatile AtomicInteger value;
  private static final String DATE_PATTERN = "yyyy-MM-dd";
  public CircularCounter() {
    /**
     * 这里将key设置为getCurrentDateString() + "sssssssssss" 是为了测试addAndGet()方法中日期发生变化的情况
     * 正常使用应该将key初始化为getCurrentDateString()
     */
    this.key = getCurrentDateString() + "sssssssssss";
    this.value = new AtomicInteger(0);
  }
  /**
   * 获取计数器加1以后的值
   *
   * @return
   */
  public Integer addAndGet() {
    AtomicInteger oldValue = value;
    AtomicInteger newInteger = new AtomicInteger(0);
    int newVal = -1;
    String newDateStr = getCurrentDateString();
    //日期一致,计数器加1后返回
    if (isDateEquals(newDateStr)) {
      newVal = add(1);
      return newVal;
    }
    //日期不一致,保证有一个线程重置技术器
    reSet(oldValue, newInteger, newDateStr);
    this.key = newDateStr;
    //重置后加1返回
    newVal = add(1);
    return newVal;
  }
  /**
   * 获取计数器的当前值
   * @return
   */
  public Integer get() {
    return value.get();
  }
  /**
   * 判断当前日期与老的日期(也即key成员变量记录的值)是否一致
   *
   * @return
   */
  private boolean isDateEquals(String newDateStr) {
    String oldDateStr = key;
    if (!isBlank(oldDateStr) && oldDateStr.equals(newDateStr)) {
      return true;
    }
    return false;
  }
  /**
   * 如果日期发生变化,重置计数器,也即将key设置为当前日期,并将value重置为0,重置后才能接着累加,
   */
  private void reSet(AtomicInteger oldValue, AtomicInteger newValue, String newDateStr) {
    if(valueUpdater.compareAndSet(this, oldValue, newValue)) {
      System.out.println("线程" + Thread.currentThread().getName() + "发现日期发生变化");
    }
  }
  /**
   * 获取当前日期字符串
   *
   * @return
   */
  private String getCurrentDateString() {
    Date date = new Date();
    String newDateStr = new SimpleDateFormat(DATE_PATTERN).format(date);
    return newDateStr;
  }
  /**
   * 计数器的值加1。采用CAS保证线程安全性
   *
   * @param increment
   */
  private int add(int increment) {
    return value.addAndGet(increment);
  }
  public static boolean isBlank(CharSequence cs) {
    int strLen;
    if(cs != null && (strLen = cs.length()) != 0) {
      for(int i = 0; i < strLen; ++i) {
        if(!Character.isWhitespace(cs.charAt(i))) {
          return false;
        }
      }
      return true;
    } else {
      return true;
    }
  }
  public static void test() {
    CircularCounter c = new CircularCounter();
    AtomicInteger count = new AtomicInteger(0);
    List<Thread> li = new ArrayList<Thread>();
    int size = 10;
    CountDownLatch latch1 = new CountDownLatch(1);
    CountDownLatch latch2 = new CountDownLatch(size);
    for (int i = 0; i < size; i++) {
      Thread t = new Thread(new CounterRunner(c, latch1, latch2, count), "thread-" + i);
      li.add(t);
      t.start();
    }
    System.out.println("start");
    latch1.countDown();
    try {
      latch2.await();
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
    System.out.println(count.get());
    System.out.println(c.get());
    if(count.get() == c.get()) {
      System.out.println("该计数器是线程安全的!!!");
    }
  }
  public static void main(String... args) {
    for(int i = 0; i < 15; i++) {
      test();
    }
  }
}
/**
 * 测试使用的Runnable对象
 */
class CounterRunner implements Runnable {
  private CircularCounter counter;
  private CountDownLatch latch1;
  private CountDownLatch latch2;
  private AtomicInteger count;
  public CounterRunner(CircularCounter counter, CountDownLatch latch1, CountDownLatch latch2, AtomicInteger count) {
    this.latch1 = latch1;
    this.latch2 = latch2;
    this.counter = counter;
    this.count = count;
  }
  @Override
  public void run() {
    try {
      latch1.await();
      System.out.println("****************");
      for (int i = 0; i < 20; i++) {
        counter.addAndGet();
        count.addAndGet(1);
      }
      latch2.countDown();
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
  }
}
Copy after login

Summary

The above is the detailed content of Simple code example for Java thread-safe counter. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Perfect Number in Java Perfect Number in Java Aug 30, 2024 pm 04:28 PM

Guide to Perfect Number in Java. Here we discuss the Definition, How to check Perfect number in Java?, examples with code implementation.

Random Number Generator in Java Random Number Generator in Java Aug 30, 2024 pm 04:27 PM

Guide to Random Number Generator in Java. Here we discuss Functions in Java with examples and two different Generators with ther examples.

Weka in Java Weka in Java Aug 30, 2024 pm 04:28 PM

Guide to Weka in Java. Here we discuss the Introduction, how to use weka java, the type of platform, and advantages with examples.

Smith Number in Java Smith Number in Java Aug 30, 2024 pm 04:28 PM

Guide to Smith Number in Java. Here we discuss the Definition, How to check smith number in Java? example with code implementation.

Java Spring Interview Questions Java Spring Interview Questions Aug 30, 2024 pm 04:29 PM

In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview.

Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

TimeStamp to Date in Java TimeStamp to Date in Java Aug 30, 2024 pm 04:28 PM

Guide to TimeStamp to Date in Java. Here we also discuss the introduction and how to convert timestamp to date in java along with examples.

Java Program to Find the Volume of Capsule Java Program to Find the Volume of Capsule Feb 07, 2025 am 11:37 AM

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

See all articles