How to create lag in Java? [duplicate]

I’m not sure I do understand exactly what you want, but it is improbable that you will get it using a sungle thread and an endless empty loop. First, that program will use at most one system thread, and therfore, a single CPU core. Second, the hotspot compiler is likely to optimize away your empty loop (or any arithmetic operation or assignement to a variable that will never be used). So what ever you want to accomplish, you need to do something that the optimizer won’t attemp to improve. So…

If you want to slow down the execution of a program (rather than the computer), then spread around some Thread.sleep(1000). The JVM will yield that time back to the OS.

If your intention is to have the JVM do some work while waiting for some external event (as in “computing bogomips of the system”), then you should run code that will have side effect, so that the optimzer won’t remove useless variable allocations. You may, for example, do some arithmetic operations on an array, then System.out.print() (or whatever else…) any value from that array. Note however that your process will still be limited to a single thread, and that if your process performs no IO operation for a long period, then it will most likely be depriorized by the operating system, so dont expect too much reliability from that type of measurement technique.

If you’re looking at stalling the whole system, then you must run several threads, and have them do either intensive memory allocations, IO operations, or external program execution. You may for example run thousands of threads, each od them running a loop that execute an external Java program that allocate huge buffers, then write the content of that buffer to a file… Well, you get the idea 😉

Leave a Comment