Skip to content

Instantly share code, notes, and snippets.

@RyanMarcus
Created January 6, 2016 19:50
Show Gist options
  • Save RyanMarcus/90c1c639945cf12ffe7e to your computer and use it in GitHub Desktop.
Save RyanMarcus/90c1c639945cf12ffe7e to your computer and use it in GitHub Desktop.
So you think you know Java...
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.ref.WeakReference;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Random;
import java.util.function.IntFunction;
import java.util.function.Supplier;
import java.util.stream.IntStream;
// This code prints, at random, "even" or "odd" to either System in or System out.
// It also has a subtle race condition.
public class Main {
@Retention(RetentionPolicy.RUNTIME)
public @interface target {
String value();
}
public String callIfEven() {
return Thread.currentThread().getStackTrace()[1].getMethodName().substring(6).toLowerCase();
}
@target(value = "odd")
public String callIfOdd() {
try {
return getClass()
.getMethod(Thread.currentThread().getStackTrace()[1].getMethodName())
.getAnnotation(target.class)
.value();
} catch (NoSuchMethodException | SecurityException e) {
return null;
}
}
public int modulo2(int x) {
return (IntStream.range(0, x).reduce((a, b) -> (a == 0 ? 1 : 0)).getAsInt() == 0 ? 1 : 0);
}
public static void main(String[] args) throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
Random r = new Random();
Main m = new Main();
Method out = System.out.getClass().getMethod("println", String.class);
WeakReference<Method> wr = new WeakReference<Method>(out);
for (int i = 0; i < 1000; i++) {
int[] ary = new int[1000];
ary[i] = 5;
}
out = (wr.get() == null ? out : wr.get());
out.invoke((r.nextInt() % 2 == 0 ? System.out : System.err),
(((IntFunction<Integer>) m::modulo2).apply(r.nextInt(100)) == 0 ?
((Supplier<String>) m::callIfEven).get() : ((Supplier<String>) m::callIfOdd).get()));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment