JNI freeing local references

We're using JNI to receive data from a native callback function. The native side creates local references, but does not use the DeleteLocalRef function. This works fine with the SUN JRE.
However, the IBM JRE gets a stack overflow exception.
According to IBM, we should delete the local references, but this requires a total rewrite of our program.
Unfortunately, the JNI documentation is not very clear on this topic. In our understanding, the local references are being released automatically once they are out of scope.
Is it really necessary to delete the local references or is there a bug in the IBM JRE ?
Sample program :
==============
// JNITest.java
interface INativeNotification
public void nativeCallBack();
class JNITest implements INativeNotification
private long counter;
public native void nativeInitialize(INativeNotification callbackNotification);
static {
System.loadLibrary("JNITest");
public void nativeCallBack() {
System.out.println("JNITest CallBack " + counter++);
public void run() {
nativeInitialize(this);
counter = 0;
while(true)
try {
Thread.sleep(1000);
} catch(Exception e) {
public static void main(String[] args) {
JNITest jnitest = new JNITest();
jnitest.run();
// JNITest.cpp : Defines the entry point for the DLL application.
#include "stdafx.h"
#include "JNITest.h"
static DWORD dwThreadId;
static HANDLE hThread;
static HANDLE volatile hInitCompleteEvent;
static bool volatile bLoop = true;
static JavaVM *jvm = NULL;
static jobject nativeNotification;
BOOL APIENTRY DllMain( HANDLE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved )
return TRUE;
bool DoNativeCall(JNIEnv *env)
jclass cls = env->GetObjectClass(nativeNotification);
jmethodID callbackMethod = env->GetMethodID(cls, "nativeCallBack", "()V");
env->CallVoidMethod(nativeNotification, callbackMethod);
if ( env->ExceptionOccurred() )
env->ExceptionDescribe();
env->ExceptionClear();
printf("Native code got exception calling nativeCallBack\n");
return(false);
return(true);
DWORD WINAPI JNIThread( LPVOID lpParam )
JNIEnv *env = NULL;
jvm->AttachCurrentThread((void**)&env,NULL);
SetEvent(hInitCompleteEvent);
while (bLoop)
if (!DoNativeCall(env))
bLoop = false;
Sleep(1);
env->DeleteGlobalRef(nativeNotification);
jvm->DetachCurrentThread();
return 0;
* Class: JNITest
* Method: nativeInitialize
* Signature: ()V
JNIEXPORT void JNICALL Java_JNITest_nativeInitialize(JNIEnv *env, jobject object, jobject _nativeNotification)
DWORD dwThrdParam = 0;
env->GetJavaVM(&jvm);
nativeNotification = env->NewGlobalRef(_nativeNotification);
hInitCompleteEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
hThread = CreateThread( NULL, 0, JNIThread, &dwThrdParam, 0, &dwThreadId );
if (hThread == NULL)
env->DeleteGlobalRef(nativeNotification);
return;
WaitForSingleObject(hInitCompleteEvent, INFINITE);

Hi,
First of all, thank you for your time and interest.
Let me first recapitulate the history of this problem :
We have a C interface for controlling our HW boards. A few years ago, we wrote a java interface for one of our customers. This JNI wrapper was certified for the SUN JRE and has been used for several years now without a problem. There are several java and native callback functions in this wrapper and our development team took some design decisions (e.g. no DeleteLocalRef's, re-fetching the jclass and methodID in the callback functions, ...).
Recently, one customer asked us to use this wrapper with the IBM JRE. At first, there seemed to be no porting issues. However, after running for a very long time, we had a stack overflow.
Our customer reported this problem to IBM and finally, after sending a sample program (see my first post), IBM confirmed that there was a problem in their JVM. They provided a fix, but this fix only deleted local references which were created in a GetObjectClass call. After providing a few other fixes which did not provide a proper solution either, they suddenly changed their strategy and claimed that we have to delete all the local references which are created in a thread, otherwise we're not JNI compliant.
However, when we look in the IBM JVM diagnostics guide (Chapter 6 : Understanding the Java Native Interface, see http://www-106.ibm.com/developerworks/java/jdk/diagnosis/), they provide the following code as a sample for loosing local references, resulting in the underlying object being garbage collected.
jobject myJNIfunc1 ()
return env->NewObject ();
void myJNIfunc2 ()
jobject obj;
obj = myJNIfunc1 ();
.. -> no local reference to obj exists, and the garbage collector can collect it
Are we interpreting the IBM JVM diagnostics guide wrong or is there a problem in the IBM JVM ?
The SUN JVM deletes the local references properly.

Similar Messages

  • Need to delete local references in unknown calling context

    Hi,
    I was looking for the need to delete local references and came across this documentation,
    What does unknown caller context mean? and how does it cause local references to remain allocated in reference table although the native function returns?
    http://java.sun.com/docs/books/jni/html/refs.html
    5.2.1 Freeing Local References
    You want to write a utility function that is called from unknown contexts. The MyNewString example shown in Section 4.3 illustrates the use of Delete-LocalRef to delete promptly local references in a utility function. Otherwise there will be two local references that remains allocated after each call to the MyNewString function.

    how does it cause local references to remain allocated in reference table although the native function returns?Because it doesn't return to the JVM where it gets deallocated, it returns to the unknown caller context, i.e. some other piece of native code in your JNI layer. So the references remain until the unknown caller context returns to the JVM.

  • Local references for the last time..:-)

    I'm getting NUTS with this...please is it possible determine in Visual C++ which local references in JNI are not deleted????

    You have given me no solution understandable to a non geek. I will just go to Internet explorer and try my luck.

  • Why can't local references be cached ?

    Hi,
    I read that the local references created during the lifetime of a native method cannot be cached and used in another lifetime of the native method. I don't understand why they can't be cached. I know that the VM creates a registry of local references, which is deleted once the lifetime of a native method is over, thereby allowing the objects referred by those local references be eligible for garbage collection. But then if a local reference is cached to some global/static variable, then the object referenced cannot be GCed. Hence we should be able to use that cached reference in a later execution of the native method too. i.e., Even though the local reference of the eariler exceution was freed, since we have cached its value (which I assume is a sort of pointer to the actual object), we should be able to use the cached reference. If not, can anyone please explain why this does not work like that ?
    Thanks.

    I don't want global reference. But I just wanted to understand why local references can't be cached. Though I had read what all you said above, before posting my question, the answer somehow occurred to me while I was reading your reply. So, thanks.
    I think the cruical point here is that, the JVM is not aware of the copies of the local references. It does not know and care how many copies of local references we (JNI programmers) make at the JNI level.

  • Local references...some questions...

    Hi All,
    1)
    i have a native method, which i'm calling frequentely. In this method i return one object to Java language....Weird is, if i put -verbose:jni parameter to JVM ....then i receive a lot of allerts ... that a local references count has stepped over the maximum limit 16....
    According to this, i put a env->EnsureLocalCapacity(1) call
    before
    return env->NewObject(.....) statement
    and problem wen't away....But i don't understand this, i assumed that JVM release any local references returned to Java....?????
    2) Is this code correct???
    env->EnsureLocalCapacity(1);
    env->PushLocalFrame(1);
    jobject obj = env->NewObject(....) // no local references are created here..
    obj = env->PopLocalFrame(obj);
    return obj;
    Thanks ....

    efrizzell --
    The use of local base calendars in a Project Server environment is strictly the decision of each organization.  There are certainly valid reasons for permitting them, such as when PMs need to be able to create their own custom local base calendars.
     There are also valid reasons for denying their use, so that every project must be scheduled using a valid and tested base calendar created by the Project Server administrator.
    Several years ago, I worked with an organization that initially forbid the use of local base calendars.  Because of this, the Project Server administrator was hit with dozens of requests for custom enterprise base calendars.  He found the process
    of creating and maintaining enterprise base calendars to be so much work that he gave up trying to control it, and enabled the permission to allow PMs to create their own local base calendars.
    If your organization allows the use of local base calendars, the base calendar will be stored in the project in which it was created.  Hope this helps.
    Dale A. Howard [MVP]

  • Ejb-link is still required when using local references?

    Hi!
    In BEA's link (http://e-docs.bea.com/wls/docs81/ejb/DDreference-ejb-jar.html#1114738) there is the following comment for weblogic-ejb-jar.xml element 'jndi-name':
    "Assigning a JNDI name to a bean is not recommended. Global JNDI names generate heavy multicast traffic during clustered server startup. See Using EJB Links for the better practice."
    Since we're using local references (local-jndi-name) to access our ejbs instead of remote references, is this still recommendation still pertinent?
    Thanks
    Christianne

    It is enough if you add the ejb-ref & ejb-link in the session bean. The
    session will look up relative to java:comp/env
    The following doc shows an example of accessing an ejb from a web app using
    ejb-link.
    http://e-docs.bea.com/wls/docs81/webapp/components.html#146848
    --Sathish
    <Christianne Carvalho> wrote in message news:[email protected]..
    I'm not getting very well how the ejb-link is used. In my case I have
    entity beans that are referenced in session beans.
    In my entity beans I have the following XDoclet tag.
    * @ejb.bean
    * name="ProductDescription"
    * display-name="ProductDescription"
    * jndi-name="ejb/ProductDescription"
    * local-jndi-name="ejb/ProductDescriptionLocal"
    * view-type="local"
    * type="CMP"
    In my session bean I'm currently getting the reference for the entity bean
    using the following code:
    productDescriptionLocalHome=(ProductDescriptionLocalHome)
    lookupLocalHome(ProductDescriptionLocalHome.JNDI_NAME);
    If I add the following XDoclet tag to my session bean, in ejb-jar.xml a
    <ejb-link> is created inside <ejb-local_ref> tag.
    * @ejb.ejb-ref ejb-name="ProductDescription" view-type="local"
    Considering the info above:
    1) In the entity bean, is there any extra tag to define the ejb-link or is
    the ejb-link only defined in the session bean?
    2) Re session bean, only adding the @ejb-ref xdoclet tag is enough for
    using the ejb-link or do I also have to change my lookup? If I do, what do
    I have to search for in the lookup?
    Thanks!

  • Local references and EJBs in separate jars

    Hi
    I have trouble in getting local references when the EJBs are built in separate jar files. I am using the <ejb-link> in the <local-ejb-ref>. But I could not get reference to the EJB's local reference.
    Please let me know if there is any documentation that tells about getting local references and having the EJBs in separate jar files.
    Thanks

    Greetings,
    Hi
    I have trouble in getting local references when the
    EJBs are built in separate jar files. I am using theThere are a number of reasons why this may be happening and without more specific information it is difficult to say which you are encountering... In any case, the fact that your beans are in separate jars is not, by itself, the issue. It is worth noting, however, that Local references may only be used when both components (referencer and referencee) are co-located within the same VM instance and perhaps this little fact may shed some light on your problem??
    <ejb-link> in the <local-ejb-ref>. But I could not get<ejb-link> should point to the actual JNDI binding name, sans root nomenclature (java:comp/env/), but with full sub-context (ejb/myapp/.../MyLocalBean), of the referenced bean.
    reference to the EJB's local reference.Perhaps it goes without saying (but just to be sure :)... of course, your referenced bean must actually have Local interfaces associated with it.
    Please let me know if there is any documentation
    that tells about getting local references and having
    the EJBs in separate jar files.Both the J2EE tutorial and the EJB 2.0 spec. have the relevant information. :) However, I've already listed the requirements above: supplied local interfaces, co-located components, and correct link reference.
    I hope this helps.
    ThanksRegards,
    Tony "Vee Schade" Cook

  • EJB 3.0 Local References

    I have an EJB module that contains a session bean, MasterBean, with a local interface MasterLocal, packaged in an EAR file. I am trying to look up a reference to MasterLocal in a regular Java class in the same EAR file. I am able to look up the MasterLocal in my WAR file using the following code
    web.xml:
        <ejb-local-ref>
            <ejb-ref-name>ejb/MasterLocal</ejb-ref-name>
            <ejb-ref-type>Session</ejb-ref-type>
            <local>facade.MasterLocal</local>
            <ejb-link>MasterBean</ejb-link>
        </ejb-local-ref> Lookup:
    MasterLocal masterLocal = null;
            try {
                InitialContext ic = new InitialContext();
                masterLocal = (MasterLocal) ic.lookup("java:comp/env/ejb/MasterLocal");
            } catch (NamingException ex) {
                logger.severe("Error getting MasterLocal: " + ex.getMessage());
            }How can I use similar code to look up a reference to MasterLocal in the EAR module?
    Luke Mauldin

    [#|2007-02-01T12:09:04.263-0600|INFO|sun-appserver-pe9.0|javax.enterprise.system.container.ejb|_ThreadID=15;_ThreadName=httpWorkerThread-8080-0;|
    javax.ejb.EJBException
         at com.sun.ejb.containers.BaseContainer.processSystemException(BaseContainer.java:3730)
         at com.sun.ejb.containers.BaseContainer.completeNewTx(BaseContainer.java:3630)
         at com.sun.ejb.containers.BaseContainer.postInvokeTx(BaseContainer.java:3431)
         at com.sun.ejb.containers.BaseContainer.postInvoke(BaseContainer.java:1247)
         at com.sun.ejb.containers.EJBLocalObjectInvocationHandler.invoke(EJBLocalObjectInvocationHandler.java:192)
         at com.sun.ejb.containers.EJBLocalObjectInvocationHandlerDelegate.invoke(EJBLocalObjectInvocationHandlerDelegate.java:71)
         at $Proxy93.searchVisitorBadge(Unknown Source)
         at securitylog.login.SelectVisitors.search_action(SelectVisitors.java:752)
         at securitylog.login.SelectVisitors.init(SelectVisitors.java:712)
         at com.sun.rave.web.ui.appbase.servlet.LifecycleListener.fireInit(LifecycleListener.java:555)
         at com.sun.rave.web.ui.appbase.servlet.LifecycleListener.attributeAdded(LifecycleListener.java:405)
         at org.apache.coyote.tomcat5.CoyoteRequest.setAttribute(CoyoteRequest.java:1634)
         at org.apache.coyote.tomcat5.CoyoteRequestFacade.setAttribute(CoyoteRequestFacade.java:522)
         at javax.servlet.ServletRequestWrapper.setAttribute(ServletRequestWrapper.java:295)
         at com.sun.faces.context.RequestMap.put(ExternalContextImpl.java:1055)
         at com.sun.faces.application.ApplicationAssociate.createAndMaybeStoreManagedBeans(ApplicationAssociate.java:525)
         at com.sun.faces.el.ManagedBeanELResolver.getValue(ManagedBeanELResolver.java:82)
         at javax.el.CompositeELResolver.getValue(CompositeELResolver.java:143)
         at com.sun.faces.el.FacesCompositeELResolver.getValue(FacesCompositeELResolver.java:62)
         at com.sun.el.parser.AstIdentifier.getValue(AstIdentifier.java:65)
         at com.sun.el.ValueExpressionImpl.getValue(ValueExpressionImpl.java:192)
         at com.sun.faces.application.ValueBindingValueExpressionAdapter.getValue(ValueBindingValueExpressionAdapter.java:102)
         at com.sun.rave.web.ui.appbase.faces.ViewHandlerImpl.pageBean(ViewHandlerImpl.java:666)
         at com.sun.rave.web.ui.appbase.faces.ViewHandlerImpl.pageBean(ViewHandlerImpl.java:641)
         at com.sun.rave.web.ui.appbase.faces.ViewHandlerImpl.renderView(ViewHandlerImpl.java:249)
         at com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:133)
         at com.sun.faces.lifecycle.LifecycleImpl.phase(LifecycleImpl.java:244)
         at com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:140)
         at javax.faces.webapp.FacesServlet.service(FacesServlet.java:245)
         at org.apache.catalina.core.ApplicationFilterChain.servletService(ApplicationFilterChain.java:397)
         at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
         at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:184)
         at com.sun.webui.jsf.util.UploadFilter.doFilter(UploadFilter.java:203)
         at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:216)
         at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:184)
         at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:276)
         at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:566)
         at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:536)
         at org.apache.catalina.core.StandardContextValve.invokeInternal(StandardContextValve.java:240)
         at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:179)
         at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:566)
         at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:73)
         at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:182)
         at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:566)
         at com.sun.enterprise.web.VirtualServerPipeline.invoke(VirtualServerPipeline.java:120)
         at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:939)
         at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:137)
         at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:566)
         at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:536)
         at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:939)
         at org.apache.coyote.tomcat5.CoyoteAdapter.service(CoyoteAdapter.java:239)
         at com.sun.enterprise.web.connector.grizzly.ProcessorTask.invokeAdapter(ProcessorTask.java:667)
         at com.sun.enterprise.web.connector.grizzly.ProcessorTask.processNonBlocked(ProcessorTask.java:574)
         at com.sun.enterprise.web.connector.grizzly.ProcessorTask.process(ProcessorTask.java:844)
         at com.sun.enterprise.web.connector.grizzly.ReadTask.executeProcessorTask(ReadTask.java:287)
         at com.sun.enterprise.web.connector.grizzly.ReadTask.doTask(ReadTask.java:212)
         at com.sun.enterprise.web.connector.grizzly.TaskBase.run(TaskBase.java:252)
         at com.sun.enterprise.web.connector.grizzly.WorkerThread.run(WorkerThread.java:75)
    Caused by: java.lang.RuntimeException: javax.naming.NameNotFoundException: No object bound to name java:comp/env/ejb/MasterLocal
         at model.listeners.VisitorBadgeListener.lookupMasterBean(VisitorBadgeListener.java:67)
         at model.listeners.VisitorBadgeListener.PostLoad(VisitorBadgeListener.java:45)
         at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
         at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
         at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
         at java.lang.reflect.Method.invoke(Method.java:597)
         at oracle.toplink.essentials.internal.security.PrivilegedAccessHelper.invokeMethod(PrivilegedAccessHelper.java:307)
         at oracle.toplink.essentials.internal.ejb.cmp3.metadata.listeners.MetadataEntityListener.invokeMethod(MetadataEntityListener.java:302)
         at oracle.toplink.essentials.internal.ejb.cmp3.metadata.listeners.MetadataEntityListener.invokeMethod(MetadataEntityListener.java:324)
         at oracle.toplink.essentials.internal.ejb.cmp3.metadata.listeners.MetadataEntityListener.postClone(MetadataEntityListener.java:404)
         at oracle.toplink.essentials.descriptors.DescriptorEventManager.notifyListener(DescriptorEventManager.java:640)
         at oracle.toplink.essentials.descriptors.DescriptorEventManager.notifyEJB30Listeners(DescriptorEventManager.java:591)
         at oracle.toplink.essentials.descriptors.DescriptorEventManager.executeEvent(DescriptorEventManager.java:199)
         at oracle.toplink.essentials.internal.descriptors.ObjectBuilder.populateAttributesForClone(ObjectBuilder.java:2088)
         at oracle.toplink.essentials.internal.sessions.UnitOfWorkImpl.populateAndRegisterObject(UnitOfWorkImpl.java:2816)
         at oracle.toplink.essentials.internal.sessions.UnitOfWorkImpl.cloneAndRegisterObject(UnitOfWorkImpl.java:673)
         at oracle.toplink.essentials.internal.sessions.UnitOfWorkIdentityMapAccessor.getAndCloneCacheKeyFromParent(UnitOfWorkIdentityMapAccessor.java:152)
         at oracle.toplink.essentials.internal.sessions.UnitOfWorkIdentityMapAccessor.getFromIdentityMap(UnitOfWorkIdentityMapAccessor.java:90)
         at oracle.toplink.essentials.internal.sessions.IdentityMapAccessor.getFromIdentityMap(IdentityMapAccessor.java:295)
         at oracle.toplink.essentials.internal.sessions.UnitOfWorkImpl.registerExistingObject(UnitOfWorkImpl.java:3055)
         at oracle.toplink.essentials.internal.sessions.UnitOfWorkImpl.registerExistingObject(UnitOfWorkImpl.java:3004)
         at oracle.toplink.essentials.queryframework.ObjectBuildingQuery.registerIndividualResult(ObjectBuildingQuery.java:319)
         at oracle.toplink.essentials.internal.descriptors.ObjectBuilder.buildWorkingCopyCloneNormally(ObjectBuilder.java:441)
         at oracle.toplink.essentials.internal.descriptors.ObjectBuilder.buildObjectInUnitOfWork(ObjectBuilder.java:406)
         at oracle.toplink.essentials.internal.descriptors.ObjectBuilder.buildObject(ObjectBuilder.java:372)
         at oracle.toplink.essentials.queryframework.ReportQueryResult.processItem(ReportQueryResult.java:205)
         at oracle.toplink.essentials.queryframework.ReportQueryResult.buildResult(ReportQueryResult.java:167)
         at oracle.toplink.essentials.queryframework.ReportQueryResult.<init>(ReportQueryResult.java:83)
         at oracle.toplink.essentials.queryframework.ReportQuery.buildObject(ReportQuery.java:579)
         at oracle.toplink.essentials.queryframework.ReportQuery.buildObjects(ReportQuery.java:628)
         at oracle.toplink.essentials.queryframework.ReportQuery.executeDatabaseQuery(ReportQuery.java:776)
         at oracle.toplink.essentials.queryframework.DatabaseQuery.execute(DatabaseQuery.java:609)
         at oracle.toplink.essentials.queryframework.ObjectLevelReadQuery.execute(ObjectLevelReadQuery.java:677)
         at oracle.toplink.essentials.queryframework.ObjectLevelReadQuery.executeInUnitOfWork(ObjectLevelReadQuery.java:731)
         at oracle.toplink.essentials.internal.sessions.UnitOfWorkImpl.internalExecuteQuery(UnitOfWorkImpl.java:2218)
         at oracle.toplink.essentials.internal.sessions.AbstractSession.executeQuery(AbstractSession.java:937)
         at oracle.toplink.essentials.internal.sessions.AbstractSession.executeQuery(AbstractSession.java:909)
         at oracle.toplink.essentials.internal.ejb.cmp3.base.EJBQueryImpl.executeReadQuery(EJBQueryImpl.java:346)
         at oracle.toplink.essentials.internal.ejb.cmp3.base.EJBQueryImpl.getResultList(EJBQueryImpl.java:447)
         at facade.DataLookupBean.searchVisitorBadge(DataLookupBean.java:416)
         at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
         at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
         at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
         at java.lang.reflect.Method.invoke(Method.java:597)
         at com.sun.enterprise.security.application.EJBSecurityManager.runMethod(EJBSecurityManager.java:1050)
         at com.sun.enterprise.security.SecurityUtil.invoke(SecurityUtil.java:165)
         at com.sun.ejb.containers.BaseContainer.invokeTargetBeanMethod(BaseContainer.java:2766)
         at com.sun.ejb.containers.BaseContainer.intercept(BaseContainer.java:3847)
         at com.sun.ejb.containers.EJBLocalObjectInvocationHandler.invoke(EJBLocalObjectInvocationHandler.java:184)
         ... 53 more
    Caused by: javax.naming.NameNotFoundException: No object bound to name java:comp/env/ejb/MasterLocal
         at com.sun.enterprise.naming.NamingManagerImpl.lookup(NamingManagerImpl.java:751)
         at com.sun.enterprise.naming.java.javaURLContext.lookup(javaURLContext.java:156)
         at com.sun.enterprise.naming.SerialContext.lookup(SerialContext.java:307)
         at javax.naming.InitialContext.lookup(InitialContext.java:392)
         at model.listeners.VisitorBadgeListener.lookupMasterBean(VisitorBadgeListener.java:63)
         ... 101 more
    |#]

  • Returning local references from an EJB

    Hi,
    Is it possible to return a local object reference (of bean X) from the business method of another entity bean(Y)?
    Thanks in advance,
    Albert.

    Hey Nikola,
    Thanks for the reply.
    That is what looked so obvious to me too. My EJB is only using the local interfaces. Actually, here i am trying to use bean managed relationships. The EJB just doesn't seem to be getting deployed. Whenever i change all the references type of the specific local object to "Object" class, deployment goes thru successfully. My problem is compounded by the fact that oracle doesn't even give out any sensible error message. So i was wondering whether returning of the reference is allowed.
    Thanks,
    Albert.

  • Accessing local reference

    I have the following beans defined:
    <session>
    <ejb-name>EngineControllerEJB</ejb-name>
    <home>com.mercury.topaz.security.authorization.engine.ejbs.controller.EngineControllerHome</home>
    <remote>com.mercury.topaz.security.authorization.engine.ejbs.controller.EngineController</remote>
    <ejb-class>com.mercury.topaz.security.authorization.engine.ejbs.controller.EngineControllerBean</ejb-class>
    <session-type>Stateful</session-type>
    <transaction-type>Bean</transaction-type>
    <local>com.mercury.topaz.security.authorization.engine.ejbs.controller.LocalEngineController</local>
    <local-home>com.mercury.topaz.security.authorization.engine.ejbs.controller.LocalEngineControllerHome</local-home>
    </session>
    <session>
    <ejb-name>TopazControllerEJB</ejb-name>
    <home>com.mercury.topaz.security.authorization.engine.spi.ejbs.TopazControllerHome</home>
    <remote>com.mercury.topaz.security.authorization.engine.spi.ejbs.TopazController</remote>
    <ejb-class>com.mercury.topaz.security.authorization.engine.spi.ejbs.TopazControllerBean</ejb-class>
    <session-type>Stateful</session-type>
    <transaction-type>Bean</transaction-type>
    <ejb-local-ref>
    <description></description>
    <ejb-ref-name>EngineControllerEJB</ejb-ref-name>
    <ejb-ref-type>Session</ejb-ref-type>
    <local-home>com.mercury.topaz.security.authorization.engine.ejbs.controller.LocalEngineControllerHome</local-home>
    <local>com.mercury.topaz.security.authorization.engine.ejbs.controller.LocalEngineController</local>
    <ejb-link>EngineControllerEJB</ejb-link>
    </ejb-local-ref>
    </session>
    Obviously the first bean is bind with the name EngineControllerEJB. Now if I perform the lookup:
    ctx.lookup("EngineControllerEJB") it retrieves the RemoteHome. How do I get the Local Home?
    Thanks, Oren

    For the given EJB name "MyEJB", gain the remote home
    by 'ctx.lookup("MeEJB");' and the local by
    'ctx.lookup(java:comp/env/MyEjb");'Really the way that it is done is that by the spec everything ejb binded to JNDI needs the java:comp/env/ejb/ prefix. Maybe if you change it to this....
    <ejb-ref>
    <description></description>
    <ejb-ref-name>ejb/EngineControllerRemote</ejb-ref-name>
    <ejb-ref-type>Session</ejb-ref-type>
    <home>com.mercury.topaz.security.authorization.engine.ejbs.controller.LocalEngineControllerHome</home>
    <remote>com.mercury.topaz.security.authorization.engine.ejbs.controller.LocalEngineController</remote>
    <ejb-link>EngineControllerEJB</ejb-link>
    </ejb-ref>
    <ejb-local-ref>
    <description></description>
    <ejb-ref-name>ejb/EngineControllerLocal</ejb-ref-name>
    <ejb-ref-type>Session</ejb-ref-type>
    <local-home>com.mercury.topaz.security.authorization.engine.ejbs.controller.LocalEngineControllerHome</local-home>
    <local>com.mercury.topaz.security.authorization.engine.ejbs.controller.LocalEngineController</local>
    <ejb-link>EngineControllerEJB</ejb-link>
    </ejb-local-ref>
    now you can have:
    ctx.lookup("java:comp/env/ejb/EngineControllerLocal") and
    ctx.lookup("java:comp/env/ejb/EngineControllerRemote")

  • Applet looking up server even when local references are available

    Hi,
    I have an applet class and images packaged in a single jar.
    I am currently referring to the image from the applet with this command -
    url = getClass().getResource("/images/abc.gif");
    icon = new ImageIcon(url);The problem is that the getClass().getResource() is looking up the image on the server from where the applet was downloaded to my browser.
    that is URL is coming as
    {code{jar:http://<hostname>:port/applet.jar!/images/abc.gif{code}
    where as I expect the URL to be
    applet.jar!/images/abc.gif.My package structure of the applet and image in the jar is as follows
    -com
      - mypackage
        - TestApplet.class
    -images
    - abc.gifCould you let me know what is wrong with this code. ?
    I am using JRE 1.6.0_10 on my browser as plugin.

    >
    I think I am actually concerned abou the fact that my applet is looking up the server it was downloaded from, to fetch images, when the jar file that was downloaded already has it.>Good, I thought so. Please note that it is best to state such things in the initial post(1), so people do not have to guess.
    Your fears are unfounded. The Jar will be cached locally. Java would never return a String like the one you wanted, which is not a valid URL (in the way Java understands them) - a Java URL must be 'fully qualified', as opposed to a 'relative path'.
    'Refering back to' the location it was downloaded from is only an indication that Sun does not consider it to be our business where on the local file system that Jar might be cached. It is the same for applets and any application launched using webstart. You can use a packet sniffer such as WireShark to confirm that no extra calls are made to the server after the archives are downloaded.
    Edit 1:
    (1) D'Oh! That information was stated, or strongly implied, by the subject of your post. In that case I will amend my advice to 'mention that information on first post' to 'mention that information in the body of the first message, rather than just the title/subject' - I am not the only one who pays only scant attention to subject lines. ;-)
    Edited by: AndrewThompson64 on May 15, 2009 12:25 PM

  • [JNI Beginner] GC of Java arrays returned by the native code

    Hello all,
    I am beginning with JNI, to integrate a C library that pilots an industrial equipment, into a java UI. This library enables to exchange various proprietary PDUs (protocol data units), with the equipment, up and down (request/replies). Both requests and replies are arrays of bytes (+char*+).
    "Request" byte arrays are constructed by Java code, which passes them to the JNI code that glues with the lib. "Reply" byte arrays are returned to the Java code, which analyzes them.
    The "return reply" part is very similar to this [tutorial example|http://java.sun.com/developer/onlineTraining/Programming/JDCBook/jniexamp.html] , which returns bytes read from a file. However there's something I don't understand with regard to garbage collection of the returned byte array:
    - in this stock example, the C code creates a Java byte array fills it, and simply returns it (example code stripped to highlight only the parts relevant to my question):
        jByteArray=(*env)->NewByteArray(env, size);
        (*env)->SetByteArrayRegion(env, jByteArray, 0, size, (jbyte *)sourceBytes);
        return (jByteArray);What will happen to this Java array (jByteArray) with regard to garbage collection?
    - if it's no more referenced (the example Java code just systemouts it and forgets it), will it be eligible to GC?
    - if it is referenced by a Java variable (in my case, I plan to keep a reference to several replies as the business logic requires to analyze several of them together), do regular Java language GC rules apply, and prevent eligibility of the array to GC as long as it's referenced?
    That may sound obvious, but what mixes me up is that the same tutorial describes memory issues in subsequent chapters: spécifically, the section on "passing arrays states that:
    [in the example] the array is returned to the calling Java language method, which in turn, garbage collects the reference to the array when it is no longer usedThis seems to answer "yes" to both my questions above :o) But it goes on:
    The array can be explicitly freed with the following call:
    {code} (*env)-> ReleaseByteArrayElements(env, jByteArray, (jbyte *)sourceBytes, 0);{code}Under what circumstances would one need to explicitly free jByteArray when it's about to be returned to the Java calling method? Or does this sentence apply to completely different situations (such as, when the array is +not+ returned as is to a Java method)?
    The tutorial's next section has a much-expected +memory issues+ paragraph, from which I quote:
    By default, JNI uses local references when creating objects inside a native method. This means when the method returns, the references are eligible to be garbage collected.I assume this means, +unless the references are assigned, in the Java code, to a Java variable+, right?
    If you want an object to persist across native method calls, use a global reference instead. A global reference is created from a local reference by calling NewGlobalReference on the the local reference.I assume this enables the C code to maintain a global reference to a java object even if it's not referenced anymore from the Java variables, right?
    I also checked the [JNI specification|http://download-llnw.oracle.com/javase/6/docs/technotes/guides/jni/spec/design.html#wp1242] , but this didn't clear the doubt completely:
    *Global and Local References*
    The JNI divides object references used by the native code into two categories: local and global references. Local references are valid for the duration of a native method call, and are automatically freed after the native method returns. Global references remain valid until they are explicitly freed.
    Objects are passed to native methods as local references. All Java objects returned by JNI functions are local references. The JNI allows the programmer to create global references from local references. JNI functions that expect Java objects accept both global and local references. A native method may return a local or global reference to the VM as its resultAgain I assume the intent is that Global references are meant for objects that have to survive across native calls, regardless of whether they are referenced by Java code. But what worries me is that combining both sentences end up in +All Java objects returned by JNI functions are local references (...) and are automatically freed after the native method returns.+.
    Could you clarify how to make sure that my Java byte arrays, be they allocated in C code, behave consistently with a Java array allocated in Java code (I'm familiar already with GC of "regular" Java objects)?
    Thanks in advance, and best regards,
    J.

    jduprez wrote:
    Hello all,
    I am beginning with JNI, to integrate a C library that pilots an industrial equipment, into a java UI. This library enables to exchange various proprietary PDUs (protocol data units), with the equipment, up and down (request/replies). Both requests and replies are arrays of bytes (+char*+).
    "Request" byte arrays are constructed by Java code, which passes them to the JNI code that glues with the lib. "Reply" byte arrays are returned to the Java code, which analyzes them.
    The "return reply" part is very similar to this [tutorial example|http://java.sun.com/developer/onlineTraining/Programming/JDCBook/jniexamp.html] , which returns bytes read from a file. However there's something I don't understand with regard to garbage collection of the returned byte array:
    - in this stock example, the C code creates a Java byte array fills it, and simply returns it (example code stripped to highlight only the parts relevant to my question):
        jByteArray=(*env)->NewByteArray(env, size);
    (*env)->SetByteArrayRegion(env, jByteArray, 0, size, (jbyte *)sourceBytes);
    return (jByteArray);What will happen to this Java array (jByteArray) with regard to garbage collection?It will be collected when it is no longer referenced.
    The fact that you created it in jni doesn't change that.
    The array can be explicitly freed with the following call:
    (*env)-> ReleaseByteArrayElements(env, jByteArray, (jbyte *)sourceBytes, 0);Under what circumstances would one need to explicitly free jByteArray when it's about to be returned to the Java calling method? Or does this sentence apply to completely different situations (such as, when the array is not returned as is to a Java method)?
    Per what the tutorial says it is either poorly worded or just wrong.
    An array which has been properly initialized it a just a java object. Thus it can be freed like any other object.
    Per your original question that does not concern you because you return it.
    In terms of why you need to explicitly free local references.
    [http://download-llnw.oracle.com/javase/6/docs/technotes/guides/jni/spec/design.html#wp16785]
    The tutorial's next section has a much-expected memory issues paragraph, from which I quote:
    By default, JNI uses local references when creating objects inside a native method. This means when the method returns, the references are eligible to be garbage collected.I assume this means, unless the references are assigned, in the Java code, to a Java variable, right?As stated it is not precise.
    The created objects are tracked by the VM. When they are eligible to be collected they are.
    If you create a local reference and do NOTHING that creates an active reference elsewhere then when the executing thread returns to the VM then the local references are eligible to be collected.
    >
    If you want an object to persist across native method calls, use a global reference instead. A global reference is created from a local reference by calling NewGlobalReference on the the local reference.That is not precise. The scope is the executing thread. You can pass a local reference to another method without problem.
    I assume this enables the C code to maintain a global reference to a java object even if it's not referenced anymore from the Java variables, right?
    It enables access to it to be insured across multiple threads in terms of execution scope. Normally you should not use them.

  • Local ref garbage collection within "nested" JNI calls

    I am using a JVM started in C++ to make calls to java classes. The C++ code makes JNI call into the JVM which instantiates a java class. The java class, in the course of execution, makes other JNI calls. All this happens on one thread of execution.
    What I am seeing is that local references from the native methods being called by the java class are not being released until the initial C++ native call exits. The JNI spec (text included below) seems to indicate there is registry of "nonmovable local references to Java objects" which "keeps the objects from being garbage collected". Is there only one such registry which does not get deleted until the initial C++ native call exits? If so, this would explain what I am seeing. How do I get around it?
    Thanks,
    Iztok
    From the JNI spec:
    "To implement local references, the Java VM creates a registry for each
    transition of control from Java to a native method. A registry maps nonmovable local references to Java objects, and keeps the objects from being garbage collected. All Java objects passed to the native method (including those that are returned as the results of JNI function calls) are automatically added to the registry. The registry is deleted after the native method returns, allowing all of its entries to be garbage collected."

    When I say "initial" I mean the initial C++ JNI call into a JVM running in a C++ process as shown in the pseudo code below. initNativeFunc() makes a call to Foo.doSomething() function which calls nativeFunc2 (another native function). Only a local reference to Retval was created in nativeFunct2, so when nativeFunct2 returns and the Retval is no longer used in Foo it should be a candidate for garbage collection. But this is not what happens. The Retval from nativeFunc2 is not being cleaned up until Foo.doSomething() returns. If I make the loop in Foo.doSomething() long enough, NewDoubleArray() returns a NULL when it runs out of memory.
    void initNativeFunc() {
    jclass clazz = env->FindClass("Foo");
    jmethodID mid = env->GetMethodID(clazz, "doSomething", "()V");
    env->CallVoidMethod(clazz, mid, ...);
    JNIEXPORT jobject JNICALL nativeFunc2() {
    jclass clazz = env->FindClass("Retval");
    jmethodID mid = env->GetMethodID("Retval, "<init>", "()V");
    jobject retval= env->NewObject(clazz, mid);
    jdoubleArray da = env->NewDoubleArray(100000);
    jfieldID fid = ...
    env->SetObjectField(retval, fid, da);
    return retval;
    public class Foo {
    public native void nativeFunc2();
    public void doSomething() {
    for (int i = 0; i < 100; i++) {
    Retval retval = nativeFunc2();
    }

  • How to obtain JNIEnv pointer and jobject reference in arbitrary contexts?

    Hi,
    I need your hand. How to obtain JNIEnv pointer and jobject reference in arbitrary contexts? (See below source codes for details)
    I made some tries according to JNI spec, but still failed to get it work. Could you please provide your solutions? Better show me some source codes.
    Thank you very much !!!
    #include <jni.h>
    #include "MessageThread.h"
    #include "MyServer.h"
    // this is callback function called by the native C++ library
    void processEvent(int progress)
       in this function, i want to get "env", "obj" ( HOW? ),
       then i can do below to invoke Java function "updateUI":
       cls = env->GetObjectClass(obj);
       mid = env->GetMethodID(cls, "updateUI", "(I)V");
       env->CallVoidMethod(obj, mid, progress); 
    JNIEXPORT void JNICALL
    Java_MessageThread_handleMessageQ(JNIEnv *env, jobject obj)
      MyServer* server = MTMServer::Instance();
      if (server != NULL)
        // must register a callback function before "QueryProgress"
        server->RegisterCallback(processEvent);
        // query message within a loop, and callback "processEvent" frequently
        server->QueryProgress();
      return; 
    }

    jschell, thanks for your suggestions.
    And caching the second is definitely wrong. Arguments are passed as local references. The reference lifetime is only guaranteed for the lifetime of the method call.In my case, it just works, because my "callback" is only called before the "handleMessageQ" returns, which means it's within the lifetime of "jobject", etc.
    Use GetEnv to get the environment.Could you please provide some sample codes?
    Create a static java method which returns the object reference. In your callback call that method to get the reference that you want to work with. I didn't really understand. Could you please show me some sample codes?
    Thanks a lot!

  • Instatiating a C++ class through JNI

    I am trying to instantiate a C++ class from within my Java program using JNI. I want to instatiate the class once, and then call a function within the class a number of times, in which the results obtained from the previous time the function was run would be used the next time the function was run. By instantiating tha class, my hope is that the variable values would stay within the class, and therefore would not need to be passed.
    It is not an option to pass the variable between the C++ and Java code, since I am working with matrices and JNI does not support passing matrices.
    Thanks!

    Here are some things to try:
    1) Just keep a static reference to the class in your DLL. It shouldn't be considered a local reference as Java classes would be, but if it is, maybe you can keep it as a global reference, which is used to keep a reference to a Java class between JNI calls.
    http://java.sun.com/docs/books/tutorial/native1.1/implementing/refs.html
    2) You could also pass the entire class back and forth as a byte array and then cast it when necessary, but that's potentially a lot of data to pass around.

Maybe you are looking for

  • Multiple users with different Ipods on same computer

    My household has one general computer that is used by myself and my two teenage daughters. We don't use separate logins because it is used mostly to just go online, check our email, and use Itunes along with updating our Ipods. This works fine for us

  • Mapping problem on different levels. (IDOC) to SQL

    I am having a mapping issue with a multi segment IDOC. It seems that it should be pretty straight forward but I am struggling. I have looked at some pretty good documentation but it still doesn't seem to help. The IDOC segments deal with text lines i

  • Data from the outputstream to a file in the server.

    Hello everyone, I have put the data in the outputstream. I need to place the data in a pdf and put it in a location in the unix box. Any suggestion? Below is the code i have written so far. public ByteArrayInputStream inputStream; public ByteArrayOut

  • Cmd-returning not working

    Hello, One of the few short cuts I regularly use in Safari is when viewing a page and I decide to search for something, I fill in the search bar and then hit cmd-return to open the results in a new tab. Since Safari 5.1 came out however this no longe

  • How to delete entries in table HRP1000

    Hi, I have lots of expired entries in HRP1000 in SRM system.  (Around 26 million) Do you know how/which report help me to delete the expired data? I guess the below options: 1. use report to delete them in SRM directly? or 2. use report to delete the