The JVM is by design an insecure environment and it is generally difficult to run untrusted code in a sandboxed environment.
UPDATE I have implemented two little libraries which takes care of the grunt work of sandboxing Nashorn and Rhino code in Java:
Nashorn Sandbox (on GitHub)
Rhino Sandbox (on Github)
Restricting Script Access to Specified Java Classes: From the Oracle Nashorn docs. Shows how to restrict access to specific Java classes.
Class ContextFactory: Useful for monitoring and setting restrictions on Rhino code.
Method initSafeStandardObjects: Useful for creating sandboxed Rhino code.
Sandboxing Rhino in Java: Blog post
Securing Rhino in Java6: Blog post
Example Code Monitoring Threads: Example code how thread CPU usage can be monitored.
The Java Sandbox: A library for sandboxing any Java code. Might be useful to sandbox the Java code with runs the script.