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