sclass limitCPU_Data { int granularity = 10; double percentage; volatile long calcingSince; volatile long sleepTime, calcTime; } //static new ThreadLocal limitCPU_data; static Map limitCPU_data = synchroMap(new WeakHashMap); svoid limitCPU(double percentage) { if (percentage >= 100 || percentage < 0) ret; limitCPU_Data data = limitCPU_data.get(currentThread()); if (data == null) limitCPU_data.put(currentThread(), data = new limitCPU_Data); if (ping_impl(false)) data.calcingSince = 0; // ping slept, reset timer //limitCPU_Data data = limitCPU_data.get(); if (data.percentage != percentage) { data.percentage = percentage; data.calcTime = data.sleepTime = 0; } if (data.calcingSince == 0) { data.calcingSince = now(); ret; } long newCalcTime = now() - data.calcingSince; if (newCalcTime >= data.granularity) { // don't try to sleep too often data.calcTime += newCalcTime; double ratio = percentage/100; // todo: calc shouldSleepTime double allowedCalcTime = data.sleepTime*ratio/(1-ratio); long sleep = toLong(max(0, data.calcTime-allowedCalcTime)); if (sleep > 0) { sleep(sleep); data.sleepTime += sleep; } data.calcingSince = now(); } }