--- /dev/null
+/*******************************************************************************\r
+ * Copyright (c) 2012 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ * VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.utils.threads;\r
+\r
+import java.util.concurrent.TimeUnit;\r
+\r
+/**\r
+ * @author Antti Villberg\r
+ */\r
+public class Throttler implements Runnable {\r
+\r
+ final private IThreadWorkQueue thread;\r
+ final private int interval;\r
+\r
+ private boolean isScheduling = false;\r
+\r
+ private long[] dispatchTimes;\r
+ private long lastQueueTime;\r
+\r
+ private int dispatchTimePointer = 0;\r
+\r
+ private Runnable todo;\r
+\r
+ public Throttler(IThreadWorkQueue thread, int interval, int queueLength) {\r
+\r
+ this.thread = thread;\r
+ this.interval = interval;\r
+\r
+ long currentTime = System.currentTimeMillis();\r
+\r
+ dispatchTimes = new long[queueLength];\r
+ for(int i=0;i<dispatchTimes.length;i++)\r
+ dispatchTimes[i] = currentTime - interval;\r
+\r
+ lastQueueTime = Long.MAX_VALUE;\r
+\r
+ }\r
+\r
+ public synchronized void run() {\r
+\r
+ if(todo != null) {\r
+ thread.asyncExec(todo);\r
+ todo = null;\r
+ ThreadUtils.getTimer().schedule(this, interval, TimeUnit.MILLISECONDS);\r
+ } else {\r
+ isScheduling = false;\r
+ }\r
+\r
+ }\r
+ \r
+ public synchronized void schedule(Runnable r) {\r
+\r
+ assert(thread.currentThreadAccess());\r
+ \r
+ dispatch(r);\r
+\r
+ if(getQueueTime() < interval) {\r
+\r
+ isScheduling = true;\r
+ ThreadUtils.getTimer().schedule(this, interval, TimeUnit.MILLISECONDS);\r
+\r
+ }\r
+\r
+ }\r
+\r
+ private long getQueueTime() {\r
+ return lastQueueTime;\r
+ }\r
+\r
+ private void dispatch(Runnable runnable) {\r
+\r
+ long time = System.currentTimeMillis();\r
+ lastQueueTime = time - dispatchTimes[dispatchTimePointer];\r
+ dispatchTimes[dispatchTimePointer] = time;\r
+ dispatchTimePointer = ((dispatchTimePointer+1) % dispatchTimes.length);\r
+\r
+ if(!isScheduling) {\r
+ todo = null;\r
+ runnable.run();\r
+ } else {\r
+ todo = runnable;\r
+ }\r
+\r
+ }\r
+\r
+}\r