Attach native thread to JVM

Hi,
I use JNI to extend my Java class with some Windows specific functions.
In the native code I have to check the value of a variable from Java and for this I created a new native thread.
The documentation says that "the JNI interface pointer is valid only in current thread", so one must attach the new thread to the JVM in order to get a new interface pointer. But for attaching a thread to the JVM you need the ORIGINAL JNI INTERFACE POINTER. On the other hand, the documentation says that you "must not pass the interface pointer from one thread to another". So, I don't understand how to do it?
Here is a sample from my code:
JNIEXPORT jint JNICALL
Java_com_cts__TestJNI_startTask(JNIEnv *env, jobject obj, jstring name)
//creating a global reference
jobject globalObj = env->NewGlobalRef(obj);
//create the new thread
hThread = CreateThread(NULL,
0,
(LPTHREAD_START_ROUTINE) WaitForStop,
(LPVOID) env,//=>>> it mustn't be passed!
0,
&tid);
//the thread method, which check the value of "status" field from Java
void WINAPI WaitForStop(LPARAM lparam)
JavaVM *jvm;
JNIEnv *jenv;
pInitData->lparam->env->GetJavaVM(&jvm);
jint res = jvm->AttachCurrentThread((void**) &jenv, NULL);
if (res < 0) {
return;
jclass jclasjni = jenv->GetObjectClass(globalObj);
jfieldID jfid = jenv->GetFieldID( jclasjni, "status", "I");
jint jstatus = 0;
do
     Sleep(1000);
     jstatus = jenv->GetIntField(globalObj, jfid);
} while (jstatus == 0);
jvm->DetachCurrentThread();
Is it correct the way I attached the thread?
Because I don't quite understand this JNI interface pointer issue.
Thanks in advance

Ahhh - ha - got it working.
Here is how I did it:
dynamically link to the GetCreatedJavaVMs() function in the jni library (hJVM is the result of an earlier call to LoadLibrary):
     // type definitions for function addresses returned by loading jvm.dll
     typedef jint (JNICALL GetCreatedJavaVMs_t)( JavaVM**, jsize, jsize* );
     // function definitions for functions used in jvm.dll
     GetCreatedJavaVMs_t *GetCreatedJavaVMs;
     GetCreatedJavaVMs = (GetCreatedJavaVMs_t*)GetProcAddress( hJVM, "JNI_GetCreatedJavaVMs" );
     return GetCreatedJavaVMs( jvm, bufLen, nVMs);Get an appropriate instance on the JVM by called GetCreatedJavaVMs and pulling the first one. Once we have that, call AttachCurrentThread to get a JNIEnv pointer that we can use for doing work:
     JavaVM *jvm;
     JNIEnv *jenv;
     jint nSize = 1;
     jint nVms;
     jint nStatus = JAVAVM.GetCreatedJavaVMs( &jvm, nSize, &nVms );
     jint res = jvm->AttachCurrentThread((void**) &jenv, NULL);
    jclassStartup =
       jenv->FindClass(sStartupClass); // do some workWhen all done with the invocation, detach the jenv pointer from the current thread:
     jvm->DetachCurrentThread();Works like a charm.
- K

Similar Messages

  • Attach native thread to jvm takes much time

    Hello everyone,
    I attach a native thread to the jvm. It works but it takes about 10 seconds. I do not understand why and I would like to reduce this time to 1 or 2 seconds.
    I use a native thread to get keyboard events (a hook) to capture a screen area (with Robot class).
    Samples program :
    Abstract class used by the thread :
    class CATSrvThreadHandler
    public:
    CATSrvThreadHandler();
    enum
    enableCode = 1,
    updateCode = 2,
    disableCode = 3
    virtual ~CATSrvThreadHandler();
    virtual void doEnable() = 0;
    virtual void doUpdate() = 0;
    Herited class : class CATSrvScreenIndicator:public CATSrvThreadHandler
    CATSrvScreenIndicator CATSrvScreenIndicator::extract(JNIEnv env, jobject object)
    // Get field ID
    jfieldID l_handlerId = env->GetFieldID(env->GetObjectClass(object), "_handler", "I");
    // Get field
    CATSrvScreenIndicator l_handler = (CATSrvScreenIndicator )env->GetIntField(object, l_handlerId);
    return l_handler;
    // This method is called by Java code to activate the thread
    void CATSrvScreenIndicator::enable(JNIEnv *env)
    g_DesktopIndicatorThread.MakeSureThreadIsUp(env);
    // Takes too much time !!!! (about 5 seconds)
    while(!PostThreadMessage(g_DesktopIndicatorThread, WM_DESKTOPINDICATOR, enableCode, (LPARAM)this))
    Sleep(0);
    The thread class :
    CATSrvScreenCaptureThread::CATSrvScreenCaptureThread()
    m_env = NULL;
    m_thread = 0;
    m_vm = NULL;
    m_handlerCount = 0;
    void CATSrvScreenCaptureThread::MakeSureThreadIsUp(JNIEnv *env)
    if(!m_thread)
    // --> Get VM
    env->GetJavaVM(&m_vm);
    // --> Start "native" thread
    CreateThread(NULL, 0, ThreadProc, this, 0, &m_thread);
    DWORD WINAPI CATSrvScreenCaptureThread::ThreadProc(LPVOID lpParameter)
    CATSrvScreenCaptureThread l_this=(CATSrvScreenCaptureThread)lpParameter;
    // --> Attach the thread to the VM, takes too much time !!!! (about 5 seconds)
    l_this->m_vm->AttachCurrentThread((JNIEnv**)&l_this->m_env, NULL);
    MSG msg;
    while(GetMessage(&msg, NULL, 0, 0))
    Thanks for any information !

    It's ellapse time with no other application running
    between this method call and tray icon appearing int
    the taskbar.
    Now I am not sure I understand the question.
    To time how long a method call takes you must time the method - not just the code that the method runs in. And you need to use a timer and not just guess about it.

  • Stack size for native thread attaching to JVM

    All:
    I have a native thread (see below, FailoverCallbackThread) that attaches to the JVM and does a Java call through JNI. The stack size for the native thread is 256KB.
    at psiUserStackBangNow+112()@0x20000000007a96d0
    at psiGuessUserStackBounds+320()@0x20000000007a8940
    at psiGuessStackBounds+48()@0x20000000007a8f60
    at psiGetPlatformStackInfo+336()@0x20000000007a9110
    at psiGetStackInfo+160()@0x20000000007a8b40
    at psSetupStackInfo+48()@0x20000000007a5e00
    at vmtiAttachToVMThread+208()@0x20000000007c88b0
    at tsAttachCurrentThread+896()@0x20000000007ca500
    at attachThread+304()@0x2000000000751940
    at genericACFConnectionCallback+400(JdbcOdbc.c:4624)@0x104b1bc10
    at FailoverCallbackThread+512(vocctx.cpp:688)@0x104b8ddc0
    at start_thread+352()@0x20000000001457f0
    at __clone2+208()@0x200000000030b9f0
    This causes stack overflow in Oracle JRockit JVM. (It does not cause overflow with Oracle Sun JDK.) Is there a recommended stack size for this use case for JRockit? Is there a way to compute it roughly?
    Platform Itanium 64 (linux)]
    java version "1.5.0_06"
    Java(TM) 2 Runtime Environment, Standard Edition (build 1.5.0_06-b05)
    BEA JRockit(R) (build R26.4.0-63-63688-1.5.0_06-20060626-2259-linux-ia64, )
    mp

    How do I found default heap size, stack size for the
    thread, number of threads per jvm/process supported ?The threads is OS, OS install and jvm version specific. That information is also not useful. If you create the maximum number of threads that your application can create you will run out of memory. Threads require memory. And it is unlikely to run very well either.
    The default heap size and stack size are documented in the javadocs that explain the tools that come with the sun jdk.
    and how the above things will vary for each OS and how
    do I found ? Threads vary by OS, and OS install. The others do not (at least not with the sun jvm.)
    If I get "OutOfMemoryError: Unable to create new native thread" Most of the time it indicates a design problem in your code. At the very lease, you should consider using a thread pool instead.
    I found in one forum, in linux you can create maximum
    of 894 threads. Is it true ?Seems high since in linux each thread is a new process, but it could be.

  • Native thread support in JVM.

    Hello,
    I would like to know if which version of the JRE that supports native threads under Windows 2000. We have Dell 6450 and 8450 boxes which 6 and 8 CPUs respectivly. Are there any performance gains using green threads or native threads in your java apps running on this type of hardware? We are having problems scaling our app across multiple processors, anyone have any suggestions? I have read the articles on performance tuning for GC.
    Thanks for you help,
    Richie

    There are a lot of GC calls. About every 2-3 secs:
    [GC 2510K->2018K(2844K), 0.0083897 secs]
    [GC 2530K->2066K(2844K), 0.0079910 secs]
    [GC 2578K->2081K(2844K), 0.0057756 secs]
    [GC 2593K->2086K(2844K), 0.0049079 secs]
    [GC 2598K->2109K(2844K), 0.0045131 secs]
    [GC 2621K->2111K(2844K), 0.0040606 secs]
    [GC 2623K->2116K(2844K), 0.0032259 secs]
    [Full GC 2429K->1891K(3732K), 0.1262438 secs]
    [GC 2403K->1899K(3732K), 0.0031484 secs]
    [GC 2411K->1896K(3732K), 0.0027157 secs]
    [Full GC 2290K->1907K(3756K), 0.1177704 secs]
    [GC 2419K->1910K(3756K), 0.0027415 secs]
    [GC 2422K->1913K(3756K), 0.0027142 secs]
    [GC 2425K->1920K(3756K), 0.0029628 secs]
    [Full GC 2154K->1776K(3756K), 0.1736008 secs]
    [GC 2288K->1779K(3756K), 0.0025489 secs]
    [GC 2291K->1780K(3756K), 0.0027452 secs]
    [GC 2292K->1791K(3756K), 0.0028704 secs]
    [Full GC 2025K->1792K(3756K), 0.1165200 secs]
    [GC 2304K->1800K(3756K), 0.0028561 secs]
    [GC 2312K->1815K(3756K), 0.0033773 secs]
    [Full GC 1877K->1808K(3756K), 0.1168870 secs]
    [GC 2320K->1812K(3756K), 0.0026055 secs]
    [GC 2324K->1813K(3756K), 0.0027891 secs]
    [GC 2325K->1813K(3756K), 0.0030839 secs]
    [Full GC 2082K->1824K(3756K), 0.1178141 secs]
    [GC 2336K->1832K(3756K), 0.0028492 secs]
    [GC 2343K->1831K(3756K), 0.0031900 secs]
    [GC 2342K->1839K(3756K), 0.0028541 secs]
    [Full GC 2130K->1776K(3756K), 0.1235131 secs]
    [GC 2288K->1781K(3756K), 0.0027983 secs]
    [GC 2293K->1793K(3756K), 0.0028564 secs]
    [Full GC 2090K->1792K(3756K), 0.1179482 secs]
    [GC 2304K->1798K(3756K), 0.0027652 secs]
    [GC 2310K->1796K(3756K), 0.0031365 secs]
    [GC 2308K->1806K(3756K), 0.0028844 secs]
    [Full GC 2041K->1808K(3756K), 0.1173085 secs]
    [GC 2320K->1815K(3756K), 0.0027971 secs]
    After the changes you recommended, all the calls where full GCs but about every minute or so:
    [Full GC 29465K->1633K(229376K), 0.1860478 secs]
    [Full GC 7693K->1861K(229376K), 0.1346889 secs]
    [Full GC 6788K->2378K(229376K), 0.1453195 secs]
    [Full GC 4473K->2172K(229376K), 0.1886921 secs]
    [Full GC 3425K->2200K(229376K), 0.1256969 secs]
    [Full GC 5118K->2228K(229376K), 0.1301106 secs]
    [Full GC 4778K->2257K(229376K), 0.1294866 secs]
    [Full GC 4864K->2172K(229376K), 0.1394726 secs]
    [Full GC 4266K->2200K(229376K), 0.1312010 secs]
    [Full GC 4242K->2228K(229376K), 0.1283027 secs]
    [Full GC 4391K->2249K(229376K), 0.1281122 secs]
    [Full GC 4730K->2163K(229376K), 0.1425039 secs]
    [Full GC 3477K->2191K(229376K), 0.1254208 secs]
    [Full GC 5201K->2219K(229376K), 0.1340530 secs]
    [Full GC 4763K->2246K(229376K), 0.1299836 secs]
    [Full GC 4915K->2136K(229376K), 0.1432493 secs]
    [Full GC 4116K->2164K(229376K), 0.1287218 secs]
    [Full GC 4325K->2194K(229376K), 0.1300299 secs]
    [Full GC 4324K->2221K(229376K), 0.1302815 secs]
    [Full GC 4802K->2137K(229376K), 0.1434224 secs]
    [Full GC 3461K->2165K(229376K), 0.1263876 secs]
    [Full GC 5078K->2193K(229376K), 0.1326188 secs]
    [Full GC 4795K->2221K(229376K), 0.1319525 secs]
    [Full GC 4744K->2137K(229376K), 0.1306481 secs]
    None of the calls are very long. So far, so good.

  • JNI native threads causing JRE to fail to shut down?

    Hello,
    I am using JNI to communicate with a COM object. I am reasonably certain at this point that my JNI code is handling this properly and the third party COM library is releasing the object in question. We allocate and release hundreds of these objects and we aren't observing any memory leaks. Likewise in our handling of events we receive from the COM object. We attach the thread to Java, deliver the event, and then detach the thread from Java, with very careful error handling around the event delivery to ensure that whatever else happens the detach gets called. This code is very robust and stable in operation and has been working at load in the field for over a year now without any customer problems in the JNI area.
    However, since day one, when I go to shut down the application, the JNI isn't winding down properly. As it happens, since the JRE is running a Tomcat, driven by a wrapper service, the wrapper eventually gives up waiting and shoots the JRE in the head, but the user experience of stopping the wrapper service is ugly and we'd like to clean that up. The JNI code, of course, runs as shared code in the Tomcat.
    It is possible that the third-party library, which does network communications, is keeping a thread pool for use with any of the COM objects even after all COM objects are released. This would be experienced as a one-time hit when the first object is allocated and not as a continual leak, so we'd be unlikely to notice it otherwise.
    Will native non-Java threads running in the JRE but not allocated by the JRE itself cause the JRE to hang on until they've spontaneously decided to clean themselves up? Threads that have never been attached to the JVM? How about threads that were briefly attached to the JVM but then detached? Any worse?
    Ralph

    Hi Ralph,
    I will need some more information regarding this issue.
    1. What platform are you on?
    2. Which JRockit version are you running?
    3. If you remove the wrapper service, does JRockit freeze without exiting properly?
    As a general recommendation I would try to upgrade to the latest JRockit version. It can be downloaded from the OTN http://www.oracle.com/technology/software/products/jrockit/index.html
    You may also try some verbose printouts to debug the issue a little further. Try
    -Xverbose:thread=debug,jni=debug
    This might give us some more insight in what is going on.
    Also when JRockit freezes you can output a Java stack trace using our 'jrcmd' tool which you can find in the same folder as the java executable. Run this tool without any parameters and it will output identifiers (numbers) for every running JRockit instance on your machine. Run the same tool again, this time append the identifier you believe is the one running the Tomcat and add the command 'print_threads', ie
    jrcmd <some_id_here> print_threads
    This may show what JRockit is waiting for.
    Cheers,
    /Henrik

  • Java.lang.OutOfMemoryError: unable to create new native thread on Win2000

    Dear all,
    I install a java server (SAP J2EE) on the windows machine and run into the following problem: the total number of threads cannot exceed 1200 (as i see this in the task manager)
    After it does reach this number no other tasks can be started. Thereafter i get java.lang.OutOfMemoryError: unable to create new native thread error .
    However the other machine where the same distribution of Win2000 Server is installed can easily coupe with more than 2500 theads. The same is true when the safe mode on the first machine is on: I can generate more than 1200 threads. So it seems the problem has something to do with Windows itself.
    I am really puzzled here, would really appreciate any help.
    Thanks in advance,
    Dimitry
    Surkov Dimitry
    [email protected]
    +49.1632.492618

    well, i do not supply any options when i start jvm, but it is not the course:
    it also happens with c programs. however in the safe mode it works. both for c and for java program.
    so it must be either some software (however memory is ok) or ...? i am lost. In some Unix system you can set the total number of threads allowed as an option in the kernal. But i guess this is not the case with windows.
    Thanks a lot for your reply,
    dimitry

  • Java.lang.OutOfMemoryError: unable to create new native thread

    Hi All,
    I have installed weblogic server 8 sp4 in production environment . I am facing problems with JVM issues .
    JVM is crashing very frequently with the following errro :
    ####<Jun 18, 2009 10:58:22 AM IST> <Info> <Common> <IMM90K-21> <SalesCom> <ExecuteThread: '24' for queue: 'weblogic.kernel.Default'> <<anonymous>> <> <BEA-000628> <Created "1" resources for pool "PIConnectionPool", out of which "1" are available and "0" are unavailable.>
    ####<Jun 18, 2009 11:00:09 AM IST> <Info> <EJB> <IMM90K-21> <SalesCom> <ExecuteThread: '23' for queue: 'weblogic.kernel.Default'> <<anonymous>> <> <BEA-010051> <EJB Exception occurred during invocation from home: payoutCheck.ejb.payoutCheck_s6v3so_HomeImpl@121a735 threw exception: java.lang.OutOfMemoryError: unable to create new native thread
    java.lang.OutOfMemoryError: unable to create new native thread
         at java.lang.Thread.start(Native Method)
         at payoutCheck.classes.MyThread2.MyThreadv(PayoutCheckBOImpl.java:249)
         at payoutCheck.classes.PayoutCheckBOImpl.genSP(PayoutCheckBOImpl.java:184)
         at payoutCheck.ejb.PayoutCheckSLSB.genSP(PayoutCheckSLSB.java:191)
         at payoutCheck.ejb.payoutCheck_s6v3so_EOImpl.genSP(payoutCheck_s6v3so_EOImpl.java:315)
         at payoutCheck.ejb.payoutCheck_s6v3so_EOImpl_CBV.genSP(Unknown Source)
         at payoutCheck.deligate.PayoutCheckBD.genSP(PayoutCheckBD.java:226)
         at ui.action.SearchAction.callFilter(SearchAction.java:378)
         at sun.reflect.GeneratedMethodAccessor201.invoke(Unknown Source)
         at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
         at java.lang.reflect.Method.invoke(Method.java:324)
         at org.apache.struts.actions.DispatchAction.dispatchMethod(DispatchAction.java:280)
         at org.apache.struts.actions.DispatchAction.execute(DispatchAction.java:220)
         at org.apache.struts.action.RequestProcessor.processActionPerform(RequestProcessor.java:446)
         at org.apache.struts.action.RequestProcessor.process(RequestProcessor.java:266)
         at org.apache.struts.action.ActionServlet.process(ActionServlet.java:1292)
         at org.apache.struts.action.ActionServlet.doPost(ActionServlet.java:510)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:760)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
         at weblogic.servlet.internal.ServletStubImpl$ServletInvocationAction.run(ServletStubImpl.java:1006)
         at weblogic.servlet.internal.ServletStubImpl.invokeServlet(ServletStubImpl.java:419)
         at weblogic.servlet.internal.ServletStubImpl.invokeServlet(ServletStubImpl.java:315)
         at weblogic.servlet.internal.WebAppServletContext$ServletInvocationAction.run(WebAppServletContext.java:6718)
         at weblogic.security.acl.internal.AuthenticatedSubject.doAs(AuthenticatedSubject.java:321)
         at weblogic.security.service.SecurityManager.runAs(SecurityManager.java:121)
         at weblogic.servlet.internal.WebAppServletContext.invokeServlet(WebAppServletContext.java:3764)
         at weblogic.servlet.internal.ServletRequestImpl.execute(ServletRequestImpl.java:2644)
         at weblogic.kernel.ExecuteThread.execute(ExecuteThread.java:219)
         at weblogic.kernel.ExecuteThread.run(ExecuteThread.java:178)
    >
    The above mentioned is coming several times , anybody please help out to get rid of this issue.
    Thanks in advance ,
    Krikar.

    This only tells you that the JVM is running out of heap space. It doesn't tell you what is causing the problem. You likely have a memory leak, but you could also try increasing the max heap size of the JVM (-Xmx command line option). It would help to watch the % mem in use statistic, but only immediately after a garbage collection cycle (you can force a GC from the admin console). If the % mem in use after the GC is increasing over time, then that likely confirms you have a memory leak. Note that looking at that statistic during the server startup probably is irrelevant. You'd need to wait until the server finishes starting up, and likely processed a few messages (to load static data).
    If you get to the point of confirming that you have a memory leak, that requires doing detailed analysis with a Java profiler (JProfiler, JProbe, YourKit, etc.) to track down the source of the leak.

  • Help! Unable to create new native thread

    Ok I see this problem all over the web but most of the posts are many years old and still leave me a little confused.  Often at random times on the same tags like CFLDAP I get the error "Unable to create new native thread".  Then a few minutes later the same tag on the same page works just fine.
    I have 4GB of memory in this box with 1400 MB set as the maximum Java heap size by the way.
    Here are my arguments from the jvm.config file.
    # Arguments to VM
    java.args=-server  -Xmx1400m -Dsun.io.useCanonCaches=false -XX:MaxPermSize=192m -XX:+UseParallelGC -Dcoldfusion.rootDir={application.home}/../ -Dcoldfusion.libPath={application.home}/../lib -Dcoldfusion.classPath={application.home}/../lib/updates,{application.home}/../lib,{appli cation.home}/../gateway/lib/,{application.home}/../wwwroot/WEB-INF/flex/jars,{application. home}/../wwwroot/WEB-INF/cfform/jars,"C:\\Program Files\\Apache Software Foundation\\Apache2.2\\htdocs\\InterWeb-Prod\\includes\\classes"
    Here is a typical error that comes through.
    struct     
    Browser     Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/533.4 (KHTML, like Gecko) Chrome/5.0.375.70 Safari/533.4    
    DateTime    {ts '2010-06-23 10:07:44'}  
    Diagnostics unable to create new native thread null <br>The error occurred on line 122.
    GeneratedContent      
    HTTPReferer http://--------------------/index.cfm?FuseAction=HR.main    
    Mailto      interweb@--------------------- 
    Message     unable to create new native thread      
    QueryString fuseaction=ManagedLists.MailSubscriptions     
    RemoteAddress     192.168.250.124
    RootCause   struct    
    Message     unable to create new native thread      
    StackTrace          java.lang.OutOfMemoryError: unable to create new native thread at java.lang.Thread.start0(Native Method) at java.lang.Thread.start(Thread.java:597) at com.sun.jndi.ldap.Connection.<init>(Connection.java:208) at com.sun.jndi.ldap.LdapClient.<init>(LdapClient.java:112) at com.sun.jndi.ldap.LdapCtx.connect(LdapCtx.java:2504) at com.sun.jndi.ldap.LdapCtx.<init>(LdapCtx.java:263) at com.sun.jndi.ldap.LdapCtxFactory.getInitialContext(LdapCtxFactory.java:76) at javax.naming.spi.NamingManager.getInitialContext(NamingManager.java:667) at javax.naming.InitialContext.getDefaultInitCtx(InitialContext.java:288) at javax.naming.InitialContext.init(InitialContext.java:223) at javax.naming.InitialContext.<init>(InitialContext.java:197) at javax.naming.directory.InitialDirContext.<init>(InitialDirContext.java:82) at coldfusion.tagext.net.LdapTag.do_ActionQuery(LdapTag.java:839) at coldfusion.tagext.net.LdapTag.doStartTag(LdapTag.java:616) at coldfusion.runtime.CfJspPage._emptyTcfTag(CfJspPage.java:2661) at cfadfunctions2ecfm1473603830$funcADLOOKUPUSERNAME.runFunction(C:\Program Files\Apache Software Foundation\Apache2.2\htdocs\InterWeb-Prod\includes\adfunctions.cfm:122) at coldfusion.runtime.UDFMethod.invoke(UDFMethod.java:418) at coldfusion.runtime.UDFMethod$ArgumentCollectionFilter.invoke(UDFMethod.java:324) at coldfusion.filter.FunctionAccessFilter.invoke(FunctionAccessFilter.java:59) at coldfusion.runtime.UDFMethod.runFilterChain(UDFMethod.java:277) at coldfusion.runtime.UDFMethod.invoke(UDFMethod.java:192) at coldfusion.runtime.CfJspPage._invokeUDF(CfJspPage.java:2471) at cfadfunctions2ecfm1473603830$funcADLOOKUPMULTIPLEUSERNAMES.runFunction(C:\Program Files\Apache Software Foundation\Apache2.2\htdocs\InterWeb-Prod\includes\adfunctions.cfm:54) at coldfusion.runtime.UDFMethod.invoke(UDFMethod.java:418) at coldfusion.runtime.UDFMethod$ArgumentCollectionFilter.invoke(UDFMethod.java:324) at coldfusion.filter.FunctionAccessFilter.invoke(FunctionAccessFilter.java:59) at coldfusion.runtime.UDFMethod.runFilterChain(UDFMethod.java:277) at coldfusion.runtime.UDFMethod.invoke(UDFMethod.java:192) at coldfusion.runtime.CfJspPage._invokeUDF(CfJspPage.java:2471) at cfdsp_managedlists2ecfm55598920.runPage(C:\Program Files\Apache Software Foundation\Apache2.2\htdocs\InterWeb-Prod\hr\managedlists\dsp_managedlists.cfm:232) at coldfusion.runtime.CfJspPage.invoke(CfJspPage.java:196) at coldfusion.tagext.lang.IncludeTag.doStartTag(IncludeTag.java:370) at coldfusion.runtime.CfJspPage._emptyTcfTag(CfJspPage.java:2661) at cffbx_switch2ecfm2121232114.runPage(C:\Program Files\Apache Software Foundation\Apache2.2\htdocs\InterWeb-Prod\hr\managedlists\fbx_switch.cfm:23) at coldfusion.runtime.CfJspPage.invoke(CfJspPage.java:196) at coldfusion.tagext.lang.IncludeTag.doStartTag(IncludeTag.java:370) at coldfusion.runtime.CfJspPage._emptyTcfTag(CfJspPage.java:2661) at cffbx_fusebox30_cf502ecfm1180471387._factor4(C:\Program Files\Apache Software Foundation\Apache2.2\htdocs\InterWeb-Prod\fbx_fusebox30_cf50.cfm:241) at cffbx_fusebox30_cf502ecfm1180471387._factor5(C:\Program Files\Apache Software Foundation\Apache2.2\htdocs\InterWeb-Prod\fbx_fusebox30_cf50.cfm:1) at cffbx_fusebox30_cf502ecfm1180471387.runPage(C:\Program Files\Apache Software Foundation\Apache2.2\htdocs\InterWeb-Prod\fbx_fusebox30_cf50.cfm:1) at coldfusion.runtime.CfJspPage.invoke(CfJspPage.java:196) at coldfusion.tagext.lang.IncludeTag.doStartTag(IncludeTag.java:370) at coldfusion.runtime.CfJspPage._emptyTcfTag(CfJspPage.java:2661) at cfindex2ecfm749274359.runPage(C:\Program Files\Apache Software Foundation\Apache2.2\htdocs\InterWeb-Prod\index.cfm:23) at coldfusion.runtime.CfJspPage.invoke(CfJspPage.java:196) at coldfusion.tagext.lang.IncludeTag.doStartTag(IncludeTag.java:370) at coldfusion.filter.CfincludeFilter.invoke(CfincludeFilter.java:65) at coldfusion.filter.ApplicationFilter.invoke(ApplicationFilter.java:273) at coldfusion.filter.RequestMonitorFilter.invoke(RequestMonitorFilter.java:48) at coldfusion.filter.MonitoringFilter.invoke(MonitoringFilter.java:40) at coldfusion.filter.PathFilter.invoke(PathFilter.java:86) at coldfusion.filter.ExceptionFilter.invoke(ExceptionFilter.java:70) at coldfusion.filter.ClientScopePersistenceFilter.invoke(ClientScopePersistenceFilter.java:2 8) at coldfusion.filter.BrowserFilter.invoke(BrowserFilter.java:38) at coldfusion.filter.NoCacheFilter.invoke(NoCacheFilter.java:46) at coldfusion.filter.GlobalsFilter.invoke(GlobalsFilter.java:38) at coldfusion.filter.DatasourceFilter.invoke(DatasourceFilter.java:22) at coldfusion.CfmServlet.service(CfmServlet.java:175) at coldfusion.bootstrap.BootstrapServlet.service(BootstrapServlet.java:89) at jrun.servlet.FilterChain.doFilter(FilterChain.java:86) at coldfusion.monitor.event.MonitoringServletFilter.doFilter(MonitoringServletFilter.java:42 ) at coldfusion.bootstrap.BootstrapFilter.doFilter(BootstrapFilter.java:46) at jrun.servlet.FilterChain.doFilter(FilterChain.java:94) at jrun.servlet.FilterChain.service(FilterChain.java:101) at jrun.servlet.ServletInvoker.invoke(ServletInvoker.java:106) at jrun.servlet.JRunInvokerChain.invokeNext(JRunInvokerChain.java:42) at jrun.servlet.JRunRequestDispatcher.invoke(JRunRequestDispatcher.java:286) at jrun.servlet.ServletEngineService.dispatch(ServletEngineService.java:543) at jrun.servlet.jrpp.JRunProxyService.invokeRunnable(JRunProxyService.java:203) at jrunx.scheduler.ThreadPool$DownstreamMetrics.invokeRunnable(ThreadPool.java:320) at jrunx.scheduler.ThreadPool$ThreadThrottle.invokeRunnable(ThreadPool.java:428) at jrunx.scheduler.ThreadPool$UpstreamMetrics.invokeRunnable(ThreadPool.java:266) at jrunx.scheduler.WorkerThread.run(WorkerThread.java:66)  
    I could really use some help figuring this out.  We are getting random errors a few times a day and usually in places where we are using CFLDAP.
    Thanks,
    David

    Absolutely unbelievable that this has been going on for 4 YEARS and there are still NO definitive answers from Adobe!!
    There's no definite answer from Adobe, because there's no definitive single question.  These errors come up because - for any number of possible reasons - the JVM becomes overloaded.  And it's almost always down to an issue with the application code being run, and nothing to do with CF, per-se.  So what's Adobe supposed to do?  Come and fix your application for you?  There are plenty of diagnostic tools out there - some built into CF itself - which you could use to sort the problem out.  Or you could hire someone like Mike Brunt to come and have a look at your set up.  All it takes to fix these things is to actually do something about fixing it, rather than slamming one's fist on the desk saying "why doesn't Adobe do something!"
    I thought - and my knowledge in the area isn't expansive - the inability to allocate threads was down to the app being choked up: threads are a finite commodity, and if requests are queuing up faster than the JVM can clear them, you're gonna get errors eventually.  What causes this sort of thing?  More traffic than the server can process.  This could be because of server kit, or it could be due to code that doesn't scale to the requirement.  Usually the latter.  Basically one cannot polish a turd.
    I have a 24x7 production server that services 180,000 clients in 300 countries around the clock that cannot afford to be down for more than a few minutes at a time.
    I'm running Windows 2008 32-bit with 4GB of RAM because I have some graphics software that cannot tolerate a 64-bit OS.  Everything has been running fine for the past few months, but now it's starting to crash more and more frequently.  I have CF 8.0.1.195765 and Java 1.6.0_04
    How many concurrent requests for 180000 clients generate?  The number of clients matters less than how heavily the site is used.  But, to be honest, I get the impression the implication is "it's a busy site", in which case I think your hardware is a bit on the lean side.  Also, if it's a mission-critical app, running it on a single server is probably ill-advised, just from a fault-tolerance perspective even before one starts thinking about performance.
    If I was in your situation, I'd consider the following options:
    * upgrade your JVM to the most recent version (1.6.0_21?)
    * put more RAM in the box, and run a second CF instance on it.
    * get another box.
    * refactor the environment so the graphics software runs on a different box, upgrading the CF server to 64-bit (again, with more RAM)
    * run some diagnostics on the server, seeing what's taking up threads and where any bottlenecks might be
    * get an expert in to do the analysis side of things.
    * stop expecting Adode to fix "something".
    One of my other symptoms I have noticed is that any work done using RDP starts getting really really bogged down.  Opening Windows Explorer and searching for files can take minutes.  Restarting the CF service will sometimes fail to complete, and you have to wait a few minutes before the manual Start option appears in the dropdown.  Maybe coincidentally, the Performance Monitor will fail to add any of the ColdFusion metrics, for example Running Requests and Queued Requests, and the Event Monitor shows an error relating to an 8-byte boundary not being maintained.
    You don't, by any chance, store your client variables in the registry do you?  The only time I've seen this happen is when the CF box is munging the OS environment, and the only way I can think this could happen if it was clogging the registry.  Never store client variables in the registry.
    Adam

  • Unable to create native thread in Normal Condition

    I am trying to analyze the "OOM unable to create native thread" error that occurred in our application. I wrote a sample program which has to creates 5000 threads and monitored it using JConsole.
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    * ThreadJvmMemory.java
    * Created on June 1, 2007, 9:49 AM
    * To change this template, choose Tools | Template Manager
    * and open the template in the editor.
    * @author Administrator
    public class ThreadJvmMemory extends Thread{
    /** Creates a new instance of ThreadJvmMemory */
    BufferedReader in = null;
    public ThreadJvmMemory() {
    public static void main(String args[]){
    ThreadJvmMemory dummy = new ThreadJvmMemory();
    dummy.waitTillEnter();
    for(int i=0;i<5000;i++){
    if(i%1000==0){
    System.out.println(i);
    dummy.waitTillEnter();
    ThreadJvmMemory dummy1 = new ThreadJvmMemory();
    dummy1.start();
    public void run(){
    //System.out.println("Here");
    Object dummyObject = new Object();
    try {
    in = new BufferedReader(new InputStreamReader(System.in));
    in.readLine();
    } catch (IOException ex) {
    ex.printStackTrace();
    System.out.println("Came out of the thread");
    public void waitTillEnter(){
    try {
    if(in==null)
    in = new BufferedReader(new InputStreamReader(System.in));
    in.readLine();
    } catch (IOException ex) {
    ex.printStackTrace();
    I started the program using the following command line option..
    "c:\Program Files\Java\jdk1.5.0_09\bin\java.exe" -Dcom.sun.management.jmxremote.port=9979 -Xmx512m -Xminf0.1 -Xmaxf0.1 -XX:MaxPermSize=256m -XX:PermSize=256m -XX:+<GCTYPE> -XX:+PrintGCDetails
    where GCType will be UseTrainGC or UseSerialGC or UseParallelGC or
    What i observe in all the cases, there are no more than 1000 threads getting created . After completion of 1000 threads garbage collector keeps running and no more threads get created. Since i have configured heapsize to be 512m, PermGenSpace to be 256 and default value for process sapece is 2gb, JVM would be able to create only 1000 threads as per the formula "NoOfThreads = Process space - (Heap + permGen+some for VM initialization)/Stack Size" (correct me if i am wrong). But why i am not getting OutOfMemoryError while creating native thread. Moreover i can observer non-heap (Perm Gen) space keep growing overtime. But there is enough space in all other spaces.So my doubts are
    1. Actually when we will get OOM error saying unable to create Native thread. To be more specific when which space occupied i will get this error.
    2. Is there any way to configure process space. IMO No ?? Confirm ??
    3. Does any one tried using a a tool that analyzes verboseGC output of SUN JVM. If so can you give any pointer. I have read through GCPortal, but i havent fully deployed it.
    Java version is 1.5.0
    OS Windows 2k3
    Snippet of GC Output
    [GC [DefNew: 5208K->38K(5824K), 0.0072564 secs] 32049K->26879K(34636K), 0.0080451 secs]
    [GC [DefNew: 5222K->24K(5824K), 0.0070320 secs] 32063K->26868K(34636K), 0.0078097 secs]
    [GC [DefNew: 5208K->39K(5824K), 0.0082161 secs] 32052K->26883K(34636K), 0.0090173 secs]
    [GC [DefNew: 5223K->27K(5824K), 0.0080766 secs] 32067K->26874K(34636K), 0.0089273 secs]
    [GC [DefNew: 5211K->39K(5824K), 0.0071186 secs] 32058K->26886K(34636K), 0.0078970 secs]
    [GC [DefNew: 5223K->25K(5824K), 0.0070952 secs] 32070K->26875K(34636K), 0.0078766 secs]
    [GC [DefNew: 5209K->21K(5824K), 0.0069871 secs] 32059K->26872K(34636K), 0.0077657 secs]

    I am trying to analyze the "OOM unable to create native thread" error that occurred in our application. I wrote a sample program which has to creates 5000 threads and monitored it using JConsole.
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    * ThreadJvmMemory.java
    * Created on June 1, 2007, 9:49 AM
    * To change this template, choose Tools | Template Manager
    * and open the template in the editor.
    * @author Administrator
    public class ThreadJvmMemory extends Thread{
    /** Creates a new instance of ThreadJvmMemory */
    BufferedReader in = null;
    public ThreadJvmMemory() {
    public static void main(String args[]){
    ThreadJvmMemory dummy = new ThreadJvmMemory();
    dummy.waitTillEnter();
    for(int i=0;i<5000;i++){
    if(i%1000==0){
    System.out.println(i);
    dummy.waitTillEnter();
    ThreadJvmMemory dummy1 = new ThreadJvmMemory();
    dummy1.start();
    public void run(){
    //System.out.println("Here");
    Object dummyObject = new Object();
    try {
    in = new BufferedReader(new InputStreamReader(System.in));
    in.readLine();
    } catch (IOException ex) {
    ex.printStackTrace();
    System.out.println("Came out of the thread");
    public void waitTillEnter(){
    try {
    if(in==null)
    in = new BufferedReader(new InputStreamReader(System.in));
    in.readLine();
    } catch (IOException ex) {
    ex.printStackTrace();
    I started the program using the following command line option..
    "c:\Program Files\Java\jdk1.5.0_09\bin\java.exe" -Dcom.sun.management.jmxremote.port=9979 -Xmx512m -Xminf0.1 -Xmaxf0.1 -XX:MaxPermSize=256m -XX:PermSize=256m -XX:+<GCTYPE> -XX:+PrintGCDetails
    where GCType will be UseTrainGC or UseSerialGC or UseParallelGC or
    What i observe in all the cases, there are no more than 1000 threads getting created . After completion of 1000 threads garbage collector keeps running and no more threads get created. Since i have configured heapsize to be 512m, PermGenSpace to be 256 and default value for process sapece is 2gb, JVM would be able to create only 1000 threads as per the formula "NoOfThreads = Process space - (Heap + permGen+some for VM initialization)/Stack Size" (correct me if i am wrong). But why i am not getting OutOfMemoryError while creating native thread. Moreover i can observer non-heap (Perm Gen) space keep growing overtime. But there is enough space in all other spaces.So my doubts are
    1. Actually when we will get OOM error saying unable to create Native thread. To be more specific when which space occupied i will get this error.
    2. Is there any way to configure process space. IMO No ?? Confirm ??
    3. Does any one tried using a a tool that analyzes verboseGC output of SUN JVM. If so can you give any pointer. I have read through GCPortal, but i havent fully deployed it.
    Java version is 1.5.0
    OS Windows 2k3
    Snippet of GC Output
    [GC [DefNew: 5208K->38K(5824K), 0.0072564 secs] 32049K->26879K(34636K), 0.0080451 secs]
    [GC [DefNew: 5222K->24K(5824K), 0.0070320 secs] 32063K->26868K(34636K), 0.0078097 secs]
    [GC [DefNew: 5208K->39K(5824K), 0.0082161 secs] 32052K->26883K(34636K), 0.0090173 secs]
    [GC [DefNew: 5223K->27K(5824K), 0.0080766 secs] 32067K->26874K(34636K), 0.0089273 secs]
    [GC [DefNew: 5211K->39K(5824K), 0.0071186 secs] 32058K->26886K(34636K), 0.0078970 secs]
    [GC [DefNew: 5223K->25K(5824K), 0.0070952 secs] 32070K->26875K(34636K), 0.0078766 secs]
    [GC [DefNew: 5209K->21K(5824K), 0.0069871 secs] 32059K->26872K(34636K), 0.0077657 secs]

  • OutOfMemoryError: unable to create native thread

    Why do I get OutOfMemory exceptions even if there is plently of Memory.
    JVM settings are -Xms256M and -Xmx1024M.
    Debug at runtime (Runtime.totalMemory()) shows that it never got above 260M. Why does the JVM not grab some more memory -instead of throwing OutOfMemory exception.
    I am creating quite a lot of threads 800+ within a few minutes
    Any ideas?

    I googled a bit and one thing i came across was
    "In those hypothetical configurations, the error java.lang.OutOfMemoryError: unable to create new native thread would begin to saturate the JRun logs. To clarify the error text, the error message means that no more native, or OS, threads can be created for the JVM process, causing the JVM to throw an exception. The exception type is java.lang.outOfMemoryError, but I find that to be rather misleading since the resource limitation on the OS thread count, not memory usage. "
    So it looks like you're looking for OS specific settings rather than anything pure java.
    Note that a thread per socket is not necessary, even when not using NIO:
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.io.Reader;
    import java.net.ServerSocket;
    import java.net.Socket;
    import java.util.HashMap;
    import java.util.LinkedList;
    import java.util.List;
    import java.util.Map;
    import java.util.concurrent.Executors;
    import java.util.concurrent.TimeUnit;
    public class ForumQuestion { 
        // i'm assuming character based input
        static final List<Reader> readers = new LinkedList<Reader>();
        static final Map<Reader,StringBuffer> buffers = new HashMap<Reader,StringBuffer>();
        static final Map<Reader,Socket> sockets = new HashMap<Reader,Socket>();
        public static void main( String[] args ) throws IOException {
            // using single thread (for simplicity) to handle all sockets
            // the main trick is making sure that your thread(s) doing the reading
            // don't sit and "spin" around the inputStreams when they have nothing
            // at all waiting... wasting CPU. Here i just make the worker sleep
            // for 1000 nanos between attempts where it hasn't read anything. I'm
            // sure you can do better!
            Executors.newScheduledThreadPool( 1 ).scheduleWithFixedDelay( new Runnable() {
                public void run() {
                    checkStreams();
            }, 1000, 1000, TimeUnit.NANOSECONDS );
            // create server socket and use main thread to block waiting for connections
            ServerSocket serverSock = new ServerSocket( 1138 );
            System.out.println( "Accepting connections on port 1138" );
            while( true ) {
                Socket s = serverSock.accept();
                synchronized( readers ) {
                    Reader r = new BufferedReader( new InputStreamReader( s.getInputStream() ) );
                    readers.add( r );
                    buffers.put( r, new StringBuffer() );
                    sockets.put( r, s );
                    System.out.printf( "Connection: %s%n", s );
        private static void checkStreams() {
            // i've been lazy (over zealous) with the synchronization for simplicity. you'd want to
            // Do something cleverer than blocking accepts() while work is being done
            synchronized( readers ) {
                if ( readers.size() == 0 ) {
                    return;
                // carry on until no work was done for any incoming sockets
                while( true ) {
                    boolean workDone = false;
                    for( Reader r : readers ) {
                        try {
                            StringBuffer buff = buffers.get( r );
                            while( r.ready() ) {
                                char c = (char)r.read();
                                buff.append( c );
                                checkBuffer( r, buff, c );
                                workDone = true;
                        } catch( IOException e ) {
                            // do something here, client prob dead
                    // if no work done (no sockets had anything) then rest the thread
                    if ( !workDone ) break;
        private static void checkBuffer( Reader r, StringBuffer buff, char last ) {
            if ( last == '\n' ) {
                System.out.printf( "Read \"%s\" from %s%n", buff.toString().trim(), sockets.get( r ) );
                buff.delete( 0, buff.length() );
    Accepting connections on port 1138
    Connection: Socket[addr=/127.0.0.1,port=1776,localport=1138]
    Connection: Socket[addr=/127.0.0.1,port=1777,localport=1138]
    Read "hello" from Socket[addr=/127.0.0.1,port=1776,localport=1138]
    Read "hi" from Socket[addr=/127.0.0.1,port=1777,localport=1138]
    Read "we're two sockets, but only using one thread to read from both of us!!" from Socket[addr=/127.0.0.1,port=1776,localport=1138]
    Read "Oh! YAY!!!!" from Socket[addr=/127.0.0.1,port=1777,localport=1138]It's massively inferior to using NIO, but better than having thousands of dedicated threads

  • JNI and Native Threads Doesn't work

    I am writing a wrapper class in C++ for a java class that publishes a message to JMS. In the C++ code I create the class, and call the one method. Everything does what it is supposed to, UNLESS more than one thread calls it. All the C++ wrapper stuff is in a DLL, and the classpath is correct for the java side, I then run an exe that is linked with the dll. The dll exposes one method that creates the java class, and calls the method. when more than one thread enters the DLL, I start getting class not found exceptions?? where as if I just call the method multiple times in a single thread, all works fine?? Please help, code included
    -----------------------DLL CODE-------------------------------
    extern "C"
    BOOL APIENTRY DllMain(HINSTANCE hInst,DWORD reason,LPVOID reserved)
    switch (reason)
    case DLL_PROCESS_ATTACH:
    if(!crit_init)
    printf("Initializing Critical Section\n");
    InitializeCriticalSection(&cs);
    crit_init = true;
    EnterCriticalSection(&cs);
    if(jvm == NULL)
    char buffer[1024];
    int portNum = -1;
    JavaVMInitArgs vm_args;
    JNIEnv *env = NULL;
    JavaVMOption options[4];
    memset(buffer,0,sizeof(buffer));
    strcat(buffer,"-Djava.class.path=");
    strcat(buffer,getenv("CLASSPATH"));
    printf("\nClassPath :\n\n%s",buffer);
    printf("\n\n");
    options[0].optionString = "-Djava.compiler=NONE"; // disable JIT
    options[1].optionString = buffer; // user classes
    options[2].optionString = "-Xms64M";
    options[3].optionString = "-Xmx64M";
    vm_args.version = JNI_VERSION_1_2;
    vm_args.options = options;
    vm_args.nOptions = 4;
    vm_args.ignoreUnrecognized = 1;
    printf("Creating JVM\n\n");
    if(JNI_CreateJavaVM(&jvm, (void **)&env, &vm_args ) != 0)
    printf("Failed to Create JVM!\n");
    LeaveCriticalSection(&cs);
    return false;
    printf("JVM Created\n\n");
    LeaveCriticalSection(&cs);
    return true;
    case DLL_PROCESS_DETACH:
    break;
    case DLL_THREAD_ATTACH:
    break;
    case DLL_THREAD_DETACH:
    break;
    /* Returns TRUE on success, FALSE on failure */
    return TRUE;
    DLLIMPORT char* publishAndWait(char * destination,
    char* payloadFormat, char* transactionType,
    char *payload, int timeoutSec)
    JNIEnv* jEnv = NULL;
    if(jvm->AttachCurrentThread((void**) &jEnv, NULL) || jEnv == NULL)
    printf("AttachCurrentThread error\n");
    return NULL;
    EnterCriticalSection(&cs);
    if(jmsStub == NULL)
    int portNum = -1;
    char buffer[10];
    memset(buffer,0,sizeof(buffer));
    itoa(portNum,getenv("CORBA_RESP_PORT"),10);
    printf("Creating JMSStub Instance\n");
    jmsStub = new JMSStub(getenv("WL_URL"),getenv("WL_CONN_FACTORY"),portNum,jEnv);
    printf("JMSStub Created\n\n");
    LeaveCriticalSection(&cs);
    return jmsStub->publishAndWait(destination,payloadFormat,
    transactionType,payload,timeoutSec,jEnv);
    int retDetVal = jvm->DetachCurrentThread();
    if(retDetVal)
    printf("DetachCurrentThread error %d\n", retDetVal);
    return NULL;
    ----------------------JMS STUB CLASS (IN DLL)-------------------------
    JMSStub::JMSStub(string wlURL, string connectionFactory, int responsePort,JNIEnv* jEnv)
    printf("Setting Local Strings\n");
    this->wlURL = wlURL;
    this->connectionFactory = connectionFactory;
    this->responsePort = responsePort;
    printf("Local Strings Set\n");
    // load class
    this->loadMethodIDs(jEnv);
    localObject = jEnv->NewObject(jmsStubCls,stubMethodMap.find("<init>")->second,
    jEnv->NewStringUTF(wlURL.c_str()),jEnv->NewStringUTF(connectionFactory.c_str()),
    responsePort,false);
    // create global reference so garbage collection will not take place
    printf("Creating GlobalRef to JMSStub Instance\n");
    globalObject = jEnv->NewGlobalRef(localObject);
    void JMSStub::loadMethodIDs(JNIEnv* jEnv)
    printf("Getting Hashtable Class\n");
    hashTableCls = jEnv->FindClass("java/util/Hashtable" );
    printf("Getting JMSStub Class\n");
    jmsStubCls = jEnv->FindClass("com/pacificare/common/jms/JMSStub");
    if(hashTableCls == NULL)
    printf("Error Getting Hashtable information!!\n");
    exit(-255);
    if(jmsStubCls == NULL)
    printf("Error Getting JMSStub information!!\n");
    exit(-255);
    printf("Getting Hashtable Methods\n");
    /* Get Hashtable Constructor */
    hashMethodMap.insert(MethodIDMap::value_type("<init>",
    jEnv->GetMethodID(hashTableCls, "<init>","()V")));
    /* get put method id */
    hashMethodMap.insert(MethodIDMap::value_type("put",jEnv->GetMethodID(hashTableCls, "put",
    "(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;")));
    printf("Getting JMSStub Methods\n");
    /* get JMSStub constructor */
    stubMethodMap.insert(MethodIDMap::value_type("<init>",jEnv->GetMethodID(jmsStubCls, "<init>",
    "(Ljava/lang/String;Ljava/lang/String;IZ)V" )));
    /* find the publishAndWait method */
    stubMethodMap.insert(MethodIDMap::value_type("publishAndWait",jEnv->GetMethodID(jmsStubCls,"publishAndWait",
    "(Ljava/lang/String;Ljava/util/Hashtable;I)Ljava/lang/String;")));
    bool JMSStub::hasExceptionOccurred(JNIEnv* jEnv)
    jthrowable     jthr = NULL;
    jthr = jEnv->ExceptionOccurred();
    if(jthr == NULL)
    return false;
    jEnv->ExceptionDescribe();
    jEnv->ExceptionClear();
    return true;
    char* JMSStub::publishAndWait(char * destination,
    char* payloadFormat, char* transactionType,
    char payload, int timeoutSec,JNIEnv jEnv)
    jmethodID hpMid = hashMethodMap.find("put")->second;
    // Strings used in methods, constructors, ect
    jstring destinationStr = jEnv->NewStringUTF(destination);
    jstring payloadFormatStr = jEnv->NewStringUTF(payloadFormat);
    jstring transTypeStr = jEnv->NewStringUTF(transactionType);
    jstring payloadStr = jEnv->NewStringUTF(payloadFormat);
    jobject localHashtable = jEnv->NewObject(hashTableCls,hashMethodMap.find("<init>")->second);
    jEnv->CallObjectMethod(localHashtable,hpMid,jEnv->NewStringUTF("^^^^^payloadFormat"),payloadFormatStr);
    jEnv->CallObjectMethod(localHashtable,hpMid,jEnv->NewStringUTF("^^^^^transactionType"),transTypeStr);
    jEnv->CallObjectMethod(localHashtable,hpMid,jEnv->NewStringUTF("^^^^^payload"),payloadStr);
    jstring retStr = (jstring)jEnv->CallObjectMethod(globalObject,
    stubMethodMap.find("publishAndWait")->second,
    destinationStr,localHashtable,timeoutSec);
    if(hasExceptionOccurred(jEnv))
    printf("Exception has occurred.\n");
    return NULL;
    else
    if(retStr == NULL)
    return NULL;
    const char *utfPtr = jEnv->GetStringUTFChars(retStr,0);
    int len = jEnv->GetStringUTFLength(retStr);
    char returnStr = (char)malloc(len);
    memset(returnStr,0,len);
    memcpy(returnStr,utfPtr,len);
    jEnv->ReleaseStringUTFChars(retStr,utfPtr);
    return returnStr;
    ------------------------------EXE------------------------------------
    DWORD WINAPI ThreadFunc( LPVOID lpParam )
    char buffer = (char )lpParam;
    const char *tst = publishAndWait("vitria.jms.authreq","XML","276",buffer,120);      
    if(tst == NULL)
    printf("No Response\n");
    else
    printf("%s\n",tst);
    delete tst;
    tCntDone++;
    _endthread();
    char * readFile(char* fileName)
    FILE *xmlFile = NULL;
    printf("Opening File %s\n",fileName);
    if((xmlFile = fopen(fileName,"r")) == NULL)
    printf("Unable to open File %s\n",fileName);
    exit(-256);
    long fileLen = filelength(fileno(xmlFile));
    char *buffer = new char[30000];
    memset(buffer,0,sizeof(buffer));
    fread(buffer,fileLen,1,xmlFile);
    buffer[fileLen] = '\0';
    fclose(xmlFile);
    return buffer;
    int main(int argc, char *argv[])
    DWORD dwThreadId[2];
    HANDLE hThread[2];
    char *buffer = NULL;
    if(argc < 2)
    printf("You must supply the name of the xml file as an argument!!\n");
    exit(-255);
    buffer = readFile(argv[1]);
    printf("%s\n",buffer);
    for(int i = 0; i < 2; i++)
    printf("Creating Thread %x\n",i);
    hThread[i] = CreateThread(NULL,0,ThreadFunc,buffer,0,&dwThreadId);
    Sleep(1000);
    while(tCntDone < 2)
    Sleep(3000);
    //printf("Threads Complete %x\n",tCntDone);
    CloseHandle(hThread[0]);
    CloseHandle(hThread[1]);
    /*for(int x = 0; x < 2;x++)
    const char *tst = publishAndWait("vitria.jms.authreq","XML","276",buffer,120);      
    if(tst == NULL)
    printf("No Response\n");
    else
    printf("%s\n",tst);
    delete tst;
    delete(buffer);

    Ok, I have done some more testing. It appears that two native threads cannot access the same java object, even if a global reference exist, and you call AttachCurrentThread, and using that env pointer to make calls. It always fails with some java error, like ClassNotFoundError, and only on the second native thread created. Is this a part of the spec or is it a bug, or am I having an operator malfuntion?

  • Stopping native-threads

    hi all,
    how can i stop native (hanging) threads?
    i see that many people have this question but i can't find any real solution.
    all the time sun said we should us cancel-flags in a loop in the thread. but how to do this when the threads was written from other with native code (the most original io-classes from sun , eg. java.net.UrlConnection)?!
    look at the following code example:
    in linux and mac os-x the timeout for dns-lookups needs between 40 and 60 seconds. but what if you don't like to wait so long?! if you like to test many 1000 urls (internal and external urls mixed)
    latest with jdk 1.4 you will get almost internel-jvm-error ending in a java-crash if you test in a loop much urls.
    but please! if somebody has a thread-save-soluton please post it!
    thx
    oliver scorp
    code-example:
    ublic final class Test1 {
    private boolean urlErr = false;
    private String urlErrMsg = null;
    private int urlTimeout = 5;
    public final class TestUrlConnection extends Thread{
    private String myUrl = null;
    public TestUrlConnection(String parMyUrl) {
    super();
    myUrl = parMyUrl;
    public void run(){
    try{
    if (myUrl == null)
    return;
    java.net.URL u = new java.net.URL(myUrl);
    java.net.URLConnection uc = u.openConnection();
    uc.connect(); // 40 sec timout in linux when url not can be connected !!!
    // 60 sec timeout in MAC OS-X !!!
    // 1 sec timeout in Windows !!! (so, this example maybe doesn't work there!)
    }catch(Exception e){
    urlErr = true;
    urlErrMsg = e.toString();
    public Test1() {
    super();
    public static void main (String args[]) {
    Test1 myProg = new Test1();
    myProg.myTest1();
    public void myTest1() {
    try{
    String s = "http://www.apache.org";
    TestUrlConnection tuc = new TestUrlConnection(s);
    tuc.start();
    tuc.join(urlTimeout * 1000);
    if (tuc.isAlive()){
    tuc.stop(); //searching for an alterNATIVE
    //is extrem instable in jdk 1.4!
    //(get almost internal errors in jvm if you have many 100 test-threads)
    //tuc.interrupt(); //doesn't work by native (hanging) threads
    //tuc = null; //doesn't stop the thread
    urlErr = true;
    urlErrMsg = "Connection timeout!";
    if (urlErr)
    System.out.println(urlErrMsg);
    else
    System.out.println("Connection ok");
    }catch(Exception e){
    System.out.println(e.toString());

    the question was: how to end native threads - threadsave (without using the 'deprecated' stop-methode)?!So you have a C method (not Java) in which you created a thread that runs C code (not Java) and it is indeed running, not blocked, and you wish to end it?
    Seems like a bad design and bad idea to me, because it is very likely that it will cause memory leaks, and since it it hard to cause it to stop at arbritrary points in its execution it will also be hard to use an automated tool to track down those leaks.
    But if you have already dealt with all of those issues then you could stop it. The answer to how is specific to the thread library that you are using. So at the very least you would have to specify that. And since this particular topic has nothing to do with java you might find an answer on another list/forum/group faster.
    Despite all of the above, if the thread touches java in any way then I would say that trying to stop it arbritrarily is going to be a really bad idea. Java isn't set up for that. And at the very least you will end up with memory leaks (with no way to get rid of them, since they are likely to be internal to the JVM.) And that would be the best outcome. It is also possible that it would make the JVM unstable and I can't imagine any application where that is going to be a good thing.

  • WS 6.1SP5 gives error "unable to create native threads"

    Hi All,
    We are using AM7.0 on Sun Java Web Server 6.1 SP5. This is running on T2000 with 8 GB RAM on Solaris 10. We have implemented all the recommendations given by amtune script except Stack Size (-Xss128K). amtune recommends Stack Size of 128K. But our Web Server doesn't run with 128K. We had to bump it up to 192K.
    After some time in our load test, we get following error in our logs:
    ERROR: ConsoleServletBase.onUncaughtException
    com.iplanet.jato.NavigationException: Exception encountered during forward
    Root cause = [java.lang.OutOfMemoryError: unable to create new native thread]
    at com.iplanet.jato.view.ViewBeanBase.forward(ViewBeanBase.java:380)
    at com.iplanet.jato.view.ViewBeanBase.forwardTo(ViewBeanBase.java:261)
    at com.sun.identity.console.base.AMViewBeanBase.forwardTo(AMViewBeanBase.java:135)
    at com.sun.identity.console.base.AMAdminFrameViewBean.forwardTo(AMAdminFrameViewBe an.java:111)
    at com.iplanet.jato.ApplicationServletBase.dispatchRequest(ApplicationServletBase. java:981)
    at com.iplanet.jato.ApplicationServletBase.processRequest(ApplicationServletBase.j ava:615)
    at com.iplanet.jato.ApplicationServletBase.doGet(ApplicationServletBase.java:459)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:787)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:908)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFil terChain.java:247)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain .java:193)
    at com.sun.mobile.filter.AMLController.doFilter(AMLController.java:163)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFil terChain.java:213)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain .java:193)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java: 280)
    at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:509)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java: 212)
    at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:509)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:209)
    at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:509)
    at com.iplanet.ias.web.connector.nsapi.NSAPIProcessor.process(NSAPIProcessor.java: 161)
    at com.iplanet.ias.web.WebContainer.service(WebContainer.java:580)
    Root cause:
    java.lang.OutOfMemoryError: unable to create new native thread
    at java.lang.Thread.start0(Native Method)
    at java.lang.Thread.start(Thread.java:574)
    at netscape.ldap.LDAPConnSetupMgr.openConnection(LDAPConnSetupMgr.java:212)
    at netscape.ldap.LDAPConnThread.connect(LDAPConnThread.java:109)
    at netscape.ldap.LDAPConnection.connect(LDAPConnection.java:1075)
    at netscape.ldap.LDAPConnection.connect(LDAPConnection.java:946)
    at netscape.ldap.LDAPConnection.connect(LDAPConnection.java:858)
    Does anybody knows what this error is and how to tackle this problem ?
    Thanks in advance,
    Vivek

    Hi Sultal,
    Thanks for the response. I will try reducing the ms and mx options. BTW, following are my WS' JVM settings:
    <JAVA javahome="/usr/jdk/entsys-j2se" serverclasspath="/opt/SUNWwbsvr/bin/https/jar/webserv-rt.jar:${java.home}/lib/t
    ools.jar:/opt/SUNWwbsvr/bin/https/jar/webserv-ext.jar:/opt/SUNWwbsvr/bin/https/jar/webserv-jstl.jar:/usr/share/lib/ktse
    arch.jar" classpathsuffix="/opt/SUNWam/lib/xalan.jar:/opt/SUNWam/lib/xmlsec.jar:/opt/SUNWam/lib/xercesImpl.jar:/opt/SUN
    Wam/lib/dom.jar:/opt/SUNWam/lib/saaj-api.jar:/opt/SUNWam/lib/jaxrpc-api.jar:/opt/SUNWam/lib/jaxrpc-impl.jar:/opt/SUNWam
    /lib/jaxrpc-spi.jar:/opt/SUNWam/lib/saaj-impl.jar:/etc/opt/SUNWam/config:/opt/SUNWam/lib:/opt/SUNWam/locale:/usr/share/
    lib/mps/secv1/jss4.jar:/opt/SUNWam/lib/am_sdk.jar:/opt/SUNWam/lib/ldapjdk.jar:/opt/SUNWam/lib/am_services.jar:/opt/SUNW
    am/lib/am_sso_provider.jar:/opt/SUNWam/lib/swec.jar:/opt/SUNWam/lib/acmecrypt.jar:/opt/SUNWam/lib/iaik_ssl.jar:/opt/SUN
    Wam/lib/iaik_jce_full.jar:/opt/SUNWam/lib/mail.jar:/opt/SUNWam/lib/activation.jar:/opt/SUNWam/lib/am_logging.jar:/opt/S
    UNWam/lib/jaas.jar:/opt/SUNWam/lib/jax-qname.jar:/opt/SUNWam/lib/jaxm-api.jar:/opt/SUNWam/lib/jaxm-runtime.jar:/opt/SUN
    Wam/lib/jce1_2_1.jar:/opt/SUNWam/lib/jdk_logging.jar:/opt/SUNWam/lib/namespace.jar:/opt/SUNWam/lib/relaxngDatatype.jar:
    /opt/SUNWam/lib/xsdlib.jar:/opt/SUNWam/lib/jaxb-api.jar:/opt/SUNWam/lib/jaxb-impl.jar:/opt/SUNWam/lib/jaxb-libs.jar:/op
    t/SUNWam/lib/jaxb-xjc.jar:/opt/SUNWma/lib/wireless_rendering.jar:/opt/SUNWma/lib/wireless_rendering_util.jar:/opt/SUNWm
    a/lib/mobile_services.jar:/opt/SUNWma/lib/ccpp-1_0.jar:/opt/SUNWma/lib/ccpp-ri-1_0.jar:/opt/SUNWma/lib/jena-1.4.0.jar:/
    opt/SUNWma/lib/rdffilter.jar:/opt/SUNWma/lib/locale:/opt/SUNWam/lib/mobile_identity.jar:" envclasspathignored="true" na
    tivelibrarypathprefix="" debug="false" debugoptions="-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=n" dynamicr
    eloadinterval="-1">
    <JVMOPTIONS>-Ds1is.java.util.logging.config.class=com.sun.identity.log.s1is.LogConfigReader</JVMOPTIONS>
    <JVMOPTIONS>-DLOG_COMPATMODE=Off</JVMOPTIONS>
    <JVMOPTIONS>-Djava.security.auth.login.config=/opt/SUNWwbsvr/https-ndmseauqa01.ndc.nasa.gov/config/login.conf</JVMO
    PTIONS>
    <JVMOPTIONS>-Djava.protocol.handler.pkgs=com.iplanet.services.comm</JVMOPTIONS>
    <JVMOPTIONS>-Dcom.iplanet.am.serverMode=true</JVMOPTIONS>
    <JVMOPTIONS>-Djava.util.logging.manager=com.iplanet.ias.server.logging.ServerLogManager</JVMOPTIONS>
    <JVMOPTIONS>-Xmx3136M</JVMOPTIONS>
    <JVMOPTIONS>-Xms3136M</JVMOPTIONS>
    <JVMOPTIONS>-Xloggc:/opt/SUNWwbsvr/https-eauthws/logs/gc.log</JVMOPTIONS>
    <JVMOPTIONS>-server</JVMOPTIONS>
    <JVMOPTIONS>-Xss192K</JVMOPTIONS>
    <JVMOPTIONS>-XX:NewSize=392M</JVMOPTIONS>
    <JVMOPTIONS>-XX:MaxNewSize=392M</JVMOPTIONS>
    <JVMOPTIONS>-XX:PermSize=260M</JVMOPTIONS>
    <JVMOPTIONS>-XX:MaxPermSize=260M</JVMOPTIONS>
    <JVMOPTIONS>-XX:+DisableExplicitGC</JVMOPTIONS>
    <JVMOPTIONS>-XX:+UseParNewGC</JVMOPTIONS>
    <JVMOPTIONS>-XX:+CMSPermGenSweepingEnabled</JVMOPTIONS>
    <JVMOPTIONS>-XX:+CMSClassUnloadingEnabled</JVMOPTIONS>
    <JVMOPTIONS>-XX:+UseCMSCompactAtFullCollection</JVMOPTIONS>
    <JVMOPTIONS>-XX:CMSFullGCsBeforeCompaction=0</JVMOPTIONS>
    <JVMOPTIONS>-XX:SoftRefLRUPolicyMSPerMB=0</JVMOPTIONS>
    <JVMOPTIONS>-XX:+PrintClassHistogram</JVMOPTIONS>
    <JVMOPTIONS>-XX:+PrintGCDetails</JVMOPTIONS>
    <JVMOPTIONS>-XX:+PrintGCTimeStamps</JVMOPTIONS>
    <JVMOPTIONS>-XX:+UseConcMarkSweepGC</JVMOPTIONS>
    The error happens when the LWPs of the process goes beyond 500. In our load testing the server is getting hit 2000 requests per minute.
    I will reduce the mx and ms size, in the mean time, if you can take a look at any other thing that I need to do.
    One more thing, from where the native threads get allocated? (Heap/Perm/somewhere else)
    Regards,
    Vivek
    There is a certain limit for a number of threads that
    JVM can create. This limit depends on the OS and JVM
    options. You can try using XX:PermSize and
    -XX:MaxPermSize options as well as lowering -Xms and
    -Xmx options.

  • OutOfMemory : Unable to new native thread

    Let me start off by giving some background.
    We began experiencing this issue within the past month
    in our production environment, but cannot reproduce
    it in an isolated testing environment.
    I have performed extensive tests in regards to Heap Sizes
    and Thread Stack sizes in hopes of resolving this issue, but
    none have worked.
    Hardware/OS Settings
    OS for platform is Linux
    Distribution is RHAS 2.1
    Kernel version is 2.4.9-e.30enterprise SMP
    Box has 2 CPUs which are hyperthreaded
    ULIMIT settings
    core file size (blocks) 0
    data seg size (kbytes) unlimited
    file size (blocks) unlimited
    max locked memory (kbytes) unlimited
    max memory size (kbytes) unlimited
    open files 1024
    pipe size (512 bytes) 8
    stack size (kbytes) 8192
    cpu time (seconds) unlimited
    max user processes 8191
    virtual memory (kbytes) unlimited
    /etc/sysctl.conf , contains (effectively overrides the ulimt setting)
    fs.file-max = 65535
    /proc/sys/kernel/threads-max
    16383
    glibc version is 2.2.4
    Physical Mem : ~ 2 Gig
    Swap : ~ 4 Gig
    JVM Settings
    java version "1.4.2_03"
    Java(TM) 2 Runtime Environment, Standard Edition (build 1.4.2_03-b02)
    Java HotSpot(TM) Client VM (build 1.4.2_03-b02, mixed mode)
    -server -Djava.awt.headless=true -XX:+DisableExplicitGC -Xms1228m -Xmx1228m -XX:NewSize=256m -XX:MaxNewSize=256m -XX:+UseParNewGC -XX:+UseConcMarkSweepGC -XX:+CMSParallelRemarkEnabled -XX:+UseCMSCompactAtFullCollection -verbosegc -verbosegc -XX:+PrintGCDetails -Xloggc:/opt/logs/gc_log.txt
    Tests
    The way i understand it, the memory available for thread creation is:
    Physical Memory - "-Xmx" = ~ 800 MB (in our case)
    Also, the default stack size on linux is 512k, so a base line (with no other
    phyical memory usage than the JVM) is:
    800 * 1000 / 512 = ~ 1562 threads
    however, i when the error recurrs, i can do a :
    ps -ef | grep java | wc -l (each java thread is represented by a process on linux)
    and that # is way below 1562 (approx 90 or so)
    additionally, via java code at the time of the exception you can get
    the Mother Thread group:
            private static ThreadGroup getMotherThreadGroup()
              ThreadGroup mother = Thread.currentThread().getThreadGroup();
              while(mother.getParent() != null)
                   mother = mother.getParent();
              return mother;
         }and then get the # of threads in the group:
            Thread      currentThread = Thread.currentThread();
            ThreadGroup mother        = getMotherThreadGroup();       
         Thread[]    threads       = new Thread[mother.activeCount() + 5];          
            int threadCount;
            for (int count;;)
                count = mother.enumerate(threads,true);
                if (count < threads.length)
                    threadCount = count;
                    break;
                threads = new Thread[threads.length << 1];
            }  once again this # is way below 1562 (matches rougly to the 'ps' output)
    Additionally, I have modified the JVM parameters to indepdently reduce
    -Xms by 100 m and reduce the stack size to -Xss256k and neither of
    these resolve the issue.
    Questions
    What other OS level settings could be affecting the # of threads that can be created?
    What JVM settings could be affecting the # of threads that can be created?
    Are there ever Java threads present that will no be represented by the
    code in this post, or a 'ps' process listing?

    Some additional information, in regards to Linux and Maximum # of Threads.
    This bug entry in Redhat's Bug DB, provides some insight into the native
    thread threshold:
    https://bugzilla.redhat.com/bugzilla/show_bug.cgi?id=70058
    From the Java Bug Database:
    On Redhat 7.2, the pthread library has a hard-coded thread limit, which
    is 1024. To increase this limit, you have to change PTHREAD_THREADS_MAX
    and recompile pthread library. See LinuxThreads FAQ. Hitting an
    OutOfMemoryError after 1014 threads on RH-7.2 is normal.
    The error on RH-9 looks strange. But when I tested on my RH-9 box, things
    work ok. The testcase runs until it has hit one of the system limits:
    + max user processes (use "ulimit -u" to adjust)
    + thread limit, this is calculated based on the amount of physical memory
    (you can change it by editing /proc/sys/kernel/threads-max)
    + virtual memory. 32bit Linux by default allows 2GB virtual address space
    in user application. Unless you specify a smaller stack size (-Xss96k
    will do it), java will run out of virtual space in about 4000 threads
    (default stack size is 512k, 2GB/512k = 4096, but notice that the
    virtual memory is also used for C heap, library image, data segments, et al.)
    Another Linux Thread explanation:
    Threads
    Limitations on threads are tightly tied to both file descriptor
    limits, and process limits.
    Under Linux, threads are counted as processes, so any limits to
    the number of processes also applies to threads. In a heavily
    threaded app like a threaded TCP engine, or a java server, you
    can quickly run out of threads.
    For starters, you want to get an idea how many threads you can
    open. The `thread-limit` util mentioned in the Tuning Utilities
    section is probabaly as good as any.
    The first step to increasing the possible number of threads is
    to make sure you have boosted any process limits as mentioned
    before.
    There are few things that can limit the number of threads,
    including process limits, memory limits, mutex/semaphore/shm/ipc
    limits, and compiled in thread limits. For most cases, the
    process limit is the first one to run into, then the compiled in
    thread limits, then the memory limits.
    To increase the limits, you have to recompile glibc. Oh fun!.
    And the patch is essentially two lines!. Woohoo!
    --- ./linuxthreads/sysdeps/unix/sysv/linux/bits/local_lim.h.akl Mon Sep 4
    19:37:42 2000
    +++ ./linuxthreads/sysdeps/unix/sysv/linux/bits/local_lim.h Mon Sep 4
    19:37:56 2000
    @@ -64,7 +64,7 @@
    /* The number of threads per process. */
    #define POSIXTHREAD_THREADS_MAX 64
    /* This is the value this implementation supports. */
    -#define PTHREAD_THREADS_MAX 1024
    +#define PTHREAD_THREADS_MAX 8192
    /* Maximum amount by which a process can descrease its asynchronous I/O
    priority level. */
    --- ./linuxthreads/internals.h.akl Mon Sep 4 19:36:58 2000
    +++ ./linuxthreads/internals.h Mon Sep 4 19:37:23 2000
    @@ -330,7 +330,7 @@
    THREAD_SELF implementation is used, this must be a power of two and
    a multiple of PAGE_SIZE. */
    #ifndef STACK_SIZE
    -#define STACK_SIZE (2 * 1024 * 1024)
    +#define STACK_SIZE (64 * PAGE_SIZE)
    #endif
    /* The initial size of the thread stack. Must be a multiple of PAGE_SIZE.
    Now just patch glibc, rebuild, and install it. ;-> If you have a
    package based system, I seriously suggest making a new package
    and using it.
    And two links that describe Linux/GLIBC changes and how they affect threads:
    http://www.jlinux.org/server.html
    http://www.volano.com/linux.html
    C Code for testing Native Thread Creation:
    /* compile with:   gcc -lpthread -o thread-limit thread-limit.c */
    /* originally from: http://www.volano.com/linuxnotes.html */
    #include <stdio.h>
    #include <unistd.h>
    #include <pthread.h>
    #define MAX_THREADS 10000
    int i;
    void run(void) {
      char c;
      if (i < 10)
        printf("Address of c = %u KB\n", (unsigned int) &c / 1024);
      sleep(60 * 60);
    int main(int argc, char *argv[]) {
      int rc = 0;
      pthread_t thread[MAX_THREADS];
      printf("Creating threads ...\n");
      for (i = 0; i < MAX_THREADS && rc == 0; i++) {
        rc = pthread_create(&(thread), NULL, (void *) &run, NULL);
    if (rc == 0) {
    pthread_detach(thread[i]);
    if ((i + 1) % 100 == 0)
         printf("%i threads so far ...\n", i + 1);
    else
    printf("Failed with return code %i creating thread %i.\n",
         rc, i + 1);
    exit(0);

  • JNI native thread priority

    Hi,
    I have some JNI code that spawns a win32 thread using CreateThread and then sets it priority using SetThreadPriority.
    If i set priority higher than ABOVE_NORMAL ( i would prefer time critical), it seems the JVM crashes on exit.
    I've commented everything out in the thread method itself except to let it do a while(true){Sleep(1);}.
    If i remove the SetThreadPriority or set it to ABOVE_NORMAL or less the JVM doesnt crash when the java code calls System.exit but otherwise it does.
    Any ideas concerning this?

    Hmm..
    I was using System.runFinalizersOnExit(true), when i removed that from the java side the problem disappeared. I dont really need to make that call anyway, but i dont like when errors disappears and i dont understand why, so i would like to know how that call in conjunction with a high priority native thread can cause a jvm crash?

Maybe you are looking for

  • Why is keyPressed() not being executed in this code..??

    HI, I am trying to develop a simple game program but what is banging my head is the keyPressed(KeyEvent evnt) is not being executed, i.e. the System.out.println("XXXX") inside this method is not being reached and hence shows no any output. Any sugges

  • Hi Good Day to all experts

    I am new to java swing. I just want to ask help to all the experts here in this forum on how to display image in JLabel after pressing a JButton components. Hope you can all help me

  • Load temperatures on Macbook Pro 2014 Models

    Has anyone created or is anyone aware of another site which tests the load temperatures of any of the new 2014 macbook pros?  I am particularly interested to see load temperature difference on the MBP Retina with Iris Pro vs discrete nVidia, and the

  • Tape Co-Location

    I'm having a problem getting DPM configured to co-locate tapes the way I want. I have 6 protection groups, 3 configured for one Co-Located Protection Group Set, and 3 for another. I have a tape library with 2 drives (Dell TL2000). The problem I am ex

  • Berkeley DB installation guide asking...

    Hi, I'm the new user of Berkeley DB. I facing one of the problem now. Actually I'm trying to install DB_File Version 1.82. It requires Berkeley DB for PREREQUISITES. I'm using the ia64 GNU/Linux, perl, v5.8.8. I got a bit confusing which path or link