Welcome!

Machine Learning Authors: Elizabeth White, Liz McMillan, Yeshim Deniz, Pat Romanski, Ed Featherston

Related Topics: Machine Learning , Java IoT

Machine Learning : Article

Lesson Learnd from Using Rhino to Process JavaScript

This entry documents a few tips related to using Rhino JavaScript Engine to process JavaScript code

This entry documents a few tips related to using Rhino JavaScript Engine to process JavaScript code. If you are using Rhino, you probably won’t run into the issues covered in this post during development or even testing. However, you are fairly likely to run into these issues after your system goes live. It would easily result in days or even weeks of soul searching (speaking from my personal experience:-)). Part of the problem seems to be the lack of documentation from the web. The other part of the problem is that the problem is rather a Java language problem(very convoluted). - Java limits the maximum method size to be 64KB.

1. JVM Byte Code Size Limit Problem

On rare occasions, you will see exceptions like the followings from Rhino when processing JavaScript files:

Exception in thread “main” java.lang.IllegalArgumentException: out of range index

at org.mozilla.classfile.ClassFileWriter?.add(ClassFileWriter?.java:541) at org.mozilla.classfile.ClassFileWriter?.addLoadConstant(ClassFileWriter?.java:601) at org.mozilla.classfile.ClassFileWriter?.addPush(ClassFileWriter?.java:837) at org.mozilla.javascript.optimizer.BodyCodegen?.visitSpecialCall(Codegen.java:2571) at org.mozilla.javascript.optimizer.BodyCodegen?.generateExpression(Codegen.java:1763) at org.mozilla.javascript.optimizer.BodyCodegen?.visitSetProp(Codegen.java:3743) at org.mozilla.javascript.optimizer.BodyCodegen?.generateExpression(Codegen.java:2118) at org.mozilla.javascript.optimizer.BodyCodegen?.generateStatement(Codegen.java:1660) at org.mozilla.javascript.optimizer.BodyCodegen?.generateStatement(Codegen.java:1510) at org.mozilla.javascript.optimizer.BodyCodegen?.generateBodyCode(Codegen.java:1181) at org.mozilla.javascript.optimizer.Codegen.generateCode(Codegen.java:285) at org.mozilla.javascript.optimizer.Codegen.compileToClassFile(Codegen.java:157) at org.mozilla.javascript.optimizer.Codegen.compile(Codegen.java:67) at org.mozilla.javascript.Context.compileImpl(Context.java:2327) at org.mozilla.javascript.Context.compileString(Context.java:1323) at org.mozilla.javascript.Context.compileString(Context.java:1312) at org.mozilla.javascript.tools.shell.Main.loadScriptFromSource(Main.java:500) at org.mozilla.javascript.tools.shell.Main.processFileSecure(Main.java:439) at org.mozilla.javascript.tools.shell.Main.processFile(Main.java:406) at org.mozilla.javascript.tools.shell.Main.processSource(Main.java:397) at org.mozilla.javascript.tools.shell.Main.processFiles(Main.java:181) at org.mozilla.javascript.tools.shell.Main$IProxy.run(Main.java:102) at org.mozilla.javascript.Context.call(Context.java:540) at org.mozilla.javascript.ContextFactory?.call(ContextFactory?.java:447) at org.mozilla.javascript.tools.shell.Main.exec(Main.java:164) at org.mozilla.javascript.tools.shell.Main.main(Main.java:142)

Here are a few posts you can find when you do a web search that are related to this issue (though don’t seem to offer a solution):

This can be extremely frustrating. For example, if you are a Dojo ShrinkSafe user, you know ShrinkSafe works because you have used it millions of times on many projects successfully. But on a certain situations, you will run into the above problem. When you search specifically for this ShrinkSafe problem, here is the best that I can find:

“While it’s not recommended that you develop 2MB JS files, it seems that it *does* happen, and it’s about the time that your files get this large that a project (naturally!) turns to the Dojo compressor. Unfortunantly, the default set of arguments doesn’t hold up to a file this big, and strange exceptions result. Here is a modified recipe for use with the kinds of files that really, *really* need the Dojo compressor:
java -Xmn100M -Xms500M -Xmx500M -jar custom_rhino.jar -opt -1 -c HUGE.js > smaller.js

This is not very helpful in my own experience. First of all, there are tons of reasons that Rhino needs to process big JavaScript files (for example, you want to use Rhino to analyze a bunch of JavaScript files concatenated together). Secondly, very little explanation is given about this command line “magic”. Thirdly, this command line “magic” seems to be misleading because the problem is not related to JVM memory limit (no need to do -Xms500M -Xmx500M in my experience).

The source of the problem is not your code, not Rhino, but rather a Java language limit. See http://java.sun.com/docs/books/jvms/second_edition/html/ClassFile.doc.html, section 4.10:

The amount of code per non-native, non-abstract method is limited to 65536 bytes by the sizes…

Rhino implemented correctly by sticking to the Java language specification. In fact, you can see the following comments from <code>org.mozilla.classfile.ClassFileWriter<code>:

if (attrLength > 65536) {
// See http://java.sun.com/docs/books/jvms/second_edition/html/ClassFile.doc.html,
// section 4.10, “The amount of code per non-native, non-abstract
// method is limited to 65536 bytes…
throw new ClassFileFormatException(
“generated bytecode for method exceeds 64K limit.”);
}

The Dojo ShrinkSafe issue is fundamentally caused by this problem. Any other software that relies on Rhino will have this problem too.

2. So What Is the Solution?

The short answer is, well, there is no solution, if you rely on Rhino to compile JavaScript into Java code. Well, Java code has to subject to the 64KB Java language limit.

If you are in desperate need for a solution, you might try to “pre-process” your JavaScript code by breaking apart large JavaScript methods into a bunch of smaller methods, which may yield smaller than 64KB Java byte code for each compiled method. -Thought this approach looks really painful.

However, if you are not using Rhino to compile JavaScript to Java, there are easier ways to get around the problem. Rhino does not have to “compile JavaScript to Java code”. You can configure Rhino to run at an “Interpretive mode”. Given that there is Java byte code involved at all, this limit naturally does not apply. This is simple to do. It takes one line of code:

context.setOptimizationLevel(-1);

The above set the Rhino Context object to “interpreative” mode. See Rhino Optimization Level for detailed information.

3. Is it time for us to treat the 64KB JVM limit as a bug, rather that a Java language spec item?

In the world of JavaScript, well, it is not usual to have methods that far exceeds the 64KB limit. For example, it is very common these days for JavaScript libraries to wrap a lot of functions inside one parent function for the sake of encapsulation and scoping. For example, jQuery wraps all code inside one function block (function(){…})(). Other JavaScript libraries like Dojo use similar techniques too. In such situations, it is fairly easy to exceed the 64KB limit when compiled into Java byte code.

For dynamic languages, especially languages that developers tend to nest functions inside functions (”inner function”), the 64KB limit seems to be awfully low.

Of course, this problem is not unique to JavaScript developers. For example, JSP developers can easily run into this problem too. See http://forums.sun.com/thread.jspa?threadID=472929&messageID=2296445 for an example.

Interesting enough, bug 4262078 at bugs.sun.com, “Maximum method size is too small (64Kb)“, is exactly on this issue. See http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4262078. The bug was submitted in 1999. Nine years later, in 2008, we are still not sure whether this will be fixed.

More Stories By Coach Wei

Coach Wei is founder and CEO of Yottaa, a web performance optimization company. He is also founder and Chairman of Nexaweb, an enterprise application modernization software company. Coding, running, magic, robot, big data, speed...are among his favorite list of things (not necessarily in that order. His coding capability is really at PowerPoint level right now). Caffeine, doing something entrepreneurial and getting out of sleeping are three reasons that he gets up in the morning and gets really excited.

Comments (0)

Share your thoughts on this story.

Add your comment
You must be signed in to add a comment. Sign-in | Register

In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.


@CloudExpo Stories
Gemini is Yahoo’s native and search advertising platform. To ensure the quality of a complex distributed system that spans multiple products and components and across various desktop websites and mobile app and web experiences – both Yahoo owned and operated and third-party syndication (supply), with complex interaction with more than a billion users and numerous advertisers globally (demand) – it becomes imperative to automate a set of end-to-end tests 24x7 to detect bugs and regression. In th...
As you move to the cloud, your network should be efficient, secure, and easy to manage. An enterprise adopting a hybrid or public cloud needs systems and tools that provide: Agility: ability to deliver applications and services faster, even in complex hybrid environments Easier manageability: enable reliable connectivity with complete oversight as the data center network evolves Greater efficiency: eliminate wasted effort while reducing errors and optimize asset utilization Security: imple...
High-velocity engineering teams are applying not only continuous delivery processes, but also lessons in experimentation from established leaders like Amazon, Netflix, and Facebook. These companies have made experimentation a foundation for their release processes, allowing them to try out major feature releases and redesigns within smaller groups before making them broadly available. In his session at 21st Cloud Expo, Brian Lucas, Senior Staff Engineer at Optimizely, will discuss how by using...
In this strange new world where more and more power is drawn from business technology, companies are effectively straddling two paths on the road to innovation and transformation into digital enterprises. The first path is the heritage trail – with “legacy” technology forming the background. Here, extant technologies are transformed by core IT teams to provide more API-driven approaches. Legacy systems can restrict companies that are transitioning into digital enterprises. To truly become a lead...
Companies are harnessing data in ways we once associated with science fiction. Analysts have access to a plethora of visualization and reporting tools, but considering the vast amount of data businesses collect and limitations of CPUs, end users are forced to design their structures and systems with limitations. Until now. As the cloud toolkit to analyze data has evolved, GPUs have stepped in to massively parallel SQL, visualization and machine learning.
The session is centered around the tracing of systems on cloud using technologies like ebpf. The goal is to talk about what this technology is all about and what purpose it serves. In his session at 21st Cloud Expo, Shashank Jain, Development Architect at SAP, will touch upon concepts of observability in the cloud and also some of the challenges we have. Generally most cloud-based monitoring tools capture details at a very granular level. To troubleshoot problems this might not be good enough.
SYS-CON Events announced today that CAST Software will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 - Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. CAST was founded more than 25 years ago to make the invisible visible. Built around the idea that even the best analytics on the market still leave blind spots for technical teams looking to deliver better software and prevent outages, CAST provides the software intelligence that matter ...
SYS-CON Events announced today that Daiya Industry will exhibit at the Japanese Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Ruby Development Inc. builds new services in short period of time and provides a continuous support of those services based on Ruby on Rails. For more information, please visit https://github.com/RubyDevInc.
The next XaaS is CICDaaS. Why? Because CICD saves developers a huge amount of time. CD is an especially great option for projects that require multiple and frequent contributions to be integrated. But… securing CICD best practices is an emerging, essential, yet little understood practice for DevOps teams and their Cloud Service Providers. The only way to get CICD to work in a highly secure environment takes collaboration, patience and persistence. Building CICD in the cloud requires rigorous ar...
When it comes to cloud computing, the ability to turn massive amounts of compute cores on and off on demand sounds attractive to IT staff, who need to manage peaks and valleys in user activity. With cloud bursting, the majority of the data can stay on premises while tapping into compute from public cloud providers, reducing risk and minimizing need to move large files. In his session at 18th Cloud Expo, Scott Jeschonek, Director of Product Management at Avere Systems, discussed the IT and busine...
As businesses evolve, they need technology that is simple to help them succeed today and flexible enough to help them build for tomorrow. Chrome is fit for the workplace of the future — providing a secure, consistent user experience across a range of devices that can be used anywhere. In her session at 21st Cloud Expo, Vidya Nagarajan, a Senior Product Manager at Google, will take a look at various options as to how ChromeOS can be leveraged to interact with people on the devices, and formats th...
First generation hyperconverged solutions have taken the data center by storm, rapidly proliferating in pockets everywhere to provide further consolidation of floor space and workloads. These first generation solutions are not without challenges, however. In his session at 21st Cloud Expo, Wes Talbert, a Principal Architect and results-driven enterprise sales leader at NetApp, will discuss how the HCI solution of tomorrow will integrate with the public cloud to deliver a quality hybrid cloud e...
SYS-CON Events announced today that Yuasa System will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Yuasa System is introducing a multi-purpose endurance testing system for flexible displays, OLED devices, flexible substrates, flat cables, and films in smartphones, wearables, automobiles, and healthcare.
Is advanced scheduling in Kubernetes achievable? Yes, however, how do you properly accommodate every real-life scenario that a Kubernetes user might encounter? How do you leverage advanced scheduling techniques to shape and describe each scenario in easy-to-use rules and configurations? In his session at @DevOpsSummit at 21st Cloud Expo, Oleg Chunikhin, CTO at Kublr, will answer these questions and demonstrate techniques for implementing advanced scheduling. For example, using spot instances ...
DevOps is under attack because developers don’t want to mess with infrastructure. They will happily own their code into production, but want to use platforms instead of raw automation. That’s changing the landscape that we understand as DevOps with both architecture concepts (CloudNative) and process redefinition (SRE). Rob Hirschfeld’s recent work in Kubernetes operations has led to the conclusion that containers and related platforms have changed the way we should be thinking about DevOps and...
SYS-CON Events announced today that Taica will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Taica manufacturers Alpha-GEL brand silicone components and materials, which maintain outstanding performance over a wide temperature range -40C to +200C. For more information, visit http://www.taica.co.jp/english/.
When it comes to cloud computing, the ability to turn massive amounts of compute cores on and off on demand sounds attractive to IT staff, who need to manage peaks and valleys in user activity. With cloud bursting, the majority of the data can stay on premises while tapping into compute from public cloud providers, reducing risk and minimizing need to move large files. In his session at 18th Cloud Expo, Scott Jeschonek, Director of Product Management at Avere Systems, discussed the IT and busine...
We all know that end users experience the Internet primarily with mobile devices. From an app development perspective, we know that successfully responding to the needs of mobile customers depends on rapid DevOps – failing fast, in short, until the right solution evolves in your customers' relationship to your business. Whether you’re decomposing an SOA monolith, or developing a new application cloud natively, it’s not a question of using microservices – not doing so will be a path to eventual b...
Enterprises have taken advantage of IoT to achieve important revenue and cost advantages. What is less apparent is how incumbent enterprises operating at scale have, following success with IoT, built analytic, operations management and software development capabilities – ranging from autonomous vehicles to manageable robotics installations. They have embraced these capabilities as if they were Silicon Valley startups. As a result, many firms employ new business models that place enormous impor...
SYS-CON Events announced today that SourceForge has been named “Media Sponsor” of SYS-CON's 21st International Cloud Expo, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. SourceForge is the largest, most trusted destination for Open Source Software development, collaboration, discovery and download on the web serving over 32 million viewers, 150 million downloads and over 460,000 active development projects each and every month.