Skip to content

Instantly share code, notes, and snippets.

@kabutz
Created September 23, 2017 08:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kabutz/f971ef61f0eb784dc2376ad4f3ad7ea5 to your computer and use it in GitHub Desktop.
Save kabutz/f971ef61f0eb784dc2376ad4f3ad7ea5 to your computer and use it in GitHub Desktop.
Three cheers (or more) for Java 9 release!
// Compile and run in Java 9. Then compile and run in Java 8 and 9. Enjoy your new JDK :-D
public class Java9AtLast {
public static void hiphip(int cheers) {
try {
hiphip(cheers + 1);
} catch(StackOverflowError er) {
System.out.println("hooray x " + cheers);
}
}
public static void main(String... args) {
hiphip(0);
}
}
@JurrianFahner
Copy link

For java 8 the output is not what I've expected... It is able to catch an error (thanks for the learning experience 👍 )!
For java 9 you'd better don't try to catch the error (it becomes some cryptic):

Exception in thread "main" java.lang.NoClassDefFoundError: Could not initialize class java.lang.invoke.MethodType
	at java.base/java.lang.invoke.MethodHandleNatives.findMethodHandleType(MethodHandleNatives.java:292)
	at Java9AtLast.hiphip(Java9AtLast.java:6)

When removing the try-catch, it is more comprehensible:

Exception in thread "main" java.lang.StackOverflowError
	at Java9AtLast.hiphip(Java9AtLast.java:5)

@kabutz
Copy link
Author

kabutz commented Sep 23, 2017

You can produce some marvelous hacks with StackOverflowError - for example, make threads die without releasing their locks ... :-)

@kabutz
Copy link
Author

kabutz commented Sep 23, 2017

Fortunately synchronized is fairly robust in this way ...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment