What's in the JVM Process's Memory Space?

Hello
I'm noticing the following behavior on an NT system. On
application startup, I see
Total Heap 9 MB
Used Heap 5.5 MB
java.exe memory (from NT Task Manager) 36 MB
After a "login" operation which loads a few more
classes:
Total Heap 12.5 MB
Used Heap 8.2 MB
java.exe memory (from NT Task Manager) 53 MB
Heap memory leaks have been ruthlessly suppressed
(thanks to OptimizeIt and careful programming). The
behavior I do not understand is that the NT process
(java.exe) increased in size by 17 MB when the Java
heap increased by only 3 MB. The .jar file in which the
application resides is less than 1 MB, so this 14 MB
growth can not be attributed to new classes being
loaded.
Does anyone know what is going into the process
memory space of java.exe? It tends to grow larger
and larger.
Should I even care? Do I want a large allocation of
process memory for java.exe, or will that hamper
performance of machines with less physical memory?
Posts on related topics in this forum have sometimes
advocated allocating a lot of memory to the JVM with
-X options.
Thanks

Hello
I am facing exactly the same problem on NT. However, on 2000 Server this problem doesn't seem to exist. Are you, by any chance, using JNI? We are extensively using JNI in our Servlets and found that there is definitely some momory leak there. We could not figure out any substantial leak at Java end. In NT's "Task Manager" java.exe is always listed first and very rarely the memory usage seems to come down. On 2000 Server the performance is far better.
Please visit this link:
http://forum.java.sun.com/thread.jsp?forum=33&thread=211330
Regards
Manish Bhatnagar

Similar Messages

  • Does the JVM ever return memory back to the OS?

    Hello Gurus,
    I have an OC4J application running on Solaris that have some memory spikes (the jvm is inovked with -xms256m -xmx1024m).
    I've noted that once the heap expands, even if it shrinks back, the jvm process keeps on using the bigger memory footprint (in other words, maybe the jvm indeed manages a smaller heap size but if I execute the "top" command from a terminal - I never see that memory actually being freed).
    For the math people: my jvm memory consumption is a non-decreasing monotonic function.
    Is that a bug or the designed behavior?
    Thanks in advance!
    Amnon Sadeh.

    The physical memory and swap reservation is indeed returned
    to the OS if it's not in use. The virtual space reservation, however,
    stays.. The JVM is however circumspect/inertial is reacting to
    temporary fluctuations in java heap footprint, and employs
    a hysteretic low-pass-filter to protect against what might be
    small, high frequency fluctuations in the program's heap
    footprint.
    Hello Gurus,
    I have an OC4J application running on Solaris that
    have some memory spikes (the jvm is inovked with
    -xms256m -xmx1024m).
    I've noted that once the heap expands, even if it
    shrinks back, the jvm process keeps on using the
    bigger memory footprint (in other words, maybe the
    jvm indeed manages a smaller heap size but if I
    execute the "top" command from a terminal - I never
    see that memory actually being freed).
    For the math people: my jvm memory consumption is a
    non-decreasing monotonic function.
    Is that a bug or the designed behavior?
    Thanks in advance!
    Amnon Sadeh.

  • How to determine the size of the JVM process?

    Hi,
    How to determine the total process size of the JVM process (that includes Heap, Non Heap and Native memory)?
    Is there any command to obtain this value on Solaris (for Sun JVM)?
    I refer the process size to http://middlewaremagic.com/weblogic/wp-content/uploads/2010/11/Java_Heap_Diagram_12.jpg) here.
    Many thanks for your help in advance!

    Hi,
    Make sure that Total Heap + Native memory will be consider as total Memory.
    That means in 32 bit you will have only at most 4 GB for process + additional 2 GB for OS.
    So let assume if you have 4GM RAM then out of the 4GB you can allocate 2GB as Heap and 512m as Perm in case of Hot spot and remaining will be consider as Native memory.
    But in case of 64 bit will change you will have good amount of the memory so you can use plenty of Heap and Perm size.
    Still if you have query let me know.
    Regards,
    Kal

  • Anybody could told me when the JVM process will disappear?

    1.The system is RHEL5.1 and PC is my private machine, not connect to internet or local network.
    2.I was had a tomcat performance test, login as "tomcat" and start tomcat server, it's pid was 8902.
    3. after 12 hours, I relogin to the server but can not found process 8902.
    4.I could not found any hs_err_pid.log and core.pid file under "tomcat" home, and only myself use this machine.
    5. the jvm process have enough privilege for the file read and write.
    So, I lost my road, why the jvm process will disappear and not leave any mark? thank you for help me !

    Roy_Li wrote:
    1.The system is RHEL5.1 and PC is my private machine, not connect to internet or local network.
    2.I was had a tomcat performance test, login as "tomcat" and start tomcat server, it's pid was 8902.I don't know how you start it, but it's possible that your program gets a hangup signal and quits when you logout. You should in that case start it with nohup.
    [http://en.wikipedia.org/wiki/Nohup]
    Kaj

  • Tracking the JVM Process?

    Hi all,
    I need to find the java processes which are hanged in my system and need to kill it by programmatically.
    is it possible to trace the loaded applications in my JVM?? and I need to know which is hanged and which is running normally.
    +(I found that I can list the Java processes in the OS Level and I can able to kill it programmaticaly.+
    but Im not able to find the application which is actually hanged UP in the machine by that approach.
    and approaching by OS Level is not a gud approach too. bcoz my application must be platform independent.)
    So is there any way to approach through JVM and kill the process??
    kindly let me know If u hav any solution.
    Thanks & Regards,
    Selvaprabhu

    OS Level is not a gud approach too. bcoz my application must be platform independent.)
    So is there any way to approach through JVM and kill the process??
    kindly let me know If u hav any solution.http://www.catb.org/~esr/faqs/smart-questions.html#writewell
    How To Ask Questions The Smart Way
    Eric Steven Raymond
    Rick Moen
    Write in clear, grammatical, correctly-spelled language
    We've found by experience that people who are careless and sloppy writers are usually also careless and sloppy at thinking and coding (often enough to bet on, anyway). Answering questions for careless and sloppy thinkers is not rewarding; we'd rather spend our time elsewhere.
    So expressing your question clearly and well is important. If you can't be bothered to do that, we can't be bothered to pay attention. Spend the extra effort to polish your language. It doesn't have to be stiff or formal — in fact, hacker culture values informal, slangy and humorous language used with precision. But it has to be precise; there has to be some indication that you're thinking and paying attention.
    Spell, punctuate, and capitalize correctly. Don't confuse “its” with “it's”, “loose” with “lose”, or “discrete” with “discreet”. Don't TYPE IN ALL CAPS; this is read as shouting and considered rude. (All-smalls is only slightly less annoying, as it's difficult to read. Alan Cox can get away with it, but you can't.)
    More generally, if you write like a semi-literate b o o b you will very likely be ignored. So don't use instant-messaging shortcuts. Spelling "you" as "u" makes you look like a semi-literate b o o b to save two entire keystrokes.

  • What's consuming the app server heap memory?

    Dear all,
    I keep getting the "java.lang.OutOfMemoryError: Java heap space" error in our environment, I tried to remove the BAM from the Jboss, and the error disappear for some times, but it appear again recently, while we only changed one line of script in one of the form. (i.e. I don't think the error is caused by changing code)
    So, I would like to know where can I find some information about how the memory is consumed in ALC? Because we only have 2 workflow running, although one of them is heavily used.
    Here some information about my environment.
    - ALC 8.2.1 with no sp
    - Using the default Jboss as app server
    - Using the default MySQL as Database
    - Only 2 workflow running
      - While 1 of them have around 4 - 8 request pre week
      - And the others will have around 60 - 80 request pre day (i.e. around 490 pre week)
    Here listed some points I think may affect the memory and I want to know for sure:
    1) Number of variable used in long-live process (i.e. More variable = more Memory used)
    2) Number of operation used in long-live process (i.e. More operation = more memory used)
    3) Number of track record of long-live process (i.e. More track record = more memory used)
    4) Long-lived process vs Short-lived process (i.e. Only long-lived process will keep consume memory because short-lived process will only load on call?)
    5) Number of long-lived process still running (i.e. If we send a assign task to notify the user the workflow have been approved, and the user never dismiss it, it will turn out to consume the app server memory because it is still in the running stage)
    6) Old version of the same long-lived process will use memory even no active workflow? (i.e. Because active long-live process will load up into memory?)
    Thanks in advance
    Regards
    Bill

    Did you tried to increase your heap size in jboss server . try this  and i think it will  help you in solving this problem .
    if u want  to know how to increase the heap size:
    go to bath of ur JBoss    "D:\Adobe\Adobe LiveCycle ES2\jboss\bin" as example.
    scond find the Run file and  open it in  Text File
    find a line  which is responsible for   heap size ==>>"set JAVA_HEAP_ARGS=-XX:PermSize=128m -XX:MaxPermSize=192m -Xms1024m -Xmx1024m"
    close it and restart the server again and test your problem.
    put ur line to be like what i wrote 1024 means that 1 giga for heap of jboss.
    if the problem still appear for  you then your Memory doesnot of because memory heap size

  • At what stage of the dps process do i need xcode installed?

    I am working on a mac pro 10.7.5 and i cant install xcode on this machine. However i got a private laptop that runs on maverick.
    I can build a folio on my macpro and view it on my ipad using the adobe viewer.
    So i need to become a developer and install xcode on my laptop.
    Can i create the folio on my macpro and when the folio is finished publish it from the laptop? (from folio producer)

    Martin is correct that you don't need Xcode. You just need Application Loader, which gets installed when you dowload the Xcode SDK. Installing the SDK also takes care of the intermediate certificate required when you're using the Apple iOS developer site to create App iDs and certificates, but you can do that manually as well. Personally, I prefer installing Xcode.
    Application Loader used to work on Mac OS X 10.6, but now it requires 10.7 or later. At some point, Apple might require 10.8 or later, so you're probably better off using your computer running Maverick.

  • Apple:  Please fix the "Other" problem with memory space

    It took me 5 tries last night to get TomTom Installed cleanly on the iPhone. Each of the 4 times I tried - I kept getting gigabytes of memory in the "Other" category. The only way to get rid of the "other" memory is to restore the iphone - a 20 minute process in itself.
    While syncing mostly anything to an iphone or ipod - if you make a change in the middle of a longer sync (for a large file) and push the sync button again - the sync starts over and the large file that it was working on becomes orphaned and part of the "Other" memory. Cancelling Syncs also result in this large portion of "Other" memory being taken up by whatever the sync was working on at the time of the cancellation.

    Ted C wrote:
    It took me 5 tries last night to get TomTom Installed cleanly on the iPhone. Each of the 4 times I tried - I kept getting gigabytes of memory in the "Other" category.
    After it happened the first and second time, with the same results, you really did the same thing two more times? Yikes.
    Ever hear of the term "Idiot proof?"
    Leaving aside obvious directions that could be taken...it may be that 'idiot proof' is not the goal here. Say you have a problem like this, and don't know the solution. Maybe you come here, so some devious helper like me can pad his post counts by answering your question (regardless of the fact that the number of posts means absolutely nothing, and I volunteer my time here in any case). But, maybe you go to the Genius Bar for some 'free' help. See that shiny new iPhone 3GS? That slick looking new MacBook Pro? Maybe you suddenly remember you were thinking of a new car charging cable or BT headset for your phone. Bam. A sale is made. All because the valued customer needed help with an idiot-vulnerable product. Just food for thought. <sarcasm>And one more post to add to my post count. Whoopee. I'm going to go celebrate now.</sarcasm>
    Seriously, though, Apple generally does a good job of making user-friendly products. The iPod will be discussed in marketing classes for the next several decades as the poster child for that approach to product development.

  • Warning Your system is running low on process virtual memory space

    Hi,
    I face this problem when i use a flat file source with about 19000 records (about 6 mb size).
    The job starts there is no error message but it just halts no progress....
    Can anyone help.

    Greetings Narendra,
    It may help if you were to explain in more detail the software product you are encountering this issue. There are about 500 different products that might be encountering this issue. Specifying which product you are using will assist the Forum Team in providing an appropriate response.
    Thank you,
    Rob
    Technical Engineer
    Customer Assurance

  • What would the best process chain look like for this MD data load scenario?

    Hi there,
    I have the following setup. SAP BW connection to external system via DBConnect (DB2 database).
    We have 73 master data text data sources to load either once a week or everyday through process chain. We have not decided on the exact schedule yet.
    All the master data text DataSources pull data from the SAME VIEW created on the DB2 external system:
    VWDEDMASTERDATA
    The structure of the view is the following:
    DEDNAME
    DEDNAMETYPE
    DEDNAMECODE
    DEDNAMEDESC
    DEDNAMELONGDESC
    So, everytime master data text is extracted for all the 73 objects it queries the same view over and over again VWDEDMASTERDATA. We only differentiate in the datasource on the FIELDS tab which InfoObject should DEDNAME map to and then in InfoPackage we filter on the exact object/field to query.
    So essentially, every time we run InfoPackage for master data text object the external system gets queried in the following way:
    SELECT * from VWDEDMASTERDATA where DEDNAME = [FIELD/InfoObject specified in InfoPackage]
    So, if I have to have all 73 objects loaded, essentially the same SQL statement has to execute 73 times. In this scenario, what would be the proper process chain setup that has perfomance in mind? How should the InfoPackages be arranged, in parallel, sequentially, how many in a row, etc?
    Let me know if you need more information.
    thanks

    They would like to send the letters to me
    Depending upon how they send the letters to you and how they expect Acrobat to convert them you could be bordering on a license violation that prohibits you from using your version of Acrobat as a server-based product.
    Adobe offers server based products to convert rtf files into pdf files. Some require your company to run a server, but one seams exactly what they may want. The createpdf service is run by Adobe and seems capable of doing what your company wants.
    https://www.acrobat.com/createpdf/en/home.html

  • Memory leak in the JVM leading to system oom

    Hi,
    We are running application server using java 1.5, tomcat 5.5 ...
    The problem is that the JVM is allocating memory continuously.
    If we look at the JVM memory from JConsole everything is OK the amount of memory allocated in the heap does not grow significantly.
    If we look at the JVM memory consumption from the system perspective, the memory usage is growing until the system runs out of memory and kill the JVM. The JVM memory usage goes beyong 1.5 Go of memory whatever options you use when launching the JVM.
    The memory allocation is so intense that it can lead to a crash in few hours with very few users connected to the application.
    We have tried JDK 1.5.05 and 1.5.06 still the same.
    We are running on a Linux Debian system wth a 2.6.8 kernel.
    Any idea of where all this memory goes ?
    Any idea on how to track and solve this memory leak ?

    Hi Martinux,
    Tiger and Mustang come with a number of diagnosing tools that could help
    you spot memory problems. In particular there's something called 'jmap' which can
    take a snapshot of the JVM memory.
    Danny Coward has recently written a nice blog to emphasize the existence
    of this new tools - see
    "Crash Course: Java SE Monitoring, Management and Troubleshooting"
    http://blogs.sun.com/roller/page/dannycoward?entry=crash_course_java_se_monitoring
    Of course if the problem isn't in the JVM...
    BTW: you did also look at the non-heap memory, right? and also at the total
    number of loaded classes?
    hope this helps,
    -- daniel
    JMX, SNMP, Java, etc...
    http://blogs.sun.com/roller/page/jmxetc

  • What is the right process for moving system to another plant

    Dear Guru,
    I have below scenario which i would like to understand what should be the right process to deal with it..
    Organization Structure.
    Company code: C500
    Business area : 500A
    Plant A500 and S500 which is under the same company code and same Business area.
    Storage location: SW01 and AW01 which are physically same location address
    I have this scenario where the user have a PO under Plant S500 which already GR and IR and the physical goods is currently placed in Storage location SW01.
    But the user realized the Material should be created under Plant A500.
    For the above case, can anyone please advice me what should be the better process instead of reversal the IV/GR/PO? and what is the right process for MM and considering also from the finance point of view?
    Thank you very much,
    Regards,
    CheeWee

    Hi
    It is the configuration issue. SOmetime it happens when you copy the Reference plant to your Plant.
    Change the setting and make it both Qty & Value if you really want to manage the stock qty with value then proceed.
    Valuation area is nothing but a Plant.
    karthik
    Edited by: Karthik on Jul 25, 2011 1:23 PM

  • Solaris JVM Process Growth

    Hi,
    I am investigating a problem where we experience continual growth of our JVM process. The overall process size and native heap size of the JVM process continually grow at the same rate. I am monitoring these using the commands 'ps - o pid,vsz,rss' and 'pmap -x' respectively. The increases are in multiples of 8Kb.
    I have checked our java application using Optimizeit and it is not leaking memory. I have also monitored the size of the VM java heap using the '-verbose:gc' garbage collection debugging option. Garbage collection appears normal and the VM heap size remains below that specified by the '-Xmx' option.
    It appears that the memory growth is occurring in native code of the JVM process but I am at a loss on how to determine what is causing this. Can anyone advise me what may be causing this JVM process growth or ways in which I may be able to find this out?
    I am using JRE 1.4.2 SE (1.4.2_08_b03) on Solaris 8. Within the JVM we are running our web app in Tomcat 4.1.
    The shared libraries loaded by the JVM (as shown by pldd) are:
    /usr/lib/libthread.so.1
    /usr/lib/libdl.so.1
    /usr/lib/libc.so.1
    /usr/platform/sun4u/lib/libc_psr.so.1
    /vob/ntg-thirdparty/java/j2sdk1.4.2_08/jre/lib/sparc/client/libjvm.so
    /usr/lib/libCrun.so.1
    /usr/lib/libsocket.so.1
    /usr/lib/libnsl.so.1
    /usr/lib/libm.so.1
    /usr/lib/libsched.so.1
    /usr/lib/libmp.so.2
    /vob/ntg-thirdparty/java/j2sdk1.4.2_08/jre/lib/sparc/native_threads/libhpi.so
    /vob/ntg-thirdparty/java/j2sdk1.4.2_08/jre/lib/sparc/libverify.so
    /vob/ntg-thirdparty/java/j2sdk1.4.2_08/jre/lib/sparc/libjava.so
    /vob/ntg-thirdparty/java/j2sdk1.4.2_08/jre/lib/sparc/libzip.so
    /vob/ntg-thirdparty/java/j2sdk1.4.2_08/jre/lib/sparc/libjdwp.so
    /vob/ntg-thirdparty/java/j2sdk1.4.2_08/jre/lib/sparc/libdt_socket.so
    /usr/lib/nss_files.so.1
    /vob/ntg-thirdparty/java/j2sdk1.4.2_08/jre/lib/sparc/libnet.so
    /vob/ntg-thirdparty/tibco/rv-7.1/sol28/lib/libtibrvj.so
    /vob/ntg-thirdparty/tibco/rv-7.1/sol28/lib/libtibrvcmq.so
    /vob/ntg-thirdparty/tibco/rv-7.1/sol28/lib/libtibrvcm.so
    /vob/ntg-thirdparty/tibco/rv-7.1/sol28/lib/libtibrvft.so
    /vob/ntg-thirdparty/tibco/rv-7.1/sol28/lib/libtibrv.so
    /usr/lib/libpthread.so.1
    /vob/ntg-thirdparty/java/j2sdk1.4.2_08/jre/lib/sparc/libnio.so
    /usr/lib/librt.so.1
    /usr/lib/libaio.so.1
    /usr/lib/libsendfile.so.1
    /vob/ntg/dev/resources/lib/sol8gcc/libjavaperljni.so
    /vob/ntg/dev/thirdparty/perl-5.8.0-gcc-thread/lib/libperl.so
    /usr/lib/libw.so.1
    /vob/ntg/dev/resources/lib/sol8gcc/libstdc++.so.2.10.0
    /vob/ntg-thirdparty/java/j2sdk1.4.2_08/jre/lib/sparc/libioser12.so
    /vob/ntg-thirdparty/java/j2sdk1.4.2_08/jre/lib/sparc/libawt.so
    /vob/ntg-thirdparty/java/j2sdk1.4.2_08/jre/lib/sparc/libmlib_image.so
    /vob/ntg-thirdparty/java/j2sdk1.4.2_08/jre/lib/sparc/headless/libmawt.so
    /vob/ntg-thirdparty/java/j2sdk1.4.2_08/jre/lib/sparc/libcmm.so
    /vob/ntg-thirdparty/java/j2sdk1.4.2_08/jre/lib/sparc/libfontmanager.so
    /vob/ntg-thirdparty/java/j2sdk1.4.2_08/jre/lib/sparc/libdcpr.so
    /vob/ntg-thirdparty/java/j2sdk1.4.2_08/jre/lib/sparc/libjpeg.so
    Any Help is much appreciated.

    Hi
    If u can, use 1.4.2_10 (latest as of now). There is a bug 6250517, fixed in _09. Not sure if u r making any calls to NetworkInterface.getNetworkInterfaces.
    Also noticed that you are using tibco. How about putting -Xcheck:jni and see if it picks up anything.
    Unfortunately Solaris 8 didnt have libumem for tracking memory allocation. If u have any Solaris 9/10 boxes, you can use libumem to track it down.
    http://access1.sun.com/techarticles/libumem.html

  • How can I reduce the size of the jvm?

    I would like to decrease the size of a jvm; I've found a program that makes it, but you don't know how does it works (and you have to pay for it), I'm talking about VM Optimizer 2.0, from Invirtus.
    Can anyone tell me how can I reduce the size of the jvm?
    Thanks a lot.

    I assume you mean the size of a JVM instance in memory and not the size of the JRE which is on the disk.
    I don't believe that there is any way at present for your Java code to change the amount of memory available to the JVM. This shouldn't matter too much, though. Firstly, you can control the size of the JVM from the command prompt with the -Xms and -Xmx options. Secondly, any remotely reasonable operating system is going to wait until the JVM has requested memory before allocating all of it. If you start a JVM with a 2Gb heap, it does not occupy 2Gb of physical memory straight away.
    Finally, I did a Google on InVirtus VM Optimizer and must request some information. What does that software have to do with Java? It's designed to reduce the size of a virtual computer as created by a prorgam such as VMWare. It has nothing to do with the Java virtual machine.

  • Capturing stdout from JVM process

    Hi,
    Using JNI native methods I call functions in a shared C library from my Java program. I do not have access to the shared library source code. The shared library writes informational messages to stdout. I want to be able to capture these messages and display them in my Java GUI as they occur. I need a cross-platform solution because the Java program needs to run on both Windows and Linux.
    I have googled and searched the JavaSoft forums but I cannot find an answer to what I am trying to do. I have seen answers on how to do it if you are using Runtime.exec methods, but I am not doing that. Also, redirection on the command line will not work since I want to show these messages as they occur in my GUI.
    I have thought of redirecting stdout to a pipe in the JNI code and using select to read the bytes off the pipe. Then sending the bytes up to a Java object. All this would run in a separate thread. But this seems overly complicated.
    Any suggestions?
    charlie

    I developed a solution to this problem using named pipes. It works well on Linux (2.6 kernel) and it may work on Windows but I don't know. Example code follows. I would be most interested in any feedback on this solution or on the code itself.
    There are 2 files, StdoutRedirect.java and StdoutRedirect.c.
    1) Compile the java file and run javah on it to get StdoutRedirect.h.
    2) Compile the C file into a shared library, here's a makefile:
    StdoutRedirect: StdoutRedirect.o
    gcc -shared -o libStdoutRedirect.so StdoutRedirect.o
    3) Run the java class file.
    charlie
    **** StdoutRedirect.java ****
    import java.io.FileNotFoundException;
    import java.io.IOException;
    * This class, along with its JNI library, demonstrates a method of redirecting stdout of the JVM process to a Java
    * Reader thread. Using this method the stdout bytes can be sent anywhere in the Java program; e.g., displayed in a GUI.
    * This has only been tested on a Linux 2.6 kernel.
    public class StdoutRedirect {
        static {
            System.loadLibrary("StdoutRedirect");
        final static public String NAMED_PIPE = "/tmp/stdoutRedirect";
        native private void setupNamedPipe();
        native private void redirectStdout();
        native public void someRoutine();
        // Flag to indicate to Reader thread when to terminate
        protected boolean keepReading = true;
        public static void main(String[] args) throws IOException {
            StdoutRedirect redir = new StdoutRedirect();
            redir.setupNamedPipe();
            // The first reader or writer to connect to the named pipe will block. So, the reader
            // must be opened first and must be in a new thread. We want it to be in a separate
            // thread anyways so we can receive data asynchronously.
            redir.openReader();
            // At this point, the reader thread is blocked on creating the FileInputStream
            // because it is the first thing to connect to the named pipe. We grab the lock
            // here and redirect stdout to the named pipe. This opens a writer on the named
            // pipe and the reader thread will unblock. We want to wait for the reader thread
            // to unblock and be ready to receive data before continuing.
            synchronized (redir) {
                redir.redirectStdout();
                try {
                    // wait for the reader thread to be ready to receive data
                    redir.wait();
                } catch (InterruptedException e) {
            // write some data to stdout in our C routine
            redir.someRoutine();
            // All done now, so indicate this with our flag
            redir.keepReading = false;
            // The reader thread may be blocked waiting for something to read and not see
            // the flag. So, wake it up.
            System.out.println("Shut down");
            // Make sure everything is out of stdout and then close it.
            System.out.flush();
            System.out.close();
            // stdout is closed. This will not be visible.
            System.out.println("Won't see this.");
         * Starts the reader thread which listens to the named pipe and spits the data
         * it receives out to stderr.
        private void openReader() {
            new Thread() {
                public void run() {
                    try {
                        int BUFF_SIZE = 256;
                        byte[] bytes = new byte[BUFF_SIZE];
                        int numRead = 0;
                        // At this point there is no writer connected to the named pipe so this statement
                        // will block until there is.
                        FileInputStream fis = new FileInputStream(NAMED_PIPE);
                        // The reader thread is ready to accept data. Notify the main thread.
                        synchronized (StdoutRedirect.this) {
                            StdoutRedirect.this.notify();
                        // Keep reading data until EOF or we're told to quit and there is no more data to read
                        while (numRead != -1 && (StdoutRedirect.this.keepReading || fis.available() != 0)) {
                            numRead = fis.read(bytes, 0, BUFF_SIZE);
                            System.err.print("Received - " + new String(bytes, 0, numRead));
                        if (fis != null) {
                            fis.close();
                        System.err.println("Receiver shut down");
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
            }.start();
    } // class StdoutRedirect**** StdoutRedirect.c ****
    #include "StdoutRedirect.h"
    #include <sys/types.h>
    #include <sys/stat.h>
    #include <stdio.h>
    #include <fcntl.h>
    #include <string.h>
    #include <errno.h>
    // The filesystem location for the named pipe
    const char *namedPipe = "/tmp/stdoutRedirect";
    * Create the named pipe we're going to redirect stdout through. After this
    * method completes, the pipe will exist but nothing will be connected to it.
    JNIEXPORT void JNICALL Java_StdoutRedirect_setupNamedPipe(JNIEnv *env, jobject obj) {
      // make sure there is no pre-existing file in our way
      remove(namedPipe);
      // create the named pipe for reading and writing
      mkfifo(namedPipe, S_IRWXU);
    * Redirect stdout to our named pipe. After this method completes, stdout
    * and the named pipe will be identical.
    JNIEXPORT void JNICALL Java_StdoutRedirect_redirectStdout(JNIEnv *env, jobject obj) {
      // Open the write end of the named pipe
      int  namedPipeFD = open(namedPipe, O_WRONLY);
      printf("Before redirection...\n");
      // make sure there is nothing left in stdout
      fflush(stdout);
      // duplicate stdout onto our named pipe
      if ( dup2(namedPipeFD, fileno(stdout)) == -1 ) {
        fprintf(stderr, "errno %s.\n", strerror(errno));
        fprintf(stderr, "Couldn't dup stdout\n");
      printf("After redirection.\n");
      // flushing is necessary, otherwise output does not stay in sync with Java layer
      fflush(stdout);
    * Do some random writing to stdout.
    JNIEXPORT void JNICALL Java_StdoutRedirect_someRoutine(JNIEnv *env, jobject obj) {
      int i;
      for ( i = 0; i < 3; i++ ) {
        printf("Message %d\n", i);
      printf("End of messages\n");
      // flushing is necessary, otherwise output does not stay in sync with Java layer
      fflush(stdout);
    }

Maybe you are looking for