<<

Journal of Automation, Mobile Robotics & Intelligent Systems VOLUME 10, N° 1 2016

AJVM – Implemented in ActionScript 3.0

Submitted: 5th January 2016; accepted: 2nd February 2016

Arkadiusz Janik, Jakub Krawczyk

DOI: 10.14313/JAMRIS_1-2016/8 solution allowing to execute (in an isolated environ- ment) the whole OS and other software designed for Abstract: This paper describes the concept and implementation (VMWare Workstation or Oracle xVM VirtualBox). details of AJVM – state-of-the art Thea specific platform is software due to capable hardware of executing virtualization bina- (JVM) implemented in ActionScript 3.0. Action Script ry, precompiled code which is an output of a built-in is an objective programming language that supports compilation to Java . In the presented solu- device [7]. In the further part of this paper the term tion there has been a novel idea utilized – to use the virtualcompiler machine defining will its be own used architecture to denote the as interpreter.of a virtual other Virtual Machine’s environment (Action- Script Virtual Machine) to build Java Virtual Machine. 1.2. Flash Platform and ActionScript 3.0 The subset of features specified in JVM Specification technology (previously known as v.2 supported by AJVM has been chosen in a way which Macromedia Flash) is a multimedia platform en- enables the machine to be used in many practical ap- abling new features in web pages: animations, video plications both in the commercial context as well as in streaming, interactivity commonly used to imple- science. As the architecture of AJVM is modular, the ex- ment games, advertisements as well as more sophis- tension of its features in the future will not cause any ticated and complex applications. difficulties. The implementation of AJVM in ActionScript 3.0 which is executed by ActionScript Virtual Machine (Shockwave Flash Object). Usually there is a single (AVM) makes it possible to use Java code in applications Flash applications are published as SWF files written in ActionScript 3.0. It spawns many new oppor- libraries and multimedia resources. In Flash 5 the tunities considering that AVM is a part of FlashPlayer – conceptfile per application of actions introduced even though in itFlash may 4contain was extend many- commonly used multimedia player available in the form Action Script term was used of plugins for the majority of modern web browsers, in- in the context of a programming language [10, 11]. cluding mobile versions. Flashed and, 7 forwas the released first time, together with the second ver- sion of ActionScript programming language: such Keywords: JVM, Action Script, bytecode features as type-control (during compilation) and inheritance based on classes were introduced. Flash Players 9 was released with ActionScript 3.0 – the 1. Introduction - Traditional, commercial implementations of JVM port downgrade compatibility, there are two virtual Specification aim to increase the performance of machineslanguage wasin the redesigned player: AVM1 significantly (to support and, toAction sup- a Virtual Machine (VM). As a result VMs are usually Script 1.0 and 2.0) and AVM2 (to support Action- implemented in low level programming languages, Script 3.0) [14]. The number of new features have tightly integrated with (OS) and been introduced to the player including performance hardware (Just In Time that compile by- tecode into native code of the hardware platform). OpenGL), type-control (during code compilation and The goal of AJVM is to execute Java applications in execution),optimization separation (hardware of acceleration class-based forand DirectX prototype- and a variety of computers equipped mainly with a web based inheritance, using packages, namespaces and browser, to increase code reusability by making it regular expressions, new bytecode format, support possible to use Java libraries in Flash applications and to provide convenient platform for end-users to To sum up: ActionScript 3.0 is object-based, im- observe and understand concepts behind JVM. On perativefor E4X format programing and others. language with strong type-con- top of that the solution extends Flash platform with trol, compiled to bytecode being executed on AVM2 new features: multi-threading, blocking operations, virtual machine, single-threaded (driven by events generic classes as well as a new concept of execut- triggered by Flash Player) so not supporting blocking ing bytecode. methods, with automatic (Gar- bage Collector), not supporting generic classes, not 1.1. Basic Terms supporting anonymous classes. There are two major types of virtual machines: In the further part of the paper any references to emulators and interpreters [9]. The emulator is a Action Script will refer to Action Script 3.0.

58 Journal of Automation, Mobile Robotics & Intelligent Systems VOLUME 10, N° 1 2016

2. Related Work AminNes – Flash NES Emulator – Flash NES Emu- There are two major aspects of the contribution lator is an emulator of Nintendo Entertainment System of our work: Implementation of Java Virtual Machine in a non- 2KB video memory. The emulator supports MOS 6502 standard environment and– 8 bitsguarantees gaming theconsole highest equipped quality withof rendered 2kB RAM video. and Emulation of Java platform inside Flash Player. Flip8 – CHIP-8 Flash Emulator - In the opinion of the authors, there are no solu- tions other than AJVM that handle both: Action Script in 70s used to interpret programming– Flip8 language is an called emu and JVM. This makes AJVM a unique system capable of lator of CHIP-8. CHIP-8 is a virtual machine designed- emulating Java platform inside Flash Player. There are number of publications on the subject includingCHIP-8. It 35 used different to be operations installed on [19]. a graphical calcu of non-standard JVMs including the ones mentioned lators. Flip8 is an emulator able to execute bytecode below: 3. Implementation of JVM in ActionScript 3.0 Jamiga – the goal of the project is to execute Java ActionScript Java Virtual Machine (AJVM) was applications on Amiga computers [16]. implemented in Action Script [13]. It implements JC – the property of the JVM is a novel approach to executing bytecode. All Java classes are translated JVM v.2.0. The sections included below present more - informationa subset of features on the architecture described in and the implementationspecification of piled to native code thus enabling performance simi- problems the authors of this article had to solve. laron-the-fly to traditional to source Just code In Time in languageCompilers and (JITs) then [17]. com Squawk – implementation of JVM for Java ME (Mi- 3.1. Virtual Machine vs Standard cro Edition) for embedded systems and small, mobile The crucial part of the implementation of any devices. All elements, except for low-level modules sup- Java Virtual Machine is a – the im- - plementation of core Java classes described by JVM plemented in Java (including Garbage Collector) [15]. Hello portingGNU I/O operations – Java and Standard OS specific Library code, distributwere im- Word Java application requires hundreds of core Java ed under GNU license providing a great base to build classesspecification to be present[4]. Even and execution loaded into of the VM. simplest The solution own JVMs [20]. described in the paper contains following elements in JOP - terms of a standard library: plementation of JVM with predictable execution time AJVM library – ActionScript 3.0 library contain- – is a hardware im Flash or Flex projects. Flex is a set of components al- afor low embedded cost FPGA real-time (Field-Programmable systems. Due toGate the Array). small ing files of AJVM, ready to be used in any- size of the processor used, it can be implemented in be of more importance though slightly more expen- Silverlightlowing a developer [12]. to write RIA applications. It is be siveFor low than volume conventional systems, processors. the flexibility The ofprocessor an FPGA wascan ing ARTcompared standard to technologies library – suchan equivalent as XUL, JavaFX of Java or standard library included in any JVM distributions - sordesigned executes in VHDL bytecode programming directly, without language necessity (Very high to speed Hardware Description Language). The proces- native(such asimplementation JRE System Library of selected for JavaSE). methods A in standard the VM. Forlibrary the ispurpose specific of for AJVM VM implementationwe implemented as a itstandard expects (whichcompile is in-time consistent nor withto parse/interpret JVM –stack-based class VM files. rather Us thaning FPGA register-based) allows JOP to[21]. dynamically declare stack size based on GNU Classpath. Sable VM libraryAs the called authors ART focused (ActionScript on the selected Runtime) features which of is virtual machine, using state-of-the-art interpretation techniques. Its– goalsis a highly is to portablebe reasonably and efficient small, fast,Java standard library though it is possible to extend the implementationJVM, the ART is not in future. a complete implementation of the and compliant with the various specifications (JVM 3.2. High Level Overview of AJVM specification,2.1. Emulators JNI, of invocation Other Platforms interface, Implemented etc.) [18]. AJVM is available as an object created by the pro- in the Flash grammer’s code inside his/her Flash application (in Even though ActionScript 3.0 is relatively new lan- the similar way as for interpreter for Python guage there have been several emulators implement- programming language). Consequently, the program- ed so far: mer’s code has a full control over AJVM. Moreover, FC64 – Flash Commodore 64 Emulator – FC64 is several isolated instances of AJVM within the single a low-level, fully functional emulator of Commodore Flash host application can be created. 64 allowing a user to execute applications designed - for Commodore 64 as well as to write code in BASIC ally the code of Flash host-application and the code programming language [22]. Due to the features of the Flash platform usu FlashZXSpectrum48k - of AJVM are distributed in a single SWF file whereas- lar to FC64. The difference is – that Sinclair it emulates ZX Spectrum Sinclair Java classes that are part of ART and Java classes of Emulator} – FlashZXSpectrum48k is a solution simi server.the programmer’s code will be distributed as JAR ar chives (or single *.class files) located on the same web ZX Spectrum platform. Articles 59 Journal of Automation, Mobile Robotics & Intelligent Systems VOLUME 10, N° 1 2016

compiling the application) frequency of refreshing thecation application’s defines by viewthemselves in a web (usually browser. statically, Flash Player when takes all available steps to support the requested FPS (Frames Per Second) parameter. We implemented similar logic for AJVM – a pro- -

pergrammer frame usingAJVM AJVMcan execute defines before (as one giving of thethe paramcontrol backeters toof AJVMFlash configuration)application. AJVM how monitors many milliseconds its execu- tion time and breaks the execution of the bytecode immediately when the requested threshold is met. Fig. 1. High level overview of AJVM In future we plan to add adaptive mechanism inside AJVM so that it dynamically changes the parameter depending on complexity of Java and/or Flash code Figure 1 presents a high level overview of AJVM. and available computational power (for instance to As mentioned before, the programmer’s Flash slow down execution of Java code during dynamic code has a full control over AJVM particularly in the animations of a Flash application). below areas: Implementing native methods – some methods Starting and stopping AJVM instances – instanc- delivered with Java standard library are native meth- es of AJVM are independent objects created, started ods. Similarly, user’s methods can also be native. AJVM and stopped in moments which are arbitrarily chosen - during the lifetime of host Flash application. ers to declare and implement own native methods – Configuring classpath – similarly to traditional writtenuses native in ActionScript code to implement 3.0. As ARTa result thus the enabling user’s apus- plications can communicate with Flash applications. know where to look for compiled Java classes. Unlike Configuring logger – one of the goals of imple- JVMs, also AJVM needs classpath [3] to be defined to menting AJVM was to provide platform that can be used by users to experiment with and learn about traditional JVMs, AJVM does not have access to the file architecture of VMs. Monitoring is crucial thus we system thus it needs to download class files from a equipped AJVM in easy to use logger supporting four code.web server. For instance, AJVM addsif one a assumes prefix with that theAJVM name is used of its in Flashown web to available compose under URLs http://domain.servused to locate class- er.com/apps/test/index.html 3.3.levels: Executing SEVERE, BytecodeWARNING, in INFO AJVM and DEBUG. under http://domain.server.com/apps/test/applica- One of innovations of AJVM is a fully objective ap- tion.swf and SWF file is available proach to VM’s major functionality which is executing as java/rt;java/classes and then executed Java class bytecode. The overview on the standard location of pl.edu.agh.test.Example. Flash host application. It means defined that theAJVM classpath tries to bytecode execution module in a typical JVM’s archi- load the class from one of the locations below (until tecture can be found in the Figure 2. In Java the bytecode is one of many attributes of http://domain.server.com/apps/test/java/rt/pl/ edu/agh/test/Example.classthe first successful try). - http://domain.server.com/apps/test/java/class- tiona method. module In ofJVM a specificationtraditional JVM’s bytecode works instructions on binary es/pl/edu/agh/test/Example.class instructionsare identified kept as numbers in a method (0x00 area till memory 0xca). An and execu rep- resented in an unchanged way comparing to the com- new entries to the class path. piled bytecode. The only exception is replacing con- SpecifyingAJVM supports main dynamic, class – Each on-the-fly JVM starts addition the ex of- stant pool elements with symbolic references (and, ecution of the user’s code following the method: of course JIT compilation to native code). There are public static void main(String args[]);

AJVM also expects the name of the main class to be provideddefined (as in onethe ofclass the specified mandatory as JVM’selements argument. of the

Configuring lifecycle of VM – As mentioned be- foreconfiguration Flash is ofa AJVM).single-threaded environment. The programmer’s code is executed solely in response to events triggered by Flash Player (a mouse click, a key- board event etc.). It is expected that an event handler gives control back to the Flash Player as soon as pos- sible to guarantee smooth execution. As the consequence, AJVM has to work in very short time slots divided by pauses long enough to handle other no Java events and to render the next Fig. 2. Location of bytecode execution module in a stan- frame of Flash animation. A developer of a Flash appli- dard JVM’s architecture

60 Articles Journal of Automation, Mobile Robotics & Intelligent Systems VOLUME 10, N° 1 2016

typical graph representation of classes and relations between them. There are following known limita- tions: Indirect references – Apart from direct relations between a class and its methods (or between a method and its arguments) a traditional syntactic parse tree stores relations between some objects purely by their

class com.test.B one has to take string “com.test.A” and identifiers.look for a graph For instance: of the class to retrievewith such any a name.attributes Such of an a approach requires checking whether the object with such a name exists and this is time consuming. Bytecode in a binary representation – A part of a syntactic parse tree – methods’ bytecode – was not Fig. 3. Simplified version of syntactic parse tree for Java parsed at all. Inside instructions of a method there classes in AJVM (which are also elements of syntactic parse tree), whichare references remain in to a classes, binary otherrepresentation methods as and long fields as the bytecode is executed. The above syntactic parse trees can be used to mobile implementations of JVMs utilizing XIP concept build even more effective representation shown in the(eXecution instruction In Place) is being thus executed not copying [6]. bytecode There are to folthe- Figure 3. All relations between represented classes, lowingmethod implications area but referring of the above to *.class mentioned files whenever models: - Necessity to interpret the instruction’s code every time the instruction is executed – in Java’s bytecode processmethods, (parsing fields andthe class even representation) external types canthus be mak re- one needs to interpret the instruction to understand solved immediately after the first step of class loading how many bytes after the instruction are the instruc- Building object-oriented representation of the tion’s arguments, which is necessary to obtain the be- bytecodeing execution – As of presentedclasses’ bytecode on the more diagram efficient. from the ginning of the next instruction. previous section we decided to use object-oriented Necessity to derefer pointers to constant pool every representation also for the bytecode. In a traditional time the instruction is executed – the instruction’s argu- approach the is represented as a sin- gle-dimensional sequence of instructions executed as entries in the constant pool (for instance: new, an- one-by-one. In practice, instruction pointer very of- ewarrayments can instructions refer to classes, which methods allocate or objects fields addressedor arrays, ten changes in a more complex way due to branch invokevirtual instruction which calls a method etc.). instructions, conditional or unconditional jumps etc. - The place in the bytecode that the control should be transferred to (after a branch instruction) is calcu- of anThe object above requires approach following may lead steps to a to significant be executed: over lated as an offset relative to the current instruction load. For instance: getting a value of a non-static field pointer. It means that executing a branch instruction from an entry in a constant pool) an address of a data requires calculating the new address and reading the Retrieve (from bytecode and using information bytecode instruction from that address. The approach anstructure address with of thethe datadescription structure of thewith field, the Retrieve (from the field’s description) informationdescription of about the field’s its class class, and its fully Retrieve an offset of the field using - qualified name, Retrieve from the data structure repre senting the object of the field the value of the Thefield above (using mentioned the offset stepsof the are fields not and ac- a of the field). The low performance of the standard approachtioned for toJIT thecompilation bytecode (JIT) execution [8]. and the access to constant pool data motivated us to look for another approach in which the following steps were taken: The construction of objective rep- resentation of Java class – Construction of syntactic parse tree, which is an object

(see Figure 3). The representation is not a Fig. 4. A sample, full graph of classes and relations between them representation of elements in class file Articles 61 Journal of Automation, Mobile Robotics & Intelligent Systems VOLUME 10, N° 1 2016

Fig. 5. Sample instruction execution graph shown in the context of objects it uses

we have taken is using a novel idea: after parsing the field instruction stores the reference to an object of class, there is an instruction execution graph being JVMField class, allowing it to load the current value built for each non-abstract method (see Figure 5). Operation codes are mapped on classes of respec- tive instructions. Whenever the instruction needs to thanof a field. 200 bytecode’s instructions has their implemen- be executed, the object’s method is executed with the tationThis (in is the a decentralizedexecute() method) approach: thus the each conceptual of more instruction’s arguments. Each object has the knowl- edge (stored as reference to) about objects repre- from the traditional implementations of JVM. schemaThe bytecode of AJVM execution (see Figure module 8) differs in AJVM significantly is virtual- by the instruction. Similarly, there are references to asenting consecutive classes, instruction fields and (ormethods to consecutive that are required instruc- bytecode expressed as objects. It means that AJVM tions for branch instructions) stored in the object. neitherized. The contains module noris created uses binaryby instructions representation of loaded of - bytecode. There are following advantages of such an tion from its method whereas the bytecode stores the approach: referenceThe method to itsstores method the soreference that it knows to the wherefirst instruc to give One-time interpretation of bytecode – Binary control back when returning. representation of bytecode is read by AJVM once, Delegation of executing an instruction to its when the class is loaded and the instruction graph is object representation – Using an objective nature of built. ActionScript 3.0 language one can create full hierar- Novel implementation of reflection – All class- chy of classes for Java instructions. A part of such a hierarchy is presented in Figure 6. Each instruction implement method ex- es, methods, fields and their attributes have objective ecute() declared in Instruction interface representations thus the implementation of reflection (design pattern Command). An argument of the method is object FrameExecution- Context, which represents a single stack frame. The object’s diagram can be found in Figure 7. FrameExecutionContext object pro- vides access to computational stack and current values of local variables thus allow- ing an instruction to execute (itself) in the current context. After execution in the way

pop two values from the stack, add them andspecific push for on theto stack instruction for iadd (for instruction) instance: JVM has to set up the next instruction to be executed. As a result, conditional instruc- tions can control their thread’s execution. An instruction can use additional references passed when the class was parsed and the graph was built. For instance: class Jget- Fig. 6. A part of a diagram showing objective hierarchy of Java fieldInstruction, which is representing get- instructions

62 Articles Journal of Automation, Mobile Robotics & Intelligent Systems VOLUME 10, N° 1 2016

does not require referencing native code. Clear and flexible architec- ture – Inspection of the instruc- tion graph as well as dependencies between classes make possible to extend AJVM in the future with in- teresting features such as dynamic - tion of code execution which can be code transformation or visualiza performance. used to analyze and optimize code 4. Additional Remarks on AJVM Implementation 4.1. Implementing Exception Handlers Fig. 7. A part of a diagram of the most important classes of One of the attributes of a com- AJVM execution module piled class is an exception handlers table. The table is used to store information about the class of an

instruction being protected by the handler,exception the being offset handled, of the thelast firstin- struction being protected and the

procedure. offsetIn AJVMof the there first areinstruction no instruction of the offsets at all, as they are replaced by the instruction graph. Conse- quently exception handlers have to

method has a collection of objects representingbe defined in anexception objective way.handlers Each (the list may be empty for methods without try-catch blocks). An object representing an exception handler stores references to all instructions being protected (as it is impossible Fig. 8. Bytecode execution module in AJVM - struction and the offset). The idea is presentedto represent in Figurethe set 9. as the first in

4.2. Garbage Collection We solved the problem of Auto- matic Memory Management (AAM [5]) using features of ActionScript 3.0 which is equipped with AMM. Flash VM (AVM2) is equipped with Garbage Collector thus the easiest way of solving GC related problems is to: • Resign from our own heap in AJVM – our JVM does not use heap at all. • Encapsulate each and every Java object inside native Action- Script objects – it is possible due to representing each Java object as Fig. 9. An objective representation of an exception handler table for a method an instance of class JVMObject defined in ActionScript 3.0 al- located on Action Script’s AVM2 heap and managed by AVM2. Each

Articles 63 Journal of Automation, Mobile Robotics & Intelligent Systems VOLUME 10, N° 1 2016

Java object is encapsulated in ActionScript 3.0 ob- ject. Each Action Script’s JVMObject stores a refer- ence to the object representing the class of the Java object and a data structure to store the Java object’s state (value of all fields from the object’s class). • Utilizing AVM2 Garbage Collector – as Java ob- jects inside AJVM are represented by ActionScript’s object they are managed by AVM2’s Garbage Collec- tor. The only limitation is not to store any additional, Fig. 10. A sample code used to register a native method external references to these objects even though it in AJVM may be useful for the purpose of VM monitoring etc. Arguments of the function are used to pass fol- 4.3. Multithreading lowing elements from native interface of AJVM to the The traditional implementation of JVMs provides user’s method: multithreading through the mapping of Java threads • The context of the current execution frame in the onto native threads (on the Operating System level) [1, execution stack frame – the reference to the case 2]. AJVM does not have access to low level OS threads of FrameExecutionContext class that gives the as it is limited by Flash Player it is run in and which access to properties of the current Java thread as executes ActionScript 3.0’s code just inside the event- well as to the stack and the local area of the stack handler’s thread. Consequently, it was necessary to frame. It allows the native method to use informa- implement the multithreading model of our own de- tion that is forbidden for Java code (for instance to sign at the level of application. We had to use an ob- implement reflection with the use of the objective jective representation of a thread as a part of VM. An representation of classes and methods). instance of AJVM holds the collection of instances of • The values of arguments passed to Java method. JVMThread class. New objects are added to the col- args contains 0 or more arguments passed to the lection every time a bytecode instruction executes native method by the Java code. Primitive types are java.lang.Thread.start() method, and are removed mapped onto corresponding types of ActionScript while returning from java.lang.Thread.run() meth- 3.0 whereas objects are represented by their en- od. As soon as the collection is empty the AJVM stops. capsulations (JVMObject) – in the native code one AJVM works in cycles and each cycle is about ex- can easily get their classes and access fields (also ecuting an amount of bytecode’s instructions of each private) in a way similar to the one used in the re- active thread. The length of AJVM’s cycle (measured flection. as a period of time as opposed to a number of instruc- • Callback that returns from native method – even though keyword return is present in ActionScript of each cycle is split between all threads accordingly 3.0, employing it for returning from function would totions) their is priorities. AJVM configuration The simplest item. way The to meet available the above time significantly reduce the capabilities of native methods. Each native implementation would have with the handling of priorities. Each AJVM cycle con- to give control back to AJVM soon after getting it sistsrequirements of/requires is to the implement following RoundRobinsteps: algorithm as Flash Player uses a single thread. Implementing Calculate the possible time of the end of the cycle return functionality in the described way allows endTime a developer to implement blocking methods (for If endTime is reached, give the control back to instance input/output operations). A thread call- (current time + configured cycle time). ing a native method is blocked until the callback For each thread in the collection: is executed. In practice it means that even void eventExecute handling method procedure step() (thus a number finishing of times the cycle). basing methods (not returning anything) should contain calculations on the priority of threads. onReturn(null) call at the end. If the thread ends(execution stack is empty), re- move the thread from the collection. 5. Test Cases Go back to step 2. The output of the implementation part of our work Obviously, the above algorithm does not apply to includes an ActionScript 3.0 library implementing the “blocked” or “waiting for monitor” (monitorenter in- most important features of Java Virtual Machine. The struction) threads. quality of the Virtual Machine can be measured with use of many indicators including the two most impor- 4.4. Native Interface Native interface of AJVM allows a user to provide and performance. As was mentioned at the beginning their implementation of Java classes as functions of tant: compatibility with JVM specification version 2- tion was not our objective. Instead, we focused on thanks to the method which binds a native method (its thoseof this parts paper, of the Standard full compliance Java Library with that JVM allow specifica a de- class,ActionScript name and 3.0. signature) It is done with during ActionScript VM initialization 3.0 ob- veloper to create the majority of typical Java applica- ject that represents the closure of the function (Call- tions. back design pattern). Figure 10 demonstrates sample Neither high performance was the goal of AJVM. implementation and the registration of native method However, it is worth comparing the implementation sqrt) in VM’s case. of AJVM with the most popular JVM – Oracle HotSpot.

64 Articles Journal of Automation, Mobile Robotics & Intelligent Systems VOLUME 10, N° 1 2016

ecution time increases linearly in a function of array

5.3.size forTest both: Case AJVM 3 – Sortingand HotSpot of Linked virtual List machines. of java.lang. Comparable Objects The test was to call java.util.Collections.sort() method from the standard library to sort linked list (java.util.LinkedList) containing objects implement- ing compareTo() method. The test validates pointer operations and virtual methods (unlike sorting arrays of primitive types). The results can be found in Fig- ure 13. Fig. 11. Execution time of the test 1 – performing fixed point arithmetic

The following testing platform was used: (VM: Java HotSpot(TM) 64-Bit Server VM (build 21.0-b17, - ment (build 1.7.0-b147). AJVM (plugin) – VM: AJVM, mixed mode, library: Java(TM) SE Runtime Environ reference version, library: ART, reference version, Flash Player: 11.2.202.233, ActiveX plugin, Internet WindowsExplorer 8.7 64-bit.All tests have been executed on () Core(TM) i7-2630QM @ 2.0 GHz, 8 GB RAM, System Fig. 13. Execution time of the test 3 – sorting linked lists 5.1. Test Case 1 – Fixed Point Arithmetic of comparable objects The test was to iterate through an array of integers and perform several calculations on each element of One can see an interesting observation here: even the array. The results are presented in Figure 11. though both tests; test 2 and test 3 are about sorting Test results leave no doubts with regards to the of a collection, the increase of execution time in test differences between commercial HotSpot VM and that in test 3 objects are sorted rather than numbers compilation used in HotSpot the code is compiled to which3 is significantly results in greatermore object than inoperations test 2. The (compare() reason is nativeexperimental, representation research and AJVM. executed Due on to a Justphysical In Time pro- - cessor rather than on a virtual machine. As a result, cient in AJVM than in HotSpot. method calls). And pointer operations are less effi 5.4. Test case 4 – Network Connections and calculations5.2. Test Case are 2done – Sorting significantly of Floating faster. Point Object Deserialization Numbers The aim of the test was to establish a network con- The test was to call java.util.Arrays.sort() method of nection with a remote server with the use of java.net. the standard library to sort an array of double num- Socket bers. The results can be found in Figure 12. The results can be found in Figure 14. so as to obtain some data and deserialize it.

Fig. 12. Execution time of the test 2 – sorting arrays of Fig. 14. Execution time of the test 4 – transferring data fixed point numbers through network connection and deserializing it

Again HotSpot VM beats AJVM and again the major Interestingly, the difference between execution factor is JIT implemented in AJVM. Another important time between AJVM and HotSpot is less visible and factor is that for arithmetic in HotSpot is do not exceeds 35%. The reason is that in the test ex- ternal, system resources are used (network connec- techniques possible. It is worth mentioning that ex- tion) intensely. In other words: it is not so important written in C which makes development optimization Articles 65 Journal of Automation, Mobile Robotics & Intelligent Systems VOLUME 10, N° 1 2016

how elements of a virtual machine are implemented 5.7. Samples of AJVM Utilization as most operations are done on a level of OS. In other This section demonstrates sample applications of words, a proportion of input/output operations to AJVM. It describes how AJVM can be used to execute other operations is higher than in previous tests. sample Internet applications – multiuser, text chat room. 5.5. Test Case 5 – Massive Multithreading The test consisted of launching the number of con- current threads, executing them and waiting for the last one to end. The results are illustrated in Figure 15.

Fig. 16. The architecture of chatroom application ex- Fig. 15. Execution time of the test 5 – executing signifi- ecuted on AJVM cant amount of concurrent threads The architecture shown in Figure 16 contains the fol- The grey bar in the Figure 15 for HotSpot indi- lowing elements: cates missing results – it was impossible to start so • HTTP server – any web server to provide static many threads. files via http protocol. The major factor that contributes to smaller ex- • Chatroom server – server implemented in Java for ecution time in AJVM comparing to HotSpot is a differ- real-time, multi user chat room (Java Object Seri- ent threading model used in both solutions. HotSpot, like many other VMs maps Java threads to native OS • Chatroom client – client application written in threads. As a result thread creation is time-consuming Flashalization using is used). Flex components. AJVM is applied operation. When there is a huge amount of threads OS to implement networking functionality (object may behave unstable. AJVM emulates multithreading - programmatically – creating and starting a new thread is as expensive as creating one more Java object. validating(de) data). It and is worthtransfer) mentioning as well as that imple the abovement businesssample uses logic Java (logging code sharedin, authorizing between andthe 5.6. Test Cases Summary client and server applications: the same class- The conclusions drawn from the executed test cas- es are loaded by HotSpot JVM (server side) and es are as follows: AJVM (client side). Once SWF file (Flash applica- Tests 1, 2 and 3 leave no doubts with regards to tion) and Java classes are loaded, HTTP protocol the differences between commercial HotSpot VM and is no longer used and there is a single network communication (TCP) established. compilation used in HotSpot the code is compiled to nativeexperimental, representation research and AJVM. executed Due on to a Justphysical In Time pro- 6. Conclusions cessor rather than on a virtual machine. As a result, Authors of this paper successfully implemented calculations are done significantly faster. Java Virtual Machine in ActionScript 3.0. As a result Test 4 shows more balanced results due to the sig- it was possible to use elements of existing elements nificant influence of input/output operations in com- of a virtual machine’s infrastructure (FlashPlayer) to parison with the execution time. Input/output op- build your own solution. It allowed authors to focus erations are less CPU demanding thus AJVM is more on selected modules of a virtual machine (like imple- effective. The results prove clearly that in some appli- mentation of a novel concept of bytecode execution cations AJVM can be used with success. engine) and to use existing ones which are beyond Test 5 provides solid evidence in favour of the exis- the scope of interest (GC, threading model etc.). Selec- tence of domains on which AJVM is more robust than tion of an environment that supports traditional VMs. The benefit of AJVM is the way thread (Action Script 3.0 and Flash Player) spawns many creation is implemented. Having said that it must be opportunities considering the fact that Flash Player is commonly used in most of modern web browsers. not mean that all thread operations are more effective As shown in the previous section, AJVM can be onemphasized AJVM. As thatit was efficient mentioned creation before of atest thread 5 focuses does successfully used in implementing various applica- only on thread creation rather than on measuring all tions, including Internet ones. There are many ad- thread-related operations (creation, sleeping, waking vantages of using AJVM including: High reusability up, thread scheduling etc.). of classes

66 Articles Journal of Automation, Mobile Robotics & Intelligent Systems VOLUME 10, N° 1 2016

Client and server elements of an Internet appli- cation usually use the same data structures, simi- - lar validation rules (for input data) as well as some ing.on-the-fly code transformation, code injection during common elements of business logic. In a traditional runtime,As it was and mentioned more efficient a couple and ofprecise times, codeAJVM profil is de- solution many of these common features are imple- signed in a modular way so that the level of depen- mented twice (often using different implementation dency on external VM (Flash Player) can be reduced platforms): on each side. It is a developer’s responsi- to some extent. For instance, it is possible to imple- bility to guarantee consistency of both parts of the ap- ment own Garbage Collector module and replace the plication. The use of AJVM enables developers to use one provided by Flash container. However, due to the same Java code at the client’s and server’s side. It module dependencies, replacing a module may result is a huge time-saver and the way to reduce a number in being forced to replace others as well. GC module of errors. mentioned above is a good example. In the current Providing lightweight implementation of Java Vir- implementation objects creation and management is tual Machine together with an application controlled by Flash at all. In order to replace GC both Even though using Java applets meet the previous- domains would have to be delivered. ly mentioned criteria (high reusability of classes), it is worth mentioning that Flash Player is much lighter Source code of AJVM can be accessed here: and more popular than Java plugins for web browsers. AJVM makes it possible to execute Java code by users - http://galaxy.uci.agh.edu.pl/~ajanik/AJVM_source_ ment neither additional plugins to web browsers. End files.zip userswho dodo notnot have intend to tobe installeven aware Java Runtimeof JVM running Environ on AUTHORS their computers. AJVM is extremely lightweight – the Arkadiusz Janik* – AGH University of Science and Technology, Faculty of Computer Science, Electronics Eliminating limitations of traditional clients sizeClient of compiled applications AJVM isare less usually than 100kb.running in single- threaded environment and thus use only a single and Telecommunications, Department of Computer thread (designed to support user’s interface). Good Science, al. Mickiewicza 30, 30-059 Kraków, Poland. examples are JavaScript, HTML5 and Flash. AJVM al- JakubE-mail: [email protected] – AGH University of Science and lows to use (on a client side) additional computation- Technology, Faculty of Computer Science, Electronics al models: multi-threading, generics etc. Of course, the performance of reference imple- mentation of AJVM requires ActionScript 3.0 code to and Telecommunications, Department of Computer be responsible for such tasks as: UI rendering, mul- *CorrespondingScience, al. Mickiewicza author 30, 30-059 Kraków, Poland. timedia streaming, and CPU intensive computations. Executed test cases shows clearly that the current which speed up bytecode execution, particularly Just REFERENCES implementation is missing optimization techniques JVM is lower comparing to traditional, commercial [1] Lindholm T., Yellin, F., The Java Virtual Machine VMsIn Time (represented compilation. by HotSpotConsequently, in test thecases efficiency executed). of Specification, 2nd Edition, Addison-Wesley, 1999. [2] Gosling J., Joy B., The Java Language Specifica- test cases using intensively external resources (less tion, Addison-Wesley, 1996. operationsThe difference on VM-level of efficiency comparing ranges to froma number ~35% of op for- The Java Class Libraries: An An- - notated Reference, Addison-Wesley, 1997. [4][3] NaughtonChan P., Lee P., R.,Morrison M., The Java Handbook, caseerations 5) which on OS-level) reveals to dominance ~12 800% of for AJVM. others. The ex Osborne/McGraw-Hill, 1996. ceptionThe futureis some work specific on AJVMsituations includes (described the extension in test [5] Venners B., Inside the Java 2 Virtual Machine, McGraw-Hil, 2000. The Java Virtual Machine, duringof the class compliance loading). with the reference specification of JVMOne (forshould instance also remember providing thatbytecode in order verification to seri- [7][6] CraigDowning I., Virtual T., Meyer Machines J., , Springer, 2005. ously think about practical application of AJVM it O’Reilly Media,Java and 1997. the Java Virtual Machine: Defi- should be made compliant with Java 7 or at least Java nition, Verification, Validation, Springer, 2001. 6 standard. [8] Stark R., Study of the techniques - for emulation programming, Universidad Po- velopment of Java Standard Library delivered with [9] Barriolitecnica V., de Fernandez Catalunya, A., 2001. JVMAnother (to provide significant full compliance work to be withdone Oracle is further imple de- ActionScript 3.0 Bible”, Wiley, mentation or full compliance with GNU Classpath). 2010. Another part of the research will concern increas- [11][10] ActionScriptBraunstein, Virtual R., Machine 2 (AVM2) Overview, ing the performance. There are many options includ- Adobe Systems Incorporated, 2007. ing Just-In-Time compilation. Also, the novel bytecode Flash Builder 4 and Flex 4 Bible, Wi- opens new possibilities related to ley, 2010. [12] Gassner D., Articles 67 Journal of Automation, Mobile Robotics & Intelligent Systems VOLUME 10, N° 1 2016

[13] Elst P., Object-Oriented ActionScript 3.0, friend-

[14] Technology Breakdown. sofED,http://www.adobe.com/products/player\_census/ 2007. flashplayer/tech\_breakdown.html accessed on 1st Oct 2015. The squawk virtual ma- chine: Java on the bare metal, ACM, 2005. [16][15] SimonJAmiga D.,VM Cifuentes homepage, C., 2014. http://jamiga2.blogspot.com/ accessed on 15th July 2015. [17] JC Virtual Machine homepage, 2013. http://jcvm.sourceforge.net/ accessed on 15th July 2015. Return Value Prediction in a Java Virtual Machine, VPW2, 2004. [18] Pickett C., Verbrugge C., accessed [19] onFlip8 21 –st CHIP-8Sep 2015. Flash Emulator homepage, 2014. [20] http://sourceforge.net/projects/flip8/GNU Classpath homepage, 2014. http://jcvm.sourceforge.net/ accessed on 21st Sep 2015.

[21] Schoeber, M., “JOP: A Java Optimized Processor [22] FC64for Embedded – Flash Commodore Real-Time Systems”, 64 Emulator VDM homep Verlag- Dr.age, Müller, 2014. 2008. ac- cessed on 2nd Apr 2015. http://codeazur.com.br/stuff/fc64\_final/

68 Articles