001/** 002 * Copyright (c) 2015-2022, Michael Yang 杨福海 (fuhai999@gmail.com). 003 * <p> 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * <p> 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * <p> 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016package io.jboot.objects.counter.impl; 017 018import io.jboot.objects.counter.JbootCounter; 019 020import java.util.HashMap; 021import java.util.Map; 022import java.util.concurrent.atomic.AtomicLong; 023 024/** 025 * @author michael yang (fuhai999@gmail.com) 026 * @Date: 2020/3/7 027 */ 028public class JbootLocalCounter implements JbootCounter { 029 030 private static Map<String, AtomicLong> ATOMICLONGS = new HashMap<>(); 031 032 private AtomicLong atomicLong; 033 034 public JbootLocalCounter(String name) { 035 atomicLong = ATOMICLONGS.get(name); 036 if (atomicLong == null) { 037 synchronized (JbootLocalCounter.class) { 038 atomicLong = ATOMICLONGS.get(name); 039 if (atomicLong == null) { 040 atomicLong = new AtomicLong(); 041 ATOMICLONGS.put(name, atomicLong); 042 } 043 } 044 } 045 } 046 047 @Override 048 public Long increment() { 049 return atomicLong.incrementAndGet(); 050 } 051 052 @Override 053 public Long decrement() { 054 return atomicLong.decrementAndGet(); 055 } 056 057 @Override 058 public Long get() { 059 return atomicLong.get(); 060 } 061 062 @Override 063 public void set(long newValue) { 064 atomicLong.set(newValue); 065 } 066}