1 /*******************************************************************************
2 * Copyright (c) 2012 Association for Decentralized Information Management in
4 * All rights reserved. This program and the accompanying materials
5 * are made available under the terms of the Eclipse Public License v1.0
6 * which accompanies this distribution, and is available at
7 * http://www.eclipse.org/legal/epl-v10.html
10 * VTT Technical Research Centre of Finland - initial API and implementation
11 *******************************************************************************/
12 package org.simantics.utils.threads;
14 import java.util.concurrent.TimeUnit;
17 * @author Antti Villberg
19 public class Throttler implements Runnable {
21 final private IThreadWorkQueue thread;
22 final private int interval;
24 private boolean isScheduling = false;
26 private long[] dispatchTimes;
27 private long lastQueueTime;
29 private int dispatchTimePointer = 0;
31 private Runnable todo;
33 public Throttler(IThreadWorkQueue thread, int interval, int queueLength) {
36 this.interval = interval;
38 long currentTime = System.currentTimeMillis();
40 dispatchTimes = new long[queueLength];
41 for(int i=0;i<dispatchTimes.length;i++)
42 dispatchTimes[i] = currentTime - interval;
44 lastQueueTime = Long.MAX_VALUE;
48 public synchronized void run() {
51 thread.asyncExec(todo);
53 ThreadUtils.getTimer().schedule(this, interval, TimeUnit.MILLISECONDS);
60 public synchronized void schedule(Runnable r) {
62 assert(thread.currentThreadAccess());
66 if(getQueueTime() < interval) {
69 ThreadUtils.getTimer().schedule(this, interval, TimeUnit.MILLISECONDS);
75 private long getQueueTime() {
79 private void dispatch(Runnable runnable) {
81 long time = System.currentTimeMillis();
82 lastQueueTime = time - dispatchTimes[dispatchTimePointer];
83 dispatchTimes[dispatchTimePointer] = time;
84 dispatchTimePointer = ((dispatchTimePointer+1) % dispatchTimes.length);