Skip to content

Instantly share code, notes, and snippets.

@chakmeshma
Created May 17, 2017 20:25
Show Gist options
  • Select an option

  • Save chakmeshma/77e0609045c915c88643610e2c41739e to your computer and use it in GitHub Desktop.

Select an option

Save chakmeshma/77e0609045c915c88643610e2c41739e to your computer and use it in GitHub Desktop.
This code causes the stack of the calling thread to look like a sin function over a specific time.
public class SinStack {
public static void drawCurve(float radius, int resolution, float totalWaitTime, int cycles) {
float cycleWaitTime = totalWaitTime / cycles;
float partAngle = (float) (Math.PI / resolution);
float partWidth = cycleWaitTime / resolution;
for (int i = 0; i < resolution * cycles; i++) {
float angleLow = partAngle * i;
float angleHigh = partAngle * (i + 1);
float heightLow = (float) Math.sin(angleLow) * radius;
float heightHigh = (float) Math.sin(angleHigh) * radius;
float height = (heightLow + heightHigh) / 2.0f;
drawSegment(radius - height, partWidth);
}
}
private static void drawSegment(float height, float width) {
if (width <= 0.0f || height < 0.0f)
return;
int depth = Math.round(height);
long nWaitTime = (long) (1000_000_000L * width);
if (depth == 0) {
forceSleep(nWaitTime);
} else {
recursiveStackTreeFunction(1, depth, nWaitTime);
}
}
private static int recursiveStackTreeFunction(int depth, int maxDepth, long waitTime) {
if (depth == maxDepth) {
forceSleep(waitTime);
return 1;
} else {
return recursiveStackTreeFunction(depth + 1, maxDepth, waitTime);
}
}
private static void forceSleep(long nWaitTime) {
long nRemainingTime = nWaitTime;
if (nWaitTime <= 0)
return;
do {
long lastSleepStartTimestamp = System.nanoTime();
try {
long millis = Math.round(((double) nRemainingTime) / 1000_000.0);
int nanos = (int) (nRemainingTime - (millis * 1000_000));
Thread.sleep(millis, nanos);
} catch (InterruptedException e) {
}
nRemainingTime -= System.nanoTime() - lastSleepStartTimestamp;
} while (nRemainingTime > 0);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment