Java square wave

I am trying to create a square wave on a parallel port with java. So far I have this implementation.

public class Wave extends Thread {

    public Wave() {
        super();
        setPriority(MAX_PRIORITY);
    }

    @Override
    public void run() {
        Wave.high();
        LockSupport.parkNanos(20000000);
        Wave.low();
        LockSupport.parkNanos(20000000);
    }

    public static native void high();
    public static native void low();
}

In which the high () and low () functions are implemented using JNI (the C shared library manages the parallel port). It works very well; it generates a square wave with a period of about 40 ms. Using an oscilloscope, it looks like the standard deviation is about 10 microseconds when the computer is in standby mode. When the computer does not work, the standard deviation becomes much larger. I think this is due to the fact that more context switches occur, and the threads remain too long in the idle state, and the specified 20 ms are not achieved exactly.

? , , , .

"" , ?

+3
3

"" , .

:

, .

, , , .

+1

, .

, (, , , JIT) java. , , gc. , , , , , . , jvm (java -X).

, . aix, , Linux. Linux. ubuntu ​​ , , , , (: , ). , " " - , , linux, , ).

+1

, , :

public class Wave extends Thread {
    private final Object BLOCKER = new Object();

    public Wave() {
        super();
        setPriority(MAX_PRIORITY);
    }

    @Override
    public void run() {
      // I suspect this should be running in an endless loop?
      for (;;) {
        Wave.high();
        long t1 = System.currentTimeMillis();

        // Round interval up to the next 20ms "deadline"
        LockSupport.parkUntil(BLOCKER, t1 + 20 - (t1 % 20));
        Wave.low();

        // Round interval up to the next 20ms "deadline"
        long t2 = System.currentTimeMillis();
        LockSupport.parkUntil(BLOCKER, t2 + 20 - (t2 % 20));
      }
    }

    public static native void high();
    public static native void low();
}

Since it depends on the wall clock's time ms, rather than the more accurate time in nanoseconds, it will not work at much higher frequencies. But this may not work, since GC (and other processes) can interrupt this thread for an β€œunsuccessful” period of time, which will lead to the same jitter.

When I tested this on my Windows 7 quad-core processor with JDK 6, I had some kind of minor jitter about every second, so the aix solution is probably better

0
source

All Articles