Revision: 15393
Author: [email protected]
Date: Fri Nov 19 00:54:05 2010
Log: Fix for http://code.google.com/p/mobicents/issues/detail?id=2129
Reduce CPU usage during idling
http://code.google.com/p/mobicents/source/detail?r=15393
Modified:
/trunk/servers/media/core/server-impl/src/main/java/org/mobicents/media/server/impl/clock/Semaphore.java
=======================================
---
/trunk/servers/media/core/server-impl/src/main/java/org/mobicents/media/server/impl/clock/Semaphore.java
Tue Nov 16 22:05:58 2010
+++
/trunk/servers/media/core/server-impl/src/main/java/org/mobicents/media/server/impl/clock/Semaphore.java
Fri Nov 19 00:54:05 2010
@@ -38,15 +38,38 @@
//current time
private long now;
+ private long ems;
/**
* Creates new instance of semaphore.
*
* @param timer timer which will be used for time measurement.
* @param precision the precision for time measurement in microseconds
*/
+ @SuppressWarnings("static-access")
public Semaphore(Timer timer, long precision) {
this.timer = timer;
this.precision = precision;
+
+ //determine worst sleep() execution
+
+ long error = 0; //max detected error.
+ long T = 10; //sleep amount
+
+ for (int i = 0; i < 100; i++) {
+ long s = timer.getTimestamp();
+ try {
+ Thread.currentThread().sleep(T);
+ } catch (InterruptedException e) {
+ }
+ long e = Math.abs((timer.getTimestamp() - s) - T * 1000000L);
+
+ //checking error
+ if (e > error) error = e;
+ }
+
+ //round result to the milliseconds
+ ems = error/1000000L + 1;
+ ems *= 2;
}
/**
@@ -56,9 +79,27 @@
*/
public void block(long amount) {
low = timer.getTimestamp() + amount * 1000000L - precision * 1000L;
+
+ //try sleep first
+ if (amount - ems > ems) {
+ try {
+ Thread.currentThread().sleep(amount - ems);
+ } catch (InterruptedException e) {
+ }
+ }
+
+ now = timer.getTimestamp();
//poll timer in cycle till required time will be reached
while ((now < low)) {
now = timer.getTimestamp();
}
}
-}
+
+ public static void main(String[] args) {
+ Semaphore semaphore = new Semaphore(new TimerImpl(), 10);
+ long s = System.nanoTime();
+ semaphore.block(22);
+ long d = System.nanoTime() - s;
+ System.out.println(d);
+}
+}