All Downloads are FREE. Search and download functionalities are using the official Maven repository.

io.github.shanqiang.sp.Throughput Maven / Gradle / Ivy

The newest version!
package io.github.shanqiang.sp;

import io.github.shanqiang.table.Table;
import io.github.shanqiang.Threads;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;

public class Throughput {
    private static final Logger logger = LoggerFactory.getLogger(Throughput.class);

    private static final Map stats = new ConcurrentHashMap();
    private static final List names = new ArrayList<>();

    static {
        new ScheduledThreadPoolExecutor(1, Threads.threadsNamed("Throughput")).scheduleWithFixedDelay(new Runnable() {
            @Override
            public void run() {
                for (String name : names) {
                    logger.info("{}: {}/s", name, stats.get(name).getAndSet(0)/5);
                }
            }
        }, 5, 5, TimeUnit.SECONDS);
    }

    public static void log(String name, List tables) {
        for (Table table : tables) {
            log(name, table);
        }
    }

    public static void log(String name, Table table) {
        if (!names.contains(name)) {
            synchronized (names) {
                if (!names.contains(name)) {
                    names.add(name);
                }
            }
        }
        stats.putIfAbsent(name, new AtomicLong());
        stats.get(name).addAndGet(table.size());
    }
}