JNI_CreateJavaVM returns -4

i have a little problem with my JNI_CreateJavaVM source:
when i try to create a new JVM with JNI_CreateJavaVM i sometimes get the error-code -4 (NOT ENOUTH MEMORY). I tried different values for the maxHeapSize (Xmx) but no luck...
I don't think it is a real memory problem, because the machine the program is running on has 2GB of RAM and only 800MB are in use.
Are there any parameters for the JVM i missed (currently i use
options[0].optionString = "-Xmx32m";
options[1].optionString = "-Djava.class.path=.";
options[2].optionString = "-Djava.compiler=NONE";
thanks
thomas buesser

Awesome! That solves the problem. I was setting "-Xms256M -Xmx512M" which I'd also been using on the Java command line.
Thanks again :-)

Similar Messages

  • JNI_CreateJavaVM returns JNI_ENOMEM (-4) from different versions of the jre

    I have created a JNI dll, invoked from a VBA Excel add-in to execute Java code. This works fine until I introduce the -Xmx parameter as a vm option.
    Before creating the VM, I use a VirtualAlloc/Free loop to make sure the -Xmx parameter is not too large, decrementing it by 2MB each time until an allocable amount is found (thanks to [jurberg's post|http://forums.sun.com/thread.jspa?forumID=37&threadID=5220601]; my version, slightly modified, is posted below). I then pass that value to the VM via the -Xmx option.
    This works great when I am using a JRE 1.6 installed in the "C:\Program Files\Java\*jre1.6.0_xx"* directory. When the same* JRE version is installed in the "C:\Program Files\Java\*jre6*" directory, JNI_CreateJavaVM fails with JNI_ENOMEM. Calling GetLastError returns 0 ("operation completed successfully"). Using a *1.5 JRE*, this also fails, returning JNI_ENOMEM, but GetLastError returns error code 6 ("the handle is invalid").
    A little about my platform:
         Windows XP Pro
         Building JNI dll using Microsoft Visual C++ 2008 and 1.5 JDK
    I have multiple JREs and JDKs installed on my system as this is a dev machine, but I have the same problem on a non-dev machine running XP Home.
    Here is a snippet of my code used to create the vm:
         // create the JNI structures
         const int numOptions = args.size();
         JavaVMInitArgs vm_args;
         JavaVMOption* options = new JavaVMOption[numOptions];
            log("Creating JVM with parameters:");
            int i = 0;
            char * nextArg;
            for (itr=args.begin(); itr != args.end(); itr++) {
                nextArg = new char[(*itr).length() + 1];
                strcpy(nextArg, (*itr).c_str());
                options.extraInfo = NULL;
    options[i++].optionString = nextArg;
    log("\t" + string(nextArg));
         vm_args.version = CRUSH_JNI_VERSION;
         vm_args.options = options;
         vm_args.nOptions = numOptions;
         vm_args.ignoreUnrecognized = JNI_FALSE;
    // load and initialize the Java VM, and return a JNI interface pointer
    JNIEnv* env = NULL;
         err = (*createVM)(&jvm, (void**)&env, &vm_args);
         // err is -4 (JNI_ENOMEM) in the cases described above
    Does anyone have any suggestions on what is going on here and how I might make this code stable for all 1.5 and 1.6 JREs, regardless of where they are installed?
    Thanks in advance,
    Sarah
    Code to determine max -Xmx value:static const DWORD NUM_BYTES_PER_MB = 1024 * 1024;
    bool canAllocate(DWORD bytes)
    LPVOID lpvBase;
    lpvBase = VirtualAlloc(NULL, bytes, MEM_RESERVE, PAGE_READWRITE);
    if (lpvBase == NULL) return false;
    VirtualFree(lpvBase, 0, MEM_RELEASE);
    return true;
    int getMaxHeapAvailable(int permGenMB, int maxHeapMB)
    DWORD          originalMaxHeapBytes = 0;
    DWORD          maxHeapBytes = 0;
    int               numMemChunks = 0;
    SYSTEM_INFO          sSysInfo;
    DWORD          maxPermBytes = permGenMB * NUM_BYTES_PER_MB;     // Perm space is in addition to the heap size
    DWORD          numBytesNeeded = 0;
    GetSystemInfo(&sSysInfo);
    // jvm aligns as follows:
    // quoted from size_t GenCollectorPolicy::compute_max_alignment() of jdk 7 hotspot code:
    // The card marking array and the offset arrays for old generations are
    // committed in os pages as well. Make sure they are entirely full (to
    // avoid partial page problems), e.g. if 512 bytes heap corresponds to 1
    // byte entry and the os page size is 4096, the maximum heap size should
    // be 512*4096 = 2MB aligned.
    // card_size computation from CardTableModRefBS::SomePublicConstants of jdk 7 hotspot code
    int card_shift = 9;
    int card_size = 1 << card_shift;
    DWORD alignmentBytes = sSysInfo.dwPageSize * card_size;
    maxHeapBytes = maxHeapMB * NUM_BYTES_PER_MB;
    // make it fit in the alignment structure
    maxHeapBytes = maxHeapBytes + (maxHeapBytes % alignmentBytes);
    numMemChunks = maxHeapBytes / alignmentBytes;
    originalMaxHeapBytes = maxHeapBytes;
    // loop and decrement requested amount by one chunk
    // until the available amount is found
    numBytesNeeded = maxHeapBytes + maxPermBytes;
    while (!canAllocate(numBytesNeeded) && numMemChunks > 0)
    numMemChunks --;
    maxHeapBytes = numMemChunks * alignmentBytes;
    numBytesNeeded = maxHeapBytes + maxPermBytes;
    if (numMemChunks == 0) return 0;
    // we can allocate the requested size, return it now
    if (maxHeapBytes == originalMaxHeapBytes) return maxHeapMB;
    // calculate the new MaxHeapSize in megabytes
    return maxHeapBytes / NUM_BYTES_PER_MB;

    I have a similar, but I think much simpler problem. Namely, I get ENOMEM's when as far as I can tell there's plenty of memory available. It seems to have something to do with how Windows is configured, although I've never been able to determine what it could be.FWIW, in my case, I found that if I loaded my JNI dll into a console process, the max heap requested was always allocated. But when loading into Excel, the same amount would be too much. This was partly due to the fact that Excel has its own memory management, limiting the amount of memory workbooks can use. Also, it could be due to the vm not being able to reserve a contiguous chunk of memory for the max heap space.
    Why (and how) separate the permanent generation space from the rest of the max heap? It seems you'll fail if you can't get that much space (which is the why) but how did you determine what it is?The VM uses the perm gen space plus the requested max heap space when attempting the VirtualAlloc call to verify that it can allocate the specified amount. The default perm gen is 64MB, but that can be changed via the -XX:MaxPermSize vm parameter, so I allow for any requested value.
    What's CRUSH_JNI_VERSION? It's not in any .h file I have.That's just my own constant defined to be either JNI_VERSION_1_4 or JNI_VERSION_1_6.
    Why are you messing with the bootclasspath? (I suspect you're adding something to it. Generally the VM can find it's own damn classpath).Yep, I'm adding the 2.1 JAXB jar to the bootclasspath because earlier 1.6 distributions included JAXB 2.0 and I needed 2.1.
    -sarah

  • Under what circumstances JNI_CreateJavaVM will return 0

    Hello all,
    Can any one please tell me "under what cicumstances JNI_CreateJavaVM returns 0" ?
    The following code segment returns 0.
    when I try to debug the code segment using VC++ 6.0. jdk 1.4.1 ON WINDOWS 2000 Prof. The debugger first shows status = -1 but once JNI_CreateJavaVM is executed the status changes to 0.
    // ----- code segment ----------------
    JavaVMOption options[3];
    JavaVMInitArgs vm_args;
    JavaVM *jvm;
    JNIEnv *env;
    options[0].optionString = "-Djava.compiler=NONE";
    options[1].optionString = "-Djava.class.path=CLASSPATH";
    options[2].optionString = "-verbose:jni";
    vm_args.version=JNI_VERSION_1_4;
    vm_args.options = options;
    vm_args.nOptions = 3;
    vm_args.ignoreUnrecognized = JNI_FALSE;
    int status = -1;
    status = (jint)JNI_CreateJavaVM(&jvm, (void**)&env, &vm_args);
    if (status < 0)
    printf("\nERROR : Creating JVM with status : %d.\n");
    else if (status == JNI_ERR)
         printf("\nERROR : Creating Java Virtual Machine (JVM).\n");
    else if (status == 0)
    printf("\nJVM status is 0.\n\n");
    else
    printf("\nVM is created.");
    Please help I could not get any clue.
    Thanks.

    Hello folks,
    Now it is ok, it was not ststus=0 but it was some junk number
    forget it

  • Creating Multiple JVMS with JNI_CreateJavaVM

    Hey there
    I'm trying to create 2 JVMS in from within a C++ program - in order to start a couple of Java servers. I've been hunting around the discussion groups and the web and there are references to not being able to create more than a single JVM with JDK 1.1 but it's claimed you can do it with JDK 1.2 onwards. I just tried it and the second invocation of JNI_CreateJavaVM returns -1. I then found a page saying that the JNI_CreateJavaVM invocations have to be in separate threads so I created a couple of threads using AfxBeginThread (using Win NT) and called JNI_CreateJavaVM once within each thread. The thread which gets to the JNI call second still returns -1.
    Has anyone got this to work ???

    You can only create one Java VM per process. For additional threading into the VM, you will need to call the AttachCurrentThread method on any additional thread that you want to execute in the VM. This only works for Win32 in 1.1

  • JNI_CreateJavaVM fails on Windows - Very urgent

    Folks,
    I am very much new to the JNI on Windows 2000. For the last two days, I am trying to load JVM into my application. But, could not succeed. Even the samples I got across the net failed. The problem is "JNI_CreateJavaVM" returns -1.
    Using Microsoft Visual Studio 6.0, and VC++, I created a project with default settings and used the following sample code and it fails left and right. Please, let me know if I am doing something wrong.
    Sample
    JNIEnv *env = NULL;
    JavaVMInitArgs vm_args;     
    JavaVMOption options[4];
    char a1,a2;
    int nbOptions;
    jint res = 0;
    char classpath,librarypath;
    classpath = malloc(1024,sizeof(char));
    librarypath= malloc(1024,sizeof(char));
    strcpy(classpath, "-Djava.class.path=e:\\jdk1.2.2;e:\\jdk1.2.2\\jre\\lib\\i18n.jar");
    strcpy(librarypath, "-Djava.library.path=.;e:\\jdk1.2.2\\jre\\bin;e:\\jdk1.2.2\\jre\\bin\\classic");
    options[0].optionString = classpath;
    options[1].optionString = librarypath;
    options[2].optionString = "-Djava.compiler=NONE";
    options[3].optionString = "-verbose:jni";
    vm_args.version = JNI_VERSION_1_2;
    vm_args.options = options;
    vm_args.nOptions = 4;
    vm_args.ignoreUnrecognized = JNI_TRUE;
    res = JNI_CreateJavaVM(&jvm,(void **)&env,&vm_args);
    I tried with other samples also. But, the result is same. JNI_CreateJavaVM returns -1.
    If possible, please respond to [email protected] also
    Thanks,
    Lokesh

    strcpy(librarypath, "-Djava.library.path=.;e:\\jdk1.2.2\\jre\\bin;e:\\jdk1.2.2\\jre\\bin\\classic");
    options[1].optionString = librarypath;This doesn't do what the author probably expected. This specifies the path(s) for Java to load native libraries from -- this is different from the path where you actually want to load the JVM from. That path is up to the system and where things happen to be, unless you specify it explicitly in your call to load jvm.dll in the case of Windows, and I assume you use the system call LoadLibrary() on Windows in order to do this. If you do not (and you don't use some other Win API call for this purpose) then you are depending entirely on your system's environment variables in order to create the JVM instance.
    So, it is not something that Sun has to do anything about.

  • When JNI_CreateJavaVM throws negative value

    when JNI_CreateJavaVM return value is negative value, does it mean
    already jvm exits.
    i try to grab the jvm using getjvms, the command returns zero code but the number of jvms is 0.
    thanks in advance
    gvkk

    the code is , i am able to successfully compile(1 warning about the exit command)and linking also successfull.when i execute it returns -1 value (JNI_ERR).this code is from forum.i have tried with the code listed in JNI specs it throws the same error.
    thanks for your time in advance
    #include <jni.h>
    main() {
    JavaVMOption options[3];
    JavaVMInitArgs vm_args;
    JavaVM *jvm;
    JNIEnv *env;
    long result;
    jmethodID mid;
    jclass cls;
    jobjectArray args;
    jstring jstr;
    options[0].optionString = "-Djava.class.path=.";
    options[1].optionString = "-Djava.compiler=NONE";
    options[2].optionString = "-verbose:jni";
    vm_args.version = JNI_VERSION_1_2;
    vm_args.options = options;
    vm_args.nOptions = 2;
    vm_args.ignoreUnrecognized = JNI_FALSE;
    /* Create the Java VM */
    result = JNI_CreateJavaVM(&jvm,(void **)&env, &vm_args);
    printf("JVM created\n");
    if(result == JNI_ERR ) {
    printf("Error invoking the JVM");
    exit (-1);
    cls = (*env)->FindClass(env, "Prog");
    if (cls == 0) {
    fprintf(stderr, "Can't find Prog class\n");
    exit(1);
    mid = (*env)->GetStaticMethodID(env,
    cls, "main", "([Ljava/lang/String;)V");
    if (mid == 0) {
    fprintf(stderr, "Can't find Prog.main\n");
    exit(1);
    jstr = (*env)->NewStringUTF(env, " from C!");
    if (jstr == 0) {
    fprintf(stderr, "Out of memory\n");
    exit(1);
    args = (*env)->NewObjectArray(env, 1,
    (*env)->FindClass
    (env, "java/lang/String"), jstr);
    if (args == 0) {
    fprintf(stderr, "Out of memory\n");
    exit(1);
    (*env)->CallStaticVoidMethod(env, cls, mid, args);
    (*jvm)->DestroyJavaVM(jvm);

  • Unable to create a JVM in Linux

    I have an applicaton that runs fine on WinNT 4.0 and in RedHat Linux 7.3 I am unable to create a JVM in the native environment. The call to JNI_CreateJavaVM() returns a -3. What I can see of the class path that is passed to the JVM is correct but fails. I am running with the j2sdk-1.3.1_04-linux package I installed today.
    Any help on this would be greatly appreciated.

    What does your LD_LIBRARY_PATH look like?

  • Starting JVM issues...

    I am trying to launch the JVM and it is a pain in the ass since it still isn't working. it keeps returning a from the create method, when i leave something out of the vmargs, like the version, it will return a -3.
    i am lost of where to go with this. I need to launch the VM somehow to use DLL's that reference a java app and java classes. is it possible to turn on logging to see where it is dying or why it is not launching?
    //Variables seen by start_jvm function
    JNIEnv *env = NULL;
    JavaVM *jvm;
    JavaVMInitArgs vm_args;
    JavaVMOption options[4];
    char *environment;
    char *puid;
    char *envKey = "CLASSPATH";
    //Function to start JVM and then FindClass
    int start_jvm(int argc, char* argv[])
        int res;
        char envarray[1024];
        printf("Starting JVM.\n");
        environment = getenv(envKey);
        options[0].optionString = "-Djava.class.path=C:\\JBuilderX\\jdk1.4\\jre\\lib\\rt.jar;C:\\PROGRA~1\\COEMES~1\\data\\classes.jar";
        options[1].optionString = "-Djava.compiler=NONE";
        options[2].optionString = "-verbose:gc,class,jni";
         vm_args.version = 0x00010002;
         vm_args.options = options;
         vm_args.nOptions = 3;
         vm_args.ignoreUnrecognized = TRUE;
        // Create the Java VM
        if(env == NULL)
            printf("No JVM running\n");
              //res = (*jvm)->AttachCurrentThread(jvm, (void**)&env, NULL);
            res = JNI_CreateJavaVM(&jvm,(void**)&env,&vm_args);
            if (res < 0)
                printf("Can't create Java VM\n");
                return -1;
            printf("JVM created\n");
        else
            printf("JVM already running");
        return 0;
    }

    > it keeps returning a [what?] from the create method
    What does JNI_CreateJavaVM return when you pass a correct init structure as shown in your code?
    (BTW, you can improve readability by using macro JNI_VERSION_1_2 instead of hard coding 0x00010002.)
    > when i leave something out of the vmargs, like the version, it will return a -3
    You mean if you deliberately leave the version field as a garbage value, it returns JNI_EVERSION? That makes sense.
    Possibly key question: where is your jvm.dll located?
    -slj-

  • JNI_CreateJavaVM trouble; returns -4

    Hello all,
    Has anyone seen a problem with the JNI_CreateJavaVM function returning a -4? This problem is happening on one our client machines that has Windows Server 2003, SP1 installed. This problem only shows up when using a web client. Console applications work fine and not all web clients running on different machines are getting this error. The client is running the OS on VMWare. I have been able to replicate the problem under SP2 only. Currently, I think that there must be some patch that was applied that is causing the problem because the error doesn't happen on other machines. Hmmmm.
    Appreciate any help,
    Wes

    Yah - no fun.
    Better post some relevant code - maybe folks can help.

  • JNI_CreateJavaVM() (1.4.0) NEVER returns if I call it from DLL !

    Hello,
    I'm invoking java application from C++ exe (Win2000) and this works almost fine (except DestroyJavaVM()), but if the same piece of code that handles Java resides in DLL then JNI_CreateJavaVM() (1.4.0) NEVER returns and the process gets stuck !!!
    What could be the reason ?
    Thanx !

    Hi,
    JVM can start java application from DLL if the application (that embeds java application and DLL) has message loop (or simple endless while loop, I tested).
    Vitally

  • Why can't I build up a VM when calling JNI_CreateJavaVM?

    Hello,everyone,I got a new question,I want to call java in linux redhat 7.3,but it is strange that I failed, though my code seems quite right,please :
    #include "jni.h"
    #include "dlfcn.h"
    #include "iostream.h"
    #include "string.h"
    #define MAX_PATH 266
    typedef jint (* JNI_CREATEJAVAVM)(JavaVM **pvm, void ** penv, void *args);
    JavaVM *jvm;
    main()
         char szJvm[MAX_PATH]="/usr/java/j2re1.4.0_01/lib/i386/client/libjvm.so";
    //I will load libjvm.so with dlopen later
    //to receive JreDir
         jclass cls;
    jmethodID mid;
         int result;
         JavaVMInitArgs vm_args;
         JavaVMOption options[2];
         jint ret = -1;
         void *hLib;
         char *error=0;
         JNI_CREATEJAVAVM pfCreateJavaVM = 0;
         JNIEnv *env;
         hLib = dlopen(szJvm,RTLD_LAZY);
         if(hLib == 0)
              cout<<"Can not load library libjvm.so of Jre!"<<endl;
              return false;
         else
         cout<<"libjvm.so has been loaded in"<<endl;
         options[0].optionString = "-Djava.compiler=NONE";
         options[1].optionString = "-Djava.class.path=.";
         vm_args.version = JNI_VERSION_1_4;
         vm_args.options = options;
         vm_args.nOptions = 2; //element number of options[4]
         vm_args.ignoreUnrecognized = true;
         /*Create Java VM*/
         pfCreateJavaVM=(JNI_CREATEJAVAVM)dlsym(hLib, "JNI_CreateJavaVM");
         error=dlerror();
         if(error) //error
              //Can't Get JNI_CreatJavaVM address
              cout<<"Can not find JNI_CreatJavaVM function in libjvm.so"<<endl;
              return false;
         else
              //jvm receive the VM being created
              //env is the environment which contains all methods of java class
              ret = (*pfCreateJavaVM)(&jvm,(void**)&env,&vm_args);
         if (ret < 0)
              //failed to create VM
    cout<<"Can not create Java VM"<<endl;
    return false;
         else
         cout<<"Virtual machine has been set up"<<endl;
    And I compile it like this:
    g++ Send.cpp -rdynamic -ldl
    Then when I run it: ./a.out
    it shows error message:
    libjvm.so has been loaded in
    Error occurred during initialization of VM
    Unable to load native library: libjvm.so: cannot open shared object file: No
    such file or directory
    I don't know what has happened.Help me please,thank you!

    Asimov,
    I have worked with JNI on OS/2 and all I can suggest is the following points...
    Hello,everyone,I got a new question,I want to call
    java in linux redhat 7.3,but it is strange that I
    failed, though my code seems quite right,please :
    #include "jni.h"
    #include "dlfcn.h"
    #include "iostream.h"
    #include "string.h"
    #define MAX_PATH 266Make this "#define MAX_PATH 1024". My code would not work with this path set to anything else. It may be OS/2 related, but try this anyway.
    >
    typedef jint (* JNI_CREATEJAVAVM)(JavaVM **pvm, void
    ** penv, void *args);
    JavaVM *jvm;
    main()
    char
    szJvm[MAX_PATH]="/usr/java/j2re1.4.0_01/lib/i386/clien
    /libjvm.so";
    //I will load libjvm.so with dlopen later
    //to receive JreDir
         jclass cls;
    jmethodID mid;
         int result;
         JavaVMInitArgs vm_args;
         JavaVMOption options[2];
         jint ret = -1;
         void *hLib;
         char *error=0;
         JNI_CREATEJAVAVM pfCreateJavaVM = 0;
         JNIEnv *env;
         hLib = dlopen(szJvm,RTLD_LAZY);
         if(hLib == 0)
    cout<<"Can not load library libjvm.so of
    f Jre!"<<endl;
              return false;
         else
         cout<<"libjvm.so has been loaded in"<<endl;
         options[0].optionString = "-Djava.compiler=NONE";
         options[1].optionString = "-Djava.class.path=.";
         vm_args.version = JNI_VERSION_1_4;
         vm_args.options = options;
    vm_args.nOptions = 2; //element number of
    options[4]
         vm_args.ignoreUnrecognized = true;
         /*Create Java VM*/
         You have configured some 'user' options here but you must get the 'system arguments' for the JVM also.
    Make a call to 'JNI_GetDefaultJavaVMInitArgs( &vm_args )', then pass 'vm_args' into your JNI_CREATEJAVAVM function later.
    pfCreateJavaVM=(JNI_CREATEJAVAVM)dlsym(hLib,
    , "JNI_CreateJavaVM");
         error=dlerror();
         if(error) //error
              //Can't Get JNI_CreatJavaVM address
    cout<<"Can not find JNI_CreatJavaVM function in
    n libjvm.so"<<endl;
              return false;
         else
              //jvm receive the VM being created
    //env is the environment which contains all methods
    s of java class
    ret =
    = (*pfCreateJavaVM)(&jvm,(void**)&env,&vm_args);
         if (ret < 0)
              //failed to create VM
    cout<<"Can not create Java VM"<<endl;
    return false;
         else
         cout<<"Virtual machine has been set up"<<endl;
    And I compile it like this:
    g++ Send.cpp -rdynamic -ldl
    Then when I run it: ./a.out
    it shows error message:
    libjvm.so has been loaded in
    Error occurred during initialization of VM
    Unable to load native library: libjvm.so: cannot
    t open shared object file: No
    such file or directory
    I don't know what has happened.Help me please,thank
    you!
    Try those small things and let me know what it returns.
    Bryan Galvin.
    Software Engineer.

  • How much space does JNI_CreateJavaVM

    Many of us who try to intialize Java inside another processes address space find problem with space, e.g., we get inexplicable ENOMEM's returned from the JNI_CreateJavaVM call. Apparently, the problem is that the VM needs contiguous address space. But, how does it determine how much it needs?
    Consider the solution in [S. Carlson's post|http://forums.sun.com/thread.jspa?threadID=5403763&tstart=0] . This solution looks for a contiguous block of memory large enough to hold the Permanent Generation (+-XX:MaxPermSpace+) space and the maximum heap (+-Xmx+) space. But it doesn't work. I'm guessing this is because the VM wants to put other stuff into that address space. My question is: What? And how do I decide how much space it wants?
    Conversely: What would happen if I iterate over the CreateJavaVM call, reducing the space requirement, until it worked? Would that work? I intend to try it, but I'm hoping somebody might tell me if it's a good idea before I waste my time.

    Conversely: What would happen if I iterate over the CreateJavaVM call, reducing the space requirement, until it worked? Would that work? I intend to try it, but I'm hoping somebody might tell me if it's a good idea before I waste my time.That won't work because CreateJavaVM sets a flag that indicates whether or not the vm creation can be re-attempted. In the case of ENOMEM, it cannot. The second attempt to call CreateJavaVM will return -1.

  • Facing problem during invoking JNI_CreateJavaVM()  method

    Hi,
    I am stucking in this problem, the method returns -1. So I am not able to resolve this problem. I am using j2sdk1.4.2_14 and and using VC++6.0 for creatinf exe
    Any help will be appreciated.
    Rgds
    ojak
         #include <jni.h>
         #include <windows.h>
         #define PATH_SEPARATOR ';'
    //     #define USER_CLASSPATH "C:\\ojak\\JNIEXAMPLES\\attachThread\\" /* where Prog.class is */
    //     #define USER_CLASSPATH "." /* where Prog.class is */
         void main() {
         JNIEnv *env;
         //JavaVM jvm = (JavaVM )0;
              //JNIEnv *env=0;
         JavaVM *jvm=0;
         jint res;
         jclass cls;
         jmethodID mid;
         jstring jstr;
         jobjectArray args;
         HINSTANCE hVM = NULL;
         JavaVMInitArgs vm_args;
         JavaVMOption options[4];
         printf("\noptions");
         options[1].optionString = "-Djava.class.path=c:\\j2sdk1.4.2_14\\jre\\lib\\rt.jar;C:\\ojak\\JNIEXAMPLES\\attachThread"; /* user classes */
    //     options[2].optionString = "-Djava.library.path=C:\\j2sdk1.4.2_14\\lib\\jvm.lib"; /* set native library path */
         options[2].optionString = "-Djava.library.path=C:\\j2sdk1.4.2_14\\jre\\bin\\client\\jvm.dll"; /* set native library path */
         options[0].optionString = "-Djava.compiler=NONE";
         //options[1].optionString = "-Djava.class.path=c:\\My Folder"; /* user classes */
         //options[2].optionString = "-Djava.library.path=C:\\j2sdk1.4.2_04\\include";
         options[3].optionString = "-verbose:jni";
         printf("%s\n",options[0].optionString);
         printf("%s\n",options[1].optionString);
         printf("%s\n",options[2].optionString);
         printf("%s\n",options[3].optionString);
         hVM = LoadLibrary("C:\\j2sdk1.4.2_14\\jre\\bin\\client\\jvm.dll");
         printf("\nversion info");
         //vm_args.version = JNI_VERSION_1_4;
         vm_args.version = JNI_VERSION_1_2;
         vm_args.options = options;
         vm_args.nOptions = 4;
         vm_args.ignoreUnrecognized = JNI_FALSE;
         printf("\ncreate\n");
         if (hVM == NULL)
         printf("hVM is null ");
         if(jvm==NULL)
         printf(" It has not value\n");
         else
              printf("It contains value\n");
         res = JNI_CreateJavaVM(&jvm, (void **)&env, &vm_args);
    if(jvm==NULL)
              printf("JVM is null\n");
         if(env==NULL)
              printf("ENV is null\n");
         if (res < 0) {
         fprintf(stderr, "Can't create Java VM \n",res);
         exit(1);
         cls = env->FindClass("HelloWorld");
         //cls = env.FindClass(env,"helloWorldClass");
         if (cls == 0) {
         fprintf(stderr, "Can't find Prog class\n");
         exit(1);
         mid = env->GetStaticMethodID(cls, "main", "([Ljava/lang/String;)V");
         if (mid == 0) {
         fprintf(stderr, "Can't find Prog.main\n");
         exit(1);
         jstr = env->NewStringUTF(" from C!");
         if (jstr == 0) {
         fprintf(stderr, "Out of memory\n");
         exit(1);
         args = env->NewObjectArray(1, (*env).FindClass("java/lang/String"), jstr);
         if (args == 0) {
         fprintf(stderr, "Out of memory\n");
         exit(1);
         env->CallStaticVoidMethod(cls, mid, args);
         jvm->DestroyJavaVM();

    Hi,
    I am stucking in this problem, the method returns -1. So I am not able to resolve this problem. I am using j2sdk1.4.2_14 and and using VC++6.0 for creatinf exe
    Any help will be appreciated.
    Rgds
    ojak
         #include <jni.h>
         #include <windows.h>
         #define PATH_SEPARATOR ';'
    //     #define USER_CLASSPATH "C:\\ojak\\JNIEXAMPLES\\attachThread\\" /* where Prog.class is */
    //     #define USER_CLASSPATH "." /* where Prog.class is */
         void main() {
         JNIEnv *env;
         //JavaVM jvm = (JavaVM )0;
              //JNIEnv *env=0;
         JavaVM *jvm=0;
         jint res;
         jclass cls;
         jmethodID mid;
         jstring jstr;
         jobjectArray args;
         HINSTANCE hVM = NULL;
         JavaVMInitArgs vm_args;
         JavaVMOption options[4];
         printf("\noptions");
         options[1].optionString = "-Djava.class.path=c:\\j2sdk1.4.2_14\\jre\\lib\\rt.jar;C:\\ojak\\JNIEXAMPLES\\attachThread"; /* user classes */
    //     options[2].optionString = "-Djava.library.path=C:\\j2sdk1.4.2_14\\lib\\jvm.lib"; /* set native library path */
         options[2].optionString = "-Djava.library.path=C:\\j2sdk1.4.2_14\\jre\\bin\\client\\jvm.dll"; /* set native library path */
         options[0].optionString = "-Djava.compiler=NONE";
         //options[1].optionString = "-Djava.class.path=c:\\My Folder"; /* user classes */
         //options[2].optionString = "-Djava.library.path=C:\\j2sdk1.4.2_04\\include";
         options[3].optionString = "-verbose:jni";
         printf("%s\n",options[0].optionString);
         printf("%s\n",options[1].optionString);
         printf("%s\n",options[2].optionString);
         printf("%s\n",options[3].optionString);
         hVM = LoadLibrary("C:\\j2sdk1.4.2_14\\jre\\bin\\client\\jvm.dll");
         printf("\nversion info");
         //vm_args.version = JNI_VERSION_1_4;
         vm_args.version = JNI_VERSION_1_2;
         vm_args.options = options;
         vm_args.nOptions = 4;
         vm_args.ignoreUnrecognized = JNI_FALSE;
         printf("\ncreate\n");
         if (hVM == NULL)
         printf("hVM is null ");
         if(jvm==NULL)
         printf(" It has not value\n");
         else
              printf("It contains value\n");
         res = JNI_CreateJavaVM(&jvm, (void **)&env, &vm_args);
    if(jvm==NULL)
              printf("JVM is null\n");
         if(env==NULL)
              printf("ENV is null\n");
         if (res < 0) {
         fprintf(stderr, "Can't create Java VM \n",res);
         exit(1);
         cls = env->FindClass("HelloWorld");
         //cls = env.FindClass(env,"helloWorldClass");
         if (cls == 0) {
         fprintf(stderr, "Can't find Prog class\n");
         exit(1);
         mid = env->GetStaticMethodID(cls, "main", "([Ljava/lang/String;)V");
         if (mid == 0) {
         fprintf(stderr, "Can't find Prog.main\n");
         exit(1);
         jstr = env->NewStringUTF(" from C!");
         if (jstr == 0) {
         fprintf(stderr, "Out of memory\n");
         exit(1);
         args = env->NewObjectArray(1, (*env).FindClass("java/lang/String"), jstr);
         if (args == 0) {
         fprintf(stderr, "Out of memory\n");
         exit(1);
         env->CallStaticVoidMethod(cls, mid, args);
         jvm->DestroyJavaVM();

  • Error occuring with JNI_CreateJavaVM: implicity dependency

    Hi ,
    I tried to create example program of JNI as shown in trial. I wanted to invoke a java program from C. I am unable to compile it. I am sending the compile command and the output I got. I used jni version 1.2
    ##########Compile Command#########
    gcc -I/usr/java1.3.1/include/ -I/usr/java1.3.1/include/solaris -L/usr/java1.3.1/jre/lib/sparc/ -ljava invokenew.c
    *************Output*******************
    Undefined first referenced
    symbol in file
    JNI_CreateJavaVM /var/tmp/ccmQWGHn.o (symbol belongs to implicit dependency /usr/java1.3.1/jre/lib/sparc//libjvm.so)
    ld: fatal: Symbol referencing errors. No output written to a.out
    collect2: ld returned 1 exit status
    I would be glad if someone can answer my question.
    Thank you,
    Kiran

    You should be linking with libjvm.so.
    God bless,
    -Toby Reyelts
    Check out Jace, http://jace.reyelts.com/jace

  • Can't get JNI_CreateJavaVM to work on linux

    i am using linux redhat 7.1 and jdk1.3.1_02 and i cannot get past the JNI_CreateJavaVM call. this same code works fine under windows.
    here's my code snippet:
    #include <stdio.h>#include <memory.h>
    #define NUMBER_OF_JVM_OPTIONS 2
    static STRING_UTF8 CLASS_PATH =  "-Djava.class.path=/usr/local/LPDProgress/LPDProgress.jar:";
    static STRING_UTF8 SECURITY_POLICY =  "-Djava.security.policy=/usr/local/LPDProgress/LPDProgress.policy";
    JavaVM*           jvm = NULL;
    JNIEnv*           env = NULL;
    int JNI_Init ( void )
      JavaVMInitArgs  jvmArgs;
      JavaVMOption    jvmOptions[NUMBER_OF_JVM_OPTIONS];
      int rc;
      if (jvm == NULL)
        memset(&jvmArgs, 0, sizeof(jvmArgs));
        jvmArgs.version = JNI_VERSION_1_2;
        jvmArgs.ignoreUnrecognized = TRUE;
        JNI_GetDefaultJavaVMInitArgs(&jvmArgs);
        jvmOptions[0].optionString = SECURITY_POLICY;
        jvmOptions[1].optionString = CLASS_PATH;
        jvmArgs.nOptions = NUMBER_OF_JVM_OPTIONS;
        jvmArgs.options = jvmOptions;
        rc = JNI_CreateJavaVM(&jvm, (void**) &env, &jvmArgs);
        if (rc == JNI_ERR)
          jvm = NULL;
          printf("Error creating JVM.\n");
          return 0;
    ... snip ...I never return from the JNI_CreateJavaVM call. it core dumps with green_threads and "hangs" with native_threads.
    here's my build script:
    #! /bin/bash
    gcc -Wall -c -I /usr/local/java2/include/ -I /usr/local/java2/include/linux/ foo.c
    gcc -Wall -I /usr/local/java2/include/ -I /usr/local/java2/include/linux/ -L /usr/local/java2/jre/lib/i386/ -ljava -lverify -L /usr/local/java2/jre/lib/i386/classic/ -ljvm -L /usr/local/java2/jre/lib/i386/native_threads/ -lhpi foo.o foo_test.c -o foo_testRegards,
    Floyd Shackelford
    4 Peaks Technology Group, Inc.
    VOICE: 334.735.9428
    FAX: 916.404.7125
    EMAIL: [email protected]
    acta non verba

    the described behavior only occurs when i run as root. when i run as a non-root user, i get a valid
    createjvm, but the next call, findclass, gets a sig 11 as follows:
    1
    2
    3
    4
    SIGSEGV   11*  segmentation violation
        si_signo [11]: SIGSEGV   11*  segmentation violation
        si_errno [0]: Success
        si_code [0]: SI_USER [pid: 0, uid: 0]
            stackpointer=0xbffff33c
    Full thread dump Classic VM (1.3.1_02-b02, native threads):
        "Finalizer" (TID:0x40efb528, sys_thread_t:0x808f320, state:R) prio=8
        "Reference Handler" (TID:0x40efb300, sys_thread_t:0x8089530, state:R) prio=10
        "SIGQUIT handler" (TID:0x40efb330, sys_thread_t:0x80874d0, state:R) prio=5
        "main" (TID:0x40efb1b0, sys_thread_t:0x804a780, state:R) prio=5
    Monitor Cache Dump:
        java.lang.Class@40F04E40/40F828C8: owner "main" (0x804a780) 1 entry
    Registered Monitor Dump:
        utf8 hash table: <unowned>
        JNI pinning lock: <unowned>
        JNI global reference lock: <unowned>
        BinClass lock: <unowned>
        Class linking lock: <unowned>
        System class loader lock: <unowned>
        Code rewrite lock: <unowned>
        Heap lock: <unowned>
        Monitor cache lock: owner "main" (0x804a780) 1 entry
        Thread queue lock: owner "main" (0x804a780) 1 entry
        Monitor registry: owner "main" (0x804a780) 1 entrymy expanded code snippet is as follows:
    // choose one or the other
    //#define WINDOWS 1
    #define LINUX 1
    #ifdef WINDOWS
    #include <windows.h>
    #endif
    #include <stdio.h>
    #include <memory.h>
    #include "LPDProgress.h"
    #define NUMBER_OF_JVM_OPTIONS 2
    #ifdef LINUX
    #ifndef TRUE
    #define TRUE  1
    #endif
    #ifndef FALSE
    #define FALSE 0
    #endif
    static STRING_UTF8 CLASS_PATH =
      "-Djava.class.path=/usr/local/LPDProgress/LPDProgress.jar:";
    static STRING_UTF8 SECURITY_POLICY =
      "-Djava.security.policy=/usr/local/LPDProgress/LPDProgress.policy";
    #endif LINUX
    #ifdef WINDOWS
    static STRING_UTF8 CLASS_PATH =
      "-Djava.class.path=/cvs/PayToPrint/LPDProgress/Class/;/cvs/PayToPrint/GUIServer/Class/;/cvs/PayToPrint/UtilityClasses/Class/;";
    //  "-Djava.class.path=/cvs/PayToPrint/Install/Diginet_LX/LPDProgress/LPDProgress.jar;";
    //  "-Djava.class.path=/Program Files/Diginet_LX/LPDProgress/LPDProgress.jar;";
    static STRING_UTF8 SECURITY_POLICY =
      "-Djava.security.policy=/cvs/PayToPrint/LPDProgress/LPDProgress.policy";
    #endif WINDOWS
    JavaVM*           jvm = NULL;
    JNIEnv*           env = NULL;
    jclass            lpdProgress_class;
    jmethodID         lpdProgress_mid;
    jmethodID         displayReceivingPrintJobMsgBox_mid;
    jmethodID         dismissReceivingPrintJobMsgBox_mid;
    jobject           lpdProgress_j;
    jstring           clientAddress_j;
    int JNI_Init ( void )
      JavaVMInitArgs  jvmArgs;
      JavaVMOption    jvmOptions[NUMBER_OF_JVM_OPTIONS];
      int rc;
      if (jvm == NULL)
    printf("1\n");
        memset(&jvmArgs, 0, sizeof(jvmArgs));
        jvmArgs.version = JNI_VERSION_1_2;
        jvmArgs.ignoreUnrecognized = TRUE;
    printf("2\n");
        JNI_GetDefaultJavaVMInitArgs(&jvmArgs);
        jvmOptions[0].optionString = SECURITY_POLICY;
        jvmOptions[1].optionString = CLASS_PATH;
        jvmArgs.nOptions = NUMBER_OF_JVM_OPTIONS;
        jvmArgs.options = jvmOptions;
    printf("3\n");
        rc = JNI_CreateJavaVM(&jvm, (void**) &env, &jvmArgs);
        if (rc != JNI_OK)
          jvm = NULL;
          printf("Error creating JVM = %i.\n",rc);
          return 0;
    printf("4\n");
        lpdProgress_class = (*env)->FindClass(env,"LPDProgress");
        if (lpdProgress_class == 0)
          jvm = NULL;
          printf("Can't find class LPDProgress.\n");
          return 0;
    printf("5\n");
        lpdProgress_mid =
          (*env)->GetMethodID (
                 env,
                   lpdProgress_class,
                   "<init>",
                   "(Ljava/lang/String;)"      // String clientAddress
                   "V" );                      // return value: void
        if (lpdProgress_mid == 0)
          jvm = NULL;
          printf("Can't find method LPDProgress.<init>(String).\n");
          return 0;
    printf("6\n");
        displayReceivingPrintJobMsgBox_mid =
          (*env)->GetMethodID (
                 env,
                   lpdProgress_class,
                   "DisplayReceivingPrintJobMsgBox",
                   "()"                        // void
                   "V" );                      // return value: void
        if (lpdProgress_mid == 0)
          jvm = NULL;
          printf("Can't find method LPDProgress.DisplayReceivingPrintJobMsgBox().\n");
          return 0;
    printf("7\n");
        dismissReceivingPrintJobMsgBox_mid =
          (*env)->GetMethodID (
                 env,
                   lpdProgress_class,
                   "DismissReceivingPrintJobMsgBox",
                   "()"                        // void
                   "V" );                      // return value: void
        if (lpdProgress_mid == 0)
          jvm = NULL;
          printf("Can't find method LPDProgress.DismissReceivingPrintJobMsgBox().\n");
          return 0;
      return 1;
    }Regards,
    Floyd Shackelford
    4 Peaks Technology Group, Inc.
    VOICE: 334.735.9428
    FAX: 916.404.7125
    EMAIL: [email protected]
    acta non verba

Maybe you are looking for

  • Sale group is automatically changing

    Hi Friends we hav defined plant for delhi (i.e) UDEL and sale groups D01 and D02 and also defined sales office also and assigned also we defined new customer(1000) with delivery plant UDEL and sale group D01 and material also defined with delivery pl

  • HR ABAP -- infotype 0024 enhancement

    u201CNew joiner u201Cis an action in our client system in which 8 infotypes are configured. When I execute this action in PA40 transaction, the 8th infotype that appears will be 0024.When this infotype screen appears as a part of u201DNew joiner u201

  • ORA-29855 while creating spatial index

    Hello, I am having trouble creating a spatial index. When I execute the following: create index la2003geoidx on polygons("GEOMETRY1") indextype is mdsys.spatial_index; I get the error ERROR at line 1: ORA-29855: error occurred in the execution of ODC

  • WS14000133- Parallel Approval

    Hi, In SRM 5.0 workflow WS14000133- n level approval of SC at header level, Is there a feature by which we can have parallel approval, but ensure that SC goes to next level only when all the parallel approvers have approved the cart? Currently in our

  • InDesign vs Photoshop for templates

    While I have access to InDesign, I've only used it once or twice. (I used QuarkXpress when I used to do print design but now rarely do print.) I need to  give a Realtor some postcard designs as templates that she can modify herself.  She has never us