package com.sifang.modules.factory;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Timer;
import java.util.TimerTask;

public class TokenBucket {

    private static final Logger log = LoggerFactory.getLogger(TokenBucket.class);
    private static final int MAX_CAP = 60;
    private int semaphore = MAX_CAP;

    public TokenBucket() {
        Timer timer = new Timer();
        timer.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                synchronized (TokenBucket.this) {
                    if (semaphore < MAX_CAP) {
                        semaphore++;
                        TokenBucket.this.notifyAll();
                    }
                }
            }
        }, 1000, 1000);
    }

    public synchronized void get() {
        while (true) {
            if (semaphore > 0) {
                semaphore--;
                break;
            } else {
                try {
                    wait();
                } catch (InterruptedException e) {
                    // ignore
                }
            }
        }
    }

}
