Welcome!

Java Authors: Roger Strukhoff, Lori MacVittie, Esmeralda Swartz, Trevor Parsons, Sandi Mappic

Related Topics: Java

Java: Article

Embedding the Java Virtual Machine, Once And For All

A solution with complete support

JTL is a portable C++ JNI template library that allows you to embed a JVM within another program. An example of this might be found inside a browser that needs to support Java plug-ins. First I'll discuss the traditional way to embed a JVM within a native program, and then talk about the generic solution offered by JTL.

To apply the solution provided by JTL, you need to know the basics of Java, C++, and JNI. However, to understand JTL's design you should be familiar with modern C++ techniques, such as template programming and the Boost library (www.boost.org).

All the sample code in this article is written for Microsoft Windows, but it can easily be ported to other platforms.

The Traditional Way to Embed the JVM

Although there are lots of resources on how to embed a JVM, most of them are based on Sheng Liang's classic book, Java Native Interface: Programmer's Guide and Specification. Figure 1 shows the basic procedure.

If the application has other threads that are using the JVM as well, the communications among these threads will look like Figure 2.

Listing 1 shows the typical code (all the error checking and exception handling code in this article has been omitted for clarity). This code works fine as long as your program is simple enough; however, there are three major drawbacks.

Issue 1: The JVM is a global variable, which is not acceptable in some cases.

Issue 2: The threads in which jvm and env are used and the thread that launches jvm couple tightly. For example, there will be a potential timing issue that's clearly shown in Figure 2. The AttachCurrentThread(...) must be called after the launcher thread initialized jvm, and DetachCurrentThread() must be called before jvm has been destroyed; otherwise this creates unnecessary communications overhead between threads. It gets worse when you don't know which thread is the launcher thread.

Of course the VM can always be created in one thread when the native application starts. However, this is a pure waste if there is no Java client. The JVM should not be created if there are no requests.

Issue 3. The function calls to Attach-CurrentThread(...) and Detach-Current Thread() should be paired so the JVM can get a chance to free the local references. However, it's too easy to not have the DetachCurrentThread() called by the programmer (because of multiple flow paths) or by exceptions. A better approach would be to encapsulate the JVM into a class or classes.

Thin JVM Wrapper

It's natural to wrap the JavaVM* pointer into a member variable, say jvm. Because only one JVM in each process can be created (until JDK 1.4.2), the obvious class design is to make jvm static. Listing 2 shows the first attempt.

Here the method's signatures are not important so let's focus on the class design. The thin wrapper approach is simple and straightforward; however, it's not much better than the C-like code in Listing 1. It only gets rid of the explicit global variable jvm (the static member variable is still kind of global though). Issues 2 and 3, mentioned in the previous section, still need to be addressed.

Singleton JVM

The Singleton design pattern is described in Design Patterns by Erich Gamma, et al, as "Ensure a class only has one instance, and provide a global point of access of it." In other words, a Singleton class is a class for which no more than one instance can exist at runtime. This is what the JVM behaves like. We can apply the Singleton pattern to the JVM class design.

Andrei Alexandrescu has provided all kinds of singleton implementations in his book Modern C++ Design and the Loki library. Loki has a singleton manager class template, SingletonHolder, that looks like Listing 3.

The template parameter T in Listing 3 is the target class, in our case CJavaVM. Other template parameters specify the policies that manage the singleton. As explained in Alexandrescu's book, "A policy defines a class interface or a class template interface. The interface consists of one or all of the following: inner type definitions, member functions, and member variables." Policy classes are not intended for stand-alone use and their member functions are often static. In Loki::-Single-tonHolder, the CreationPolicy determines how the singleton instance is created and destroyed, and the Threading-Model policy determines whether the singleton is living in a multiple threaded world.

Listing 4 provides the redesigned CJavaVM class and its usage with Loki::-SingletonHolder. A difference between CJavaVM and CJavaVM2 is that all members in CJavaVM2 are not static. Listing 4 looks fancier than Listing 1. However, it does not solve the real problems. Issues 2 and 3 are still unresolved. For example, if there are any other threads trying to make a JNI call, it's still a requirement that the JVM launcher thread has already called jvm.Start-JavaVM(). This is because CJavaVM2's constructor does nothing. If StartJava-VM() can be moved into CJavaVM2's constructor and Destroy-JavaVM() can be moved into CJavaVM2's destructor, then the timing issue will be solved, which is not easy to do.

The major difficulty is that Loki::-SingletonHolder's template parameter CreationPolicy only calls the target class T's default constructor. In other words, CJavaVM2's constructor cannot look something like this: CJavaVM2(std::-string- jvmpath, JavaVMInitArgs& args). It must be CJavaVM2(). Period.

We are not out of bullets though. The "Every problem can be solved by adding another layer of indirection" idiom applies here.

Policy-Based JVM Class

The solution is to make CJavaVM2 policy-based too. Listing 5 shows the new version.

In CJavaVM3, a new policy class JavaVMLauncher is introduced and declared as follows:


class JavaVMLauncher {
public:
    static void LaunchJavaVM(void** ppLib, JavaVM** ppJavaVM);
    static void DestroyJavaVM(void* pLib, JavaVM* pJavaVM);
}

ppLib is a pointer to a handle returned by LoadLibrary on Windows or dlopen on Solaris. To make JavaVMLauncher more generic, the void pointer is used here. The pointer to pointer method is used for ppLib and ppJavaVM in LaunchJavaVM() because JavaVMLauncher does not contain any member variables. It's the caller to provide the placeholders for the objects pointed to by ppLib and ppJavaVM. DestroyJavaVM() simply accepts the cached JavaVM* and lib handle to destroy the JVM and free the library.

Now we can invoke the JVM as in Listing 6, which is pretty much what JTL does. In JTL, there is another class template called JavaVMMgr that is the placeholder for the JavaVM* and pLib. All the JVM calls will be delegated to the JavaVMMgr.

Exception Handling

The LaunchJavaVM() method in JavaVMLauncher can fail; for example, if the user does not have a JRE installed on his machine. When this happens, LaunchJavaVM() can return a flag or error code. In JTL, it will simply throw a jtl::load_javavm_error exception.

Multithreading, Extending Loki, and boost::thread

Remember in Listing 3, Loki::Single-tonHolder has a template parameter ThreadingModel that's used to synchronize the calls to MakeInstance(). However, under different platforms the thread implementation and API are different. To make the JVM class design platform portable, it needs to use a portable threading framework. JTL uses boost::thread because it's simple and easy to use, and it will likely be part of the next version of the standard C++ library.

Though Alexandrescu provides us with the excellent SingletonHolder class, JTL does not use it directly for two main reasons: not all compilers support Loki well and Loki::ThreadingModel is only implemented to work with Windows.jtl::SingletonHolder does some extension to Loki::SingletonHolder to achieve the platform-portable goal. However, jtl::SingletonHolder uses the same template parameters (and in the same order) as Loki::SingletonHolder, therefore the user can easily switch to Loki's version if someday Loki provides us with a platform-portable ThreadingModel.

Another thing needs to be mentioned for ThreadingModel - it should be able to work with both the single-thread model and multiple-thread model. If there's only one thread, there's no sense in doing the synchronization. To achieve this generic solution, JTL provides two class templates, Multiple-ThreadModel and SingleThread-Model, as shown in Listing 7.

These two classes simply provide type definitions. In Mul-tipleThread-Model, JTL uses the boost::mutex and boost::mutex::scoped_lock as the synchronization primi-tives, while in Single-ThreadModel it uses boostex::-faked_-mutex and boostex::faked_mutex::-scoped_-lock as the synchronization primitives. The faked mutex and scoped_lock are simple extensions to boost mutex and scoped_lock. They're empty classes and provide only the required inter-face methods, which are implemented as noop. This is a common trick in generic programming. (ATL programmers will recall the CComFake-CriticalSection used in CCom-Single-Thread-Model and CComMultiThread-Model that does the same trick.)

JNIEnv Smart Pointers

In Listing 6, we solved issues 1 and 2; we no longer have a global variable, and we don't have a timing issue when calling AttachCurrentThread() and Detach-CurrentThread(). However, issue 3 - how to ensure that DetachCurrent-Thread() is called - is still unresolved.

When doing JNI programming, most of the time we're dealing with the JNIEnv* pointer rather than the JavaVM* pointer. The most important characteristic of the JNIEnv pointer is that it has thread affinity (it's only valid in its associated thread). It would be nice if we could get the JNIEnv pointer in an arbitrary context. To achieve this and solve issue 3, JTL provides three smart pointers: simple_env_ ptr, auto_env_ptr, and thread_env_ptr. They're all class templates.

Before talking about these smart pointers, let's review the scenarios in which the JNIEnv pointer is used:

  1. In the launcher thread: In this case the ThreadingModel template parameter should be SingleThread-Model to avoid unnecessary thread synchronization, even though there may be multiple threads.
  2. In multiple threads: AttachCurrent-Thread() and Detach-CurrentThread() will be called only once for each thread.
  3. In multiple threads: AttachCurrent-Thread() and Detach-CurrentThread() can be called multiple times for each thread (see below).
simple_env_ptr, auto_env_ptr and thread_env_ptr are corresponding solutions for scenarios 1, 2, and 3. All these smart pointers are derived from env_ ptr_base, which is a placeholder for JNIEnv* pointer and has other helper functions, such as operator->(), operator!(). By the way, all three JNIEnv smart pointers are not full-blown. For more details about smart pointers, please refer to Alexandrescu's book.

The simple_env_ptr is defined as the following:


template < ... >
class simple_env_ptr : public env_ptr_base {
public:
    //... typedefs for SingletonJVM;
public:
    simple_env_ptr() {
        SingletonJVM::Instance().GetEnv(&env_, jvm_version);
    }
    ~simple_env_ptr() { env_ = 0;}
};

In simple_env_ptr's constructor, the JNIEnv pointer has been initialized by calling GetEnv(). This works because the smart pointer is in the launcher thread. Similarly, auto_env_ptr is defined as the following:


template < ... >
class auto_env_ptr : public env_ptr_base {
public:
    //... typedefs for SingletonJVM;
public:
    auto_env_ptr() {
        SingletonJVM::Instance().AttachCurrentThread(&env_, 0);
    }
    ~auto_env_ptr() {
        if(env_) {
            env_ = 0;
            SingletonJVM::Instance().DetachCurrentThread();
        }
    }
}; // auto_env_ptr

As you have seen, auto_env_ptr's constructor and destructor do the job of attaching and detaching the current thread. Thus we have solved issue 3 and we don't need to worry about the missing detaching call. However, auto_env_ ptr may not work if there is more than one auto_env_ptr instance in the same thread. This is clear in the following snippet:


// auto_env_ptr ptr1, ptr2
ptr1;
// ...other stuff
{
    ptr2;
}
// ... from here all calls on ptr1 may be invalid

In this snippet, when ptr2 is out of scope, its destructor will be called, causing the current thread to detach from the JVM. This may cause problems because ptr1 is still active; however, all its local references may have been freed by the JVM because of the ptr2's detaching call.

To solve this problem, JTL provides thread_env_ptr, which is defined in Listing 8. thread_env_ptr has a counter that's a thread local storage variable. Whenever there is a new thread_env _ptr instance, the counter will be bumped by one. Whenever there is a thread_env_ptr out of scope, the counter will be decreased by one. When the counter is decreased to zero, the current thread will be detached from the JVM.

Putting It All Together

Listing 9 illustrates how to use the JTL JVM invocation. You may provide your own JVMLauncher if the default one does not meet your requirement.

Conclusion

JTL provides complete support for the JVM invocation. It also provides JNIEnv smart pointers to get the JNIEnv* pointer in arbitrary context. Most of the classes in JTL are designed as class templates and they can easily be extended. JTL provides many template parameter implementations as well, which can be used as the default template parameter value under most circumstances.

All comments about JTL and this article are highly appreciated.

More Stories By Stanley Wang

Stanley Wang is a lead software developer at Vcom3D, Inc., and the author of JTL. He received his MS in computer science from the University of Florida. He is interested in system programming, generic programming, and computer graphics.

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.


@ThingsExpo Stories
Explosive growth in connected devices. Enormous amounts of data for collection and analysis. Critical use of data for split-second decision making and actionable information. All three are factors in making the Internet of Things a reality. Yet, any one factor would have an IT organization pondering its infrastructure strategy. How should your organization enhance its IT framework to enable an Internet of Things implementation? In his session at Internet of @ThingsExpo, James Kirkland, Chief Architect for the Internet of Things and Intelligent Systems at Red Hat, will describe how to revoluti...
The Internet of Things will greatly expand the opportunities for data collection and new business models driven off of that data. In her session at Internet of @ThingsExpo, Esmeralda Swartz, CMO of MetraTech, will discuss how for this to be effective you not only need to have infrastructure and operational models capable of utilizing this new phenomenon, but increasingly service providers will need to convince a skeptical public to participate. Get ready to show them the money! Speaker Bio: Esmeralda Swartz, CMO of MetraTech, has spent 16 years as a marketing, product management, and busin...
Samsung VP Jacopo Lenzi, who headed the company's recent SmartThings acquisition under the auspices of Samsung's Open Innovaction Center (OIC), answered a few questions we had about the deal. This interview was in conjunction with our interview with SmartThings CEO Alex Hawkinson. IoT Journal: SmartThings was developed in an open, standards-agnostic platform, and will now be part of Samsung's Open Innovation Center. Can you elaborate on your commitment to keep the platform open? Jacopo Lenzi: Samsung recognizes that true, accelerated innovation cannot be driven from one source, but requires a...
SYS-CON Events announced today that Red Hat, the world's leading provider of open source solutions, will exhibit at Internet of @ThingsExpo, which will take place on November 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA. Red Hat is the world's leading provider of open source software solutions, using a community-powered approach to reliable and high-performing cloud, Linux, middleware, storage and virtualization technologies. Red Hat also offers award-winning support, training, and consulting services. As the connective hub in a global network of enterprises, partners, a...
P2P RTC will impact the landscape of communications, shifting from traditional telephony style communications models to OTT (Over-The-Top) cloud assisted & PaaS (Platform as a Service) communication services. The P2P shift will impact many areas of our lives, from mobile communication, human interactive web services, RTC and telephony infrastructure, user federation, security and privacy implications, business costs, and scalability. In his session at Internet of @ThingsExpo, Robin Raymond, Chief Architect at Hookflash Inc., will walk through the shifting landscape of traditional telephone a...
SYS-CON Events announced today that Matrix.org has been named “Silver Sponsor” of Internet of @ThingsExpo, which will take place on November 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA. Matrix is an ambitious new open standard for open, distributed, real-time communication over IP. It defines a new approach for interoperable Instant Messaging and VoIP based on pragmatic HTTP APIs and WebRTC, and provides open source reference implementations to showcase and bootstrap the new standard. Our focus is on simplicity, security, and supporting the fullest feature set.
BSQUARE is a global leader of embedded software solutions. We enable smart connected systems at the device level and beyond that millions use every day and provide actionable data solutions for the growing Internet of Things (IoT) market. We empower our world-class customers with our products, services and solutions to achieve innovation and success. For more information, visit www.bsquare.com.
How do APIs and IoT relate? The answer is not as simple as merely adding an API on top of a dumb device, but rather about understanding the architectural patterns for implementing an IoT fabric. There are typically two or three trends: Exposing the device to a management framework Exposing that management framework to a business centric logic • Exposing that business layer and data to end users. This last trend is the IoT stack, which involves a new shift in the separation of what stuff happens, where data lives and where the interface lies. For instance, it’s a mix of architectural style...
SYS-CON Events announced today that SOA Software, an API management leader, will exhibit at SYS-CON's 15th International Cloud Expo®, which will take place on November 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA. SOA Software is a leading provider of API Management and SOA Governance products that equip business to deliver APIs and SOA together to drive their company to meet its business strategy quickly and effectively. SOA Software’s technology helps businesses to accelerate their digital channels with APIs, drive partner adoption, monetize their assets, and achieve a...
From a software development perspective IoT is about programming "things," about connecting them with each other or integrating them with existing applications. In his session at @ThingsExpo, Yakov Fain, co-founder of Farata Systems and SuranceBay, will show you how small IoT-enabled devices from multiple manufacturers can be integrated into the workflow of an enterprise application. This is a practical demo of building a framework and components in HTML/Java/Mobile technologies to serve as a platform that can integrate new devices as they become available on the market.
SYS-CON Events announced today that Utimaco will exhibit at SYS-CON's 15th International Cloud Expo®, which will take place on November 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA. Utimaco is a leading manufacturer of hardware based security solutions that provide the root of trust to keep cryptographic keys safe, secure critical digital infrastructures and protect high value data assets. Only Utimaco delivers a general-purpose hardware security module (HSM) as a customizable platform to easily integrate into existing software solutions, embed business logic and build s...
Connected devices are changing the way we go about our everyday life, from wearables to driverless cars, to smart grids and entire industries revolutionizing business opportunities through smart objects, capable of two-way communication. But what happens when objects are given an IP-address, and we rely on that connection, sometimes with our lives? How do we secure those vast data infrastructures and safe-keep the privacy of sensitive information? This session will outline how each and every connected device can uphold a core root of trust via a unique cryptographic signature – a “bir...
Internet of @ThingsExpo Silicon Valley announced on Thursday its first 12 all-star speakers and sessions for its upcoming event, which will take place November 4-6, 2014, at the Santa Clara Convention Center in California. @ThingsExpo, the first and largest IoT event in the world, debuted at the Javits Center in New York City in June 10-12, 2014 with over 6,000 delegates attending the conference. Among the first 12 announced world class speakers, IBM will present two highly popular IoT sessions, which will take place November 4-6, 2014 at the Santa Clara Convention Center in Santa Clara, Calif...
Almost everyone sees the potential of Internet of Things but how can businesses truly unlock that potential. The key will be in the ability to discover business insight in the midst of an ocean of Big Data generated from billions of embedded devices via Systems of Discover. Businesses will also need to ensure that they can sustain that insight by leveraging the cloud for global reach, scale and elasticity.
WebRTC defines no default signaling protocol, causing fragmentation between WebRTC silos. SIP and XMPP provide possibilities, but come with considerable complexity and are not designed for use in a web environment. In his session at Internet of @ThingsExpo, Matthew Hodgson, technical co-founder of the Matrix.org, will discuss how Matrix is a new non-profit Open Source Project that defines both a new HTTP-based standard for VoIP & IM signaling and provides reference implementations.

SUNNYVALE, Calif., Oct. 20, 2014 /PRNewswire/ -- Spansion Inc. (NYSE: CODE), a global leader in embedded systems, today added 96 new products to the Spansion® FM4 Family of flexible microcontrollers (MCUs). Based on the ARM® Cortex®-M4F core, the new MCUs boast a 200 MHz operating frequency and support a diverse set of on-chip peripherals for enhanced human machine interfaces (HMIs) and machine-to-machine (M2M) communications. The rich set of periphera...

SYS-CON Events announced today that Aria Systems, the recurring revenue expert, has been named "Bronze Sponsor" of SYS-CON's 15th International Cloud Expo®, which will take place on November 4-6, 2014, at the Santa Clara Convention Center in Santa Clara, CA. Aria Systems helps leading businesses connect their customers with the products and services they love. Industry leaders like Pitney Bowes, Experian, AAA NCNU, VMware, HootSuite and many others choose Aria to power their recurring revenue business and deliver exceptional experiences to their customers.
The Internet of Things (IoT) is going to require a new way of thinking and of developing software for speed, security and innovation. This requires IT leaders to balance business as usual while anticipating for the next market and technology trends. Cloud provides the right IT asset portfolio to help today’s IT leaders manage the old and prepare for the new. Today the cloud conversation is evolving from private and public to hybrid. This session will provide use cases and insights to reinforce the value of the network in helping organizations to maximize their company’s cloud experience.
The Internet of Things (IoT) is making everything it touches smarter – smart devices, smart cars and smart cities. And lucky us, we’re just beginning to reap the benefits as we work toward a networked society. However, this technology-driven innovation is impacting more than just individuals. The IoT has an environmental impact as well, which brings us to the theme of this month’s #IoTuesday Twitter chat. The ability to remove inefficiencies through connected objects is driving change throughout every sector, including waste management. BigBelly Solar, located just outside of Boston, is trans...
SYS-CON Events announced today that Matrix.org has been named “Silver Sponsor” of Internet of @ThingsExpo, which will take place on November 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA. Matrix is an ambitious new open standard for open, distributed, real-time communication over IP. It defines a new approach for interoperable Instant Messaging and VoIP based on pragmatic HTTP APIs and WebRTC, and provides open source reference implementations to showcase and bootstrap the new standard. Our focus is on simplicity, security, and supporting the fullest feature set.