Click here to close now.


Java Authors: Pat Romanski, Carmen Gonzalez, Yeshim Deniz, Liz McMillan, Elizabeth White

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 (

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 {
    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 {
    //... typedefs for SingletonJVM;
    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 {
    //... typedefs for SingletonJVM;
    auto_env_ptr() {
        SingletonJVM::Instance().AttachCurrentThread(&env_, 0);
    ~auto_env_ptr() {
        if(env_) {
            env_ = 0;
}; // 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
// ...other stuff
// ... 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.


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
SYS-CON Events announced today that CommVault has been named “Bronze Sponsor” of SYS-CON's 16th International Cloud Expo®, which will take place on June 9-11, 2015, at the Javits Center in New York City, NY, and the 17th International Cloud Expo®, which will take place on November 3–5, 2015, at the Santa Clara Convention Center in Santa Clara, CA. A singular vision – a belief in a better way to address current and future data management needs – guides CommVault in the development of Singular Information Management® solutions for high-performance data protection, universal availability and sim...
SYS-CON Events announced today that SafeLogic has been named “Bag Sponsor” of SYS-CON's 16th International Cloud Expo® New York, which will take place June 9-11, 2015, at the Javits Center in New York City, NY. SafeLogic provides security products for applications in mobile and server/appliance environments. SafeLogic’s flagship product CryptoComply is a FIPS 140-2 validated cryptographic engine designed to secure data on servers, workstations, appliances, mobile devices, and in the Cloud.
SYS-CON Events announced today that StorPool Storage will exhibit at SYS-CON's 16th International Cloud Expo®, which will take place on June 9-11, 2015, at the Javits Center in New York City, NY. StorPool is distributed storage software that allows service providers, enterprises and other cloud builders to run data storage on standard x86 servers, instead of using expensive and inefficient storage arrays (SAN).
GENBAND has announced that SageNet is leveraging the Nuvia platform to deliver Unified Communications as a Service (UCaaS) to its large base of retail and enterprise customers. Nuvia’s cloud-based solution provides SageNet’s customers with a full suite of business communications and collaboration tools. Two large national SageNet retail customers have recently signed up to deploy the Nuvia platform and the company will continue to sell the service to new and existing customers. Nuvia’s capabilities include HD voice, video, multimedia messaging, mobility, conferencing, Web collaboration, deskt...
SYS-CON Events announced today that Site24x7, the cloud infrastructure monitoring service, will exhibit at SYS-CON's 16th International Cloud Expo®, which will take place on June 9-11, 2015, at the Javits Center in New York City, NY. Site24x7 is a cloud infrastructure monitoring service that helps monitor the uptime and performance of websites, online applications, servers, mobile websites and custom APIs. The monitoring is done from 50+ locations across the world and from various wireless carriers, thus providing a global perspective of the end-user experience. Site24x7 supports monitoring H...
Sonus Networks introduced the Sonus WebRTC Services Solution, a virtualized Web Real-Time Communications (WebRTC) offer, purpose-built for the Cloud. The WebRTC Services Solution provides signaling from WebRTC-to-WebRTC applications and interworking from WebRTC-to-Session Initiation Protocol (SIP), delivering advanced real-time communications capabilities on mobile applications and on websites, which are accessible via a browser.
SYS-CON Events announced today that Intelligent Systems Services will exhibit at SYS-CON's 16th International Cloud Expo®, which will take place on June 9-11, 2015, at the Javits Center in New York City, NY. Established in 1994, Intelligent Systems Services Inc. is located near Washington, DC, with representatives and partners nationwide. ISS’s well-established track record is based on the continuous pursuit of excellence in designing, implementing and supporting nationwide clients’ mission-critical systems. ISS has completed many successful projects in Healthcare, Commercial, Manufacturing, ...
SYS-CON Events announced today that B2Cloud, a provider of enterprise resource planning software, will exhibit at SYS-CON's 16th International Cloud Expo®, which will take place on June 9-11, 2015, at the Javits Center in New York City, NY. B2cloud develops the software you need. They have the ideal tools to help you work with your clients. B2Cloud’s main solutions include AGIS – ERP, CLOHC, AGIS – Invoice, and IZUM
SYS-CON Events announced today that Tufin, the market-leading provider of Security Policy Orchestration Solutions, will exhibit at SYS-CON's 16th International Cloud Expo®, which will take place on June 9-11, 2015, at the Javits Center in New York City, NY. As the market leader of Security Policy Orchestration, Tufin automates and accelerates network configuration changes while maintaining security and compliance. Tufin's award-winning Orchestration Suite™ gives IT organizations the power and agility to enforce security policy across complex, multi-vendor enterprise networks. With more than 1...
SYS-CON Events announced today that Cloudian, Inc., the leading provider of hybrid cloud storage solutions, will exhibit at SYS-CON's 16th International Cloud Expo®, which will take place on June 9-11, 2015, at the Javits Center in New York City, NY. Cloudian, Inc., is a Foster City, California - based software company specializing in cloud storage software. The main product is Cloudian, an Amazon S3-compliant cloud object storage platform, the bedrock of cloud computing systems, that enables cloud service providers and enterprises to build reliable, affordable and scalable cloud storage solu...
SYS-CON Events announced today that Gridstore™, the leader in hyper-converged infrastructure purpose-built to optimize Microsoft workloads, will exhibit at SYS-CON's 16th International Cloud Expo®, which will take place on June 9-11, 2015, at the Javits Center in New York City, NY. Gridstore™ is the leader in hyper-converged infrastructure purpose-built for Microsoft workloads and designed to accelerate applications in virtualized environments. Gridstore’s hyper-converged infrastructure is the industry’s first all flash version of HyperConverged Appliances that include both compute and storag...
Temasys has announced senior management additions to its team. Joining are David Holloway as Vice President of Commercial and Nadine Yap as Vice President of Product. Over the past 12 months Temasys has doubled in size as it adds new customers and expands the development of its Skylink platform. Skylink leads the charge to move WebRTC, traditionally seen as a desktop, browser based technology, to become a ubiquitous web communications technology on web and mobile, as well as Internet of Things compatible devices.
SYS-CON Events announced today that IDenticard will exhibit at SYS-CON's 16th International Cloud Expo®, which will take place on June 9-11, 2015, at the Javits Center in New York City, NY. IDenticard™ is the security division of Brady Corp (NYSE: BRC), a $1.5 billion manufacturer of identification products. We have small-company values with the strength and stability of a major corporation. IDenticard offers local sales, support and service to our customers across the United States and Canada. Our partner network encompasses some 300 of the world's leading systems integrators and security s...
“With easy-to-use SDKs for Atmel’s platforms, IoT developers can now reap the benefits of realtime communication, and bypass the security pitfalls and configuration complexities that put IoT deployments at risk,” said Todd Greene, founder & CEO of PubNub. PubNub will team with Atmel at CES 2015 to launch full SDK support for Atmel’s MCU, MPU, and Wireless SoC platforms. Atmel developers now have access to PubNub’s secure Publish/Subscribe messaging with guaranteed ¼ second latencies across PubNub’s 14 global points-of-presence. PubNub delivers secure communication through firewalls, proxy ser...
SYS-CON Events announced today that On the Avenue Marketing Group, a sales and marketing firm that utilizes events to market and sell products to consumers, will exhibit at SYS-CON's 16th International Cloud Expo®, which will take place on June 9-11, 2015, at the Javits Center in New York City, NY. On the Avenue Marketing Group (OTA) is a sales and marketing firm that utilizes events to market and sell products to consumers. On behalf of our clients, we attend thousands of fairs, festivals, expos, concerts, conferences, and sporting events annually, helping them reach millions of individuals ...
Containers and microservices have become topics of intense interest throughout the cloud developer and enterprise IT communities. Accordingly, attendees at the upcoming 16th Cloud Expo at the Javits Center in New York June 9-11 will find fresh new content in a new track called PaaS | Containers & Microservices Containers are not being considered for the first time by the cloud community, but a current era of re-consideration has pushed them to the top of the cloud agenda. With the launch of Docker's initial release in March of 2013, interest was revved up several notches. Then late last...
“In the past year we've seen a lot of stabilization of WebRTC. You can now use it in production with a far greater degree of certainty. A lot of the real developments in the past year have been in things like the data channel, which will enable a whole new type of application," explained Peter Dunkley, Technical Director at Acision, in this interview at @ThingsExpo, held Nov 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA.
Health care systems across the globe are under enormous strain, as facilities reach capacity and costs continue to rise. M2M and the Internet of Things have the potential to transform the industry through connected health solutions that can make care more efficient while reducing costs. In fact, Vodafone's annual M2M Barometer Report forecasts M2M applications rising to 57 percent in health care and life sciences by 2016. Lively is one of Vodafone's health care partners, whose solutions enable older adults to live independent lives while staying connected to loved ones. M2M will continue to gr...
SYS-CON Media announced today that @WebRTCSummit Blog, the largest WebRTC resource in the world, has been launched. @WebRTCSummit Blog offers top articles, news stories, and blog posts from the world's well-known experts and guarantees better exposure for its authors than any other publication. @WebRTCSummit Blog can be bookmarked ▸ Here @WebRTCSummit conference site can be bookmarked ▸ Here
SYS-CON Events announced today that Ciqada will exhibit at SYS-CON's @ThingsExpo, which will take place on June 9-11, 2015, at the Javits Center in New York City, NY. Ciqada™ makes it easy to connect your products to the Internet. By integrating key components - hardware, servers, dashboards, and mobile apps - into an easy-to-use, configurable system, your products can quickly and securely join the internet of things. With remote monitoring, control, and alert messaging capability, you will meet your customers' needs of tomorrow - today! Ciqada. Let your products take flight. For more inform...