Question about java thread implementation

Hi All,
I am comparing the performance of the Dining philosopher's problem
implemented in Java, Ada, C/Pthread, and the experimental language I
have been working on.
The algorithm is very simple: let a butler to restrict entry to the
eating table, so that deadlock is prevented.
It turns out that the java code is the winner and it is 2 times faster than C!
The comparison result really surprised me, and raised a big
question mark : why java runs so fast? I did not use high-level synchronization
constructs like Semaphores, atomic variables, etc.
I vaguely recall that Java thread is actually implemented by the underlying
system thread library(so on linux, the default would be NPTL, on windows NT threads,
and on Mac OSX it would be Cthread?). Can no longer remember where I read that.
Does anyone here have some notions about the Java thread
implementations(where is this formally explained)? or Does anyone know where
I can possibly find relevant literature or the answer?
thanks a lot.
cheers,
Tony

Peter__Lawrey wrote:
google has lots of information on java threaded.
One thing java does is support biased locking. i.e. the thread which last locked an object can lock that object again faster.
This may explain the difference. [http://www.google.co.uk/search?q=java+usebiasedlocking]
Note: you can turn this option off and other locking options to see if a feature is giving you the performance advantage.
Personally I have found that real world multi-threaded applications are easier to write in Java, esp. when you have a team of developers. For this reason, alot of C/C++ libraries are single threaded, even when there would be a performance advantage in being multi-threaded (because its just too hard in reality to make it thread safe and faster because of it)I didn't know that, very interesting :-)

Similar Messages

  • Question about java threads programming

    Hi
    I have to develop a program where I need to access data from database, but I need to it using multithreading, currently I go sequentially to each database to access data which is slow
    I have a Vector called systemnames, this one has list of all the systems I need to access.
    Here is my current code, some thing like this
    Vector masterVector = new Vector();
    GetData data = new GetData();
    For(int i =0; i < systemnames.size(); i++)
    masterVector.add(data.getData((String)systemnames.get(i));
    public class GetData
    private Vector getData(String ipaddress)
    //process SQL here
    return data;
    how do i convert this to multithread application, so there will be one thread running for each system in vector, this is speed up the process of extracting data and displaying it
    has any one done this kind of program, what are the precautions i need to take care of
    Ashish

    http://www.google.com/search?q=java+threads+tutorial&sourceid=opera&num=0&ie=utf-8&oe=utf-8
    http://java.sun.com/docs/books/tutorial/essential/threads/
    http://www.javaworld.com/javaworld/jw-04-1996/jw-04-threads.html
    http://www.cs.clemson.edu/~cs428/resources/java/tutorial/JTThreads.html
    http://www-106.ibm.com/developerworks/edu/j-dw-javathread-i.html
    When you post code, please use [code] and [/code] tags as described in Formatting Help on the message entry page. It makes it much easier to read and prevents accidental markup from array indices like [i].

  • Question About Java Threads and Blocking

    I'm helping someone rehost a tool from the PC to the Sun. We're using the Netbeans IDE and the Java programming language. I took a Java course several years ago, but need some help with something now. We're developing a front-end GUI using Swing to allow users to select different options to perform their tasks. I have a general question that will apply to all cases where we run an external process from the GUI. We have a "CommandProcessor" class that will call an external process using the "ProcessBuilder" class. I'm including the snippet of code below where this happens. We pass in a string which is the command we want to run. We also instantiate a class called "StreamGobbler" my coworker got off the Internet for redirecting I/O to a message window. I'm also including the "StreamGobbler" class below for reference. Here's the "CommandProcessor" class:
    // Test ProcessBuilder
    public class CommandProcessor {
    public static void Run(String[] cmd) throws Exception {
    System.out.println("inside CommandProcessor.Run function...");
    Process p = new ProcessBuilder(cmd).start();
    StreamGobbler s1 = new StreamGobbler("stdin", p.getInputStream());
    StreamGobbler s2 = new StreamGobbler("stderr", p.getErrorStream());
    s1.start();
    s2.start();
    //p.waitFor();
    System.out.println("Process Returned");
    Here's the "StreamGobbler" class:
    import java.lang.*;
    import java.io.*;
    // Attempt to make the output of the process go to the message window
    // as it is produced rather that waiting for the process to finish
    public class StreamGobbler implements Runnable {
    String name;
    InputStream is;
    Thread thread;
    public StreamGobbler (String name, InputStream is){
    this.name = name;
    this.is = is;
    public void start(){
    thread = new Thread (this);
    thread.start();
    public void run(){
    try{
    InputStreamReader isr = new InputStreamReader(is);
    BufferedReader br = new BufferedReader(isr);
    while (true){
    String s = br.readLine();
    if (s == null) break;
    System.out.println(s);
    //messageWindow.writeToMessageArea("[" + name + "]" + s);
    is.close();
    catch(Exception ex){
    System.out.println("Problem reading stream" + name + "...:" + ex);
    ex.printStackTrace();
    The "CommandProcessor" class calls two (2) instances of the "StreamGobbler" class, one for "stdin" and one for "stderr". My coworker discovered these are the 2 I/O descriptors that are needed for the external command we're running in this case. We're actually called the Concurrent Versions System (cvs) command from the GUI. Here's what we need it to do:
    We want to display the output real-time as the external process is executing, but we want to block any actions being performed on the GUI itself until the process finishes. In other words, we want to show the user any generated output from the process, but don't want to alllow them to perform any other actions on the GUI until this process has finished. If we use the "waitFor()" function associated with a process, it blocks all external process output until the process has completed and then spews all the output to the screen all at once. That's NOT what we want. Also, if we don't use the "waitFor()" function, the code just continues on as it should, but we don't know how to block any actions on the GUI until this process has finished. My coworker tried the following code, but it also blocked any output until the process had finished:
    while (s1.thread.isAlive() || s2.thread.isAlive())
    // We really don't do anything here
    I'm pretty sure we have to use threads for the output, but how do we instantly show all output and block any GUI actions?
    Thank you in advance for your help!

    You're talking about a GUI, but there's nothing in that code which is putting events into the GUI update thread. You also say that nothing happens to the GUI until the CommandProcessor.Run() method returns if you wait for the process.
    This implies that you're calling CommandProcessor.Run() in an ActionListener. This will block the GUI thread until it completes.
    I was going to explain what to do, but a quick Google informed me that there's a new class which is designed to help in these situations SwingWorker (or as a [separate library|https://swingworker.dev.java.net/] if you're not up-to-date yet).

  • Question about Java's HttpServer: Threading? Backlog?

    Hello,
    I have two questions about Java's HttpServer (com.sun.net.httpserver). From the JavaDoc:
    >
    Management of threads can be done external to this object by providing a Executor object. If none is provided a default implementation is used.
    >
    How can I get information about the default implementation in 1.6.0_13? Do you know the behavior? From my observations, the default implementation uses no Threads, meaning every request is handled in the same Thread, this results in handling the requests to the HttpServer one after another.
    Is this right?
    The second question is about this, also from the JavaDoc:
    >
    When binding to an address and port number, the application can also specify an integer backlog parameter. This represents the maximum number of incoming TCP connections which the system will queue internally. [...]
    >
    When setting the backlog to -1, it uses the systems default backlog. How can I determine the systems default backlog? Can some lines of Java code reveal it (there is no getBeacklog() method)? Or is it up to the Operating System (we use Redhat Linux)?
    Thanks a lot for your help!
    Regards,
    Timo

    How can I determine the systems default backlog?You can't. There is no API for that even at the C level.
    Can some lines of Java code reveal itNo.
    Or is it up to the Operating System (we use Redhat Linux)?Yes. Linux provides a large default. It seems to be at least 50 on most platforms. This is not something you should be worrying about.

  • Three questions about Java and Ftp

    Hello, i've the following questions about Java and Ftp:
    1- .netrc file is in $HOME directory but i can't access to this directory from java code. The following line producesan Exception (directory doesn't exists)
    FileWriter file = new FileWriter ("$HOME/.netrc");
    2- .netrc file must have the following permissions: -rw- --- --- but when i create the .netrc file the following permissions are on default: -rw- r-- r--, how can i change this permissions? (In java code, i can't use chmod.....)
    3- Are there any way to pass parameters to a .netrc file? If i get to do this i needn't change the permissions because i can't modify or create/destroy this file.
    Thanks in advanced!!!
    Kike

    1- .netrc file is in $HOME directory but i can't
    access to this directory from java code. The
    following line producesan Exception (directory
    doesn't exists)
    FileWriter file = new FileWriter ("$HOME/.netrc");$HOME would have to be replaced by a shell, I don't
    think you can use it as part of a legal path.
    Instead, use System.getProperty("user.home");
    Ok, thanks
    2- .netrc file must have the followingpermissions:
    -rw- --- --- but when i create the .netrc file the
    following permissions are on default: -rw- r--r--,
    how can i change this permissions? (In java code,i
    can't use chmod.....)Yes, you can: Runtime.exec("chmod ...");
    I need to use estrictly the .netrc with -rw- --- --- permissions
    Yes, i can use Runtime.exec ("chmod ..."); but i don't like very much this solution because is a slow solution, am i right?
    3- Are there any way to pass parameters to a.netrc
    file? If i get to do this i needn't change the
    permissions because i can't modify orcreate/destroy
    this file.I don't think so. Why do you need the .netrc file in
    Java at all? Writing a GUI frontend?I want to use automatic ftp in a java program and FTP server, the files and path are not always the same, so i can:
    - modify .netrc (for me is the complex option)
    - destroy and create a new .netrc (is easier but i have permissions problem)
    - use .netrc with parameters but i haven't found any help about it
    Thanks for your prompt reply!!!!
    Kike

  • Question about Java implementation in Linux platform

    Hello,
    I shall implement one Java program in Linux platform. I'm a newer to linux. Need I install some special software in Linux platform to compile and run JAVA program?
    Thank you in advance
    java_linux

    Sorry, this forum is about Sun Studio, which is a collection of native compilers and tools. About Java, please use Java forum; for example, one of these: http://forums.sun.com/category.jspa?categoryID=5

  • Question about Java apps structure

    Hello guys,
    I'm a professional C++ programmer and I would like to start learning Java. I'm reading about Java from here and there and would like to ask you about how a java program is structured compared to C++.
    So in C++, I have main.cpp (or any other file name, doesn't matter), which contains a the main() function, and I have .h and .cpp class files that I instantiate (basically) in my main function to get my program to work.
    In Java, I'm confused and can't really find the "general" rule to how stuff are organised. I noticed that every class has a main function (why?), and there's no global scope. And "somehow", file names must exactly be equal to the class names.
    The question is: how are Java files of classes (and other stuff, if available) are arranged to create a program? What's the standard why? And How can I have many classes together in a single main()?
    Thank you for any efforts :-)
    Edited by: 927494 on 13.04.2012 07:02
    Edited by: 927494 on 13.04.2012 09:10

    Thank you guys for the replies. I still have some more doubts :-)
    Do I have to have a file for the implementation and a file for the definitons, like cpp and header files? or just everything inside the class?
    Why does Netbeans fail to compile when I change the class name? what should I change with the class name in general to have it compile correctly? From what I understand till now, the top level class's name (the class with the main() function that's gonna be executed) has to be equal to the file name (and I got that this is the sufficient condition for the app to compile), while the same file can have more classes if I wish. Did I get that right?
    I don't know if I get that right too, we pass only a SINGLE class/file to the compiler, and it automatically resolves ALLLL the included files automatically, unlike C++, where all cpp files have to be passed to the compiler/makefile to create object files, and then the executable is created after linking all those object files with the libraries together. i.e.: Java doesn't really need a makefile because making is really simple with only 1 filename. True?

  • Questions about Java Servlets and JSP

    Hi,
    I'm a confident Java Programmer (and really enjoy using this language) but am very new to Java servlets and Java Server Pages.
    I have previously worked with Perl on my web projects (simple 'league' style voting pages). I read in my 'Core Java' book that I should no longer use perl or even cgi.
    I need to know more about Java servlets and Java Server Pages so I can make the switch to a 'real' programming language.
    I have a few questions:
    How should I start to learn JS and JSP?
    How applicable will the java knowlegdge I have already be?
    Are JSP common on the world wide web?
    What tools do I need to start? (I currently develop in JBuilder and have Java 1.4.1 Standard Edition)
    Is it likey my web host (and others) will support JSP?
    Thank-you very much for helping a novice get started,
    Regards,
    Paul

    Hi, Steve ...has to be frustrating! But do not despair.
    Let's suppose the servlet it's named MyServlet on package org.servlets
    WEB-INF should look:
    WEB-INF
    classes
    org
    servlets
    MyServlet.class
    web.xml
    web.xml file should have this two declarations:
    <web-app>
      <servlet>
        <servlet-name>MyServlet</servlet-name>
        <servlet-class>org.servlets.MyServlet</servlet-class>
      </servlet>
      <!-- other servlets -->
      <servlet-mapping>
        <servlet-name>MyServlet</servlet-name>
        <url-pattern>/MyServlet</url-pattern>
      </servlet-mapping>
      <!-- other servlets mappings -->
    </web-app>Now, once the container starts (Tomcat?), you should be able to see that servlet in:
    http://localhost:8080/[my-context/]MyServletAnd what my-context is? The web application context. This string should be empty if your're deploying to the root context, otherwise should the context name. In Tomcat, deploying to root context defaults to using webapps/ROOT.
    Sorry for my English, but I felt the need to answer your request. I hope it helps despite my writing.

  • Question about Java Errors

    I have some questions about some java errors
    1. what kind of errors are contained in Error class?
    2.does this class contain only runtime errors?
    3. if the question number 2 is positive, what about InstantiationError which is a compile error and is a subclass of Error.
    4.When our program is out of memory, which processes are done for an error to be produced. is the error actually from OS or VM?

    I have some questions about some java errors
    1. what kind of errors are contained in Error class?An Error is a subclass of Throwable that indicates serious problems that a reasonable application should not try to catch.
    2.does this class contain only runtime errors?No
    3. if the question number 2 is positive, what about
    InstantiationError which is a compile error and is a
    subclass of Error.
    4.When our program is out of memory, which processes
    are done for an error to be produced. is the error
    actually from OS or VM?Various - both, depending on where the error occurred.

  • Question about java-based server app frameworks

    Hello, I am working on a Java applet application and would like to choose a Java-based scalable server framework to use within my applcation. I have found a few like xsocket or QuickServer and have a question about other. And, also, which is the one You may advise? Yours sincerely, Slawek

    For online gaming server. I first heard of xsocket and started using this, but have the problem with NAT. I now know that I need to initiate connections from client behind NAT (server has a public IP) and send messages from server to client within the same connection. I am doing this the following way (as shown in examples- below), but it appears that server receives messages, but client doesnt. I dont listen on any ports in client application and just need to take advantage of the connection initiated (information go from client to server properly).
    Server-
    try{ nbc = pool.getNonBlockingConnection(inetAddress, 8090);
    try{ nbc.write("|01|______|02|______|03|______|04|______|05|______|06|______|07|______|08|______|09|______|10|______"); }catch(Exception ee){}
    }catch(java.io.IOException f){}
    Client-
    public boolean onData(INonBlockingConnection nbc) throws IOException,ClosedChannelException,BufferUnderflowException,MaxReadSizeExceededException{
    String x = nbc.readStringByLength(100);
    System.out.println("S >> C = "+x);

  • Some questions about Java deployment steps and techniques

    All my java experience is coding and testing in my local machine (where, of course, a jre is available), but ... when I deploy to other people, they may not have a jre or they may have a different version of it than the one needed to run my application. I've read different stuff online including jars and java web start but still I have many questions.
    (1) first one first, Sun contradicts common sense, when it says that i can redistribute my own customized light version of their jre by taking out some files (java.sun.com/j2se/1.5.0/jre/README). there are two ways for me to get a jre: Way one is by downloading one from Sun, the download comes as an *.exe file and I don't see how I can take files out of it, so do you know how?. Way two would be by simply copying the set of files i choose (according to that Readme) from my current jre installation (the one on my \java\jdk\jre directory), does this make sense?, (if you're under windows) doesn't an installed version of a jre need a couple of dlls plus some new registry entries?, this contradicts common sense, if I'm not wrong, that Readme is a nonsense, but since that readme is at each of us jre installation \java\jdk1.x\jre\Readme, it can't be a nonsense, therefore I'm wrong, therefore the answer is either Way 1 or Way 2, HOW? ... or maybe there's a Way 3?
    (2) Say I never read that Readme so I download the jre (as an exe) to bundle it along with my application in a jar ... now I'll give my neighbor either a jar with two exes or two exes jars ... is there a way to make a jar so that two files get executed? ... if the answer is No and I have competition from a second neighbor, then I believe I'm asking my first neighbor to choose my application based on our friendship, that's not reasonable if we are doing business, so Java loses.
    (3) Say that my application is a single executable file like this,
    class X{
    public static void main(String[]$$$){
    System.out.println("Console, where are you?");
    At this point, say that my neighbor accepted the two executables, he executed the jre.exe and has jre6 in his system, now he double clicks on my X.jar ... it's a console application and jar files are not associated with the java.exe launcher since java 5, but with javaw which doesn't open any console ... how do i make it so a console opens and prints "Console, where are you?" ... do I ask my neighbor-customer to add a couple of lines to his path and open his console and (please) enter java -jar jarfile.jar? ... isn't it too much? ... i hope i'm wrong cause this is kind of discouraging
    (4) I've read that by installing a more recent version of a jre on a system that has an older jre (there to help other applications work), I might be causing a problem for the other applications to run ... I guess that's the reason why that Readme kind of encourage to redistribute a "private" version of a jre (one that doesn't come with a java.exe launcher ... any feedback on this?
    (5) I'm reading a lot of hype about Java Web Start ... it looks better than the traditional jar/jre deployment ... but setting up a MIME type to *.jnlp, it doesn't come with some free hosting I've checked ... somebody can recommend a free hosting service that allows to set a *.jnlp MIME? (I'll appreciate a suggestion here, cause I would like to test Web Start)... and, anyhow, how you people compare it with the paradigm of the single executable file?.
    Thanks. Your feedback is highly appreciated.

    jorgelbanda wrote:
    ..(5) I'm reading a lot of hype about Java Web Start ... It's gratifying to think that someone who wants to deploy apps., has the common sense to search first! You would not guess how I often I hear "I wanna' make an EXE" shortly followed by "What's webstart?".
    ...it looks better than the traditional jar/jre deployment ... but setting up a MIME type to .jnlp, it doesn't come with some free hosting I've checked ... OK. You cannot define new mime types, but perhaps the site already has it defined. An easy way to check is to upload 'any old file' that ends in .jnlp and use the [mime type checker|http://pscode.org/mime/] to see what content type it is served as.
    ..somebody can recommend a free hosting service that allows to set a .jnlp MIME? (I'll appreciate a suggestion here, cause I would like to test Web Start)... I'm pretty sure the Google based sites offer it.
    Note that I edited the asterisks out of your post, to avoid the forum software parsing half the reply as bold.

  • Help needed about Java Threads ?

    Hi,
    I have a p2p java program that contains many classes, A.java, B.java, etc. It works fine when i send or recieve to eachother one at a time, but I would like to be able to send/recieve things at the same time. So i would probably need to use Java Threads. Can somebody please show me how this is done. I would really appriciate it. Thanks!!
    import java.net.*;
    import java.io.*;
    import java.lang.*;
    public class A {
            private static String hostname; //host name
            public A () { }
           public static void send() throws IOException {
                    //send code here
            public static void receive() throws IOException{               
                    //receive code here
            public static void main(String args[]) throws IOException {
                    //do both send/recieve at the same time?
                    send();
                    receieve();
    }

    Well, I think( this is comming out my rear ) that the scope of the recieve() call is not in the main method anymore but instead in class you've created with "new Thread()" and it's throwing from the public void run() instead. This is a good example of complicated code. I would do this:
    (Untested code)
    import java.net.*;
    import java.io.*;
    import java.lang.*;
    public class A implements Runnable { // <--- NEW
            private static String hostname; //host name
            public A () { }
            public static void send() throws IOException {
                    //send code here
            public static void receive() throws IOException{               
                    //receive code here
            public static void main(String args[]) throws IOException {
                    //do both send/recieve at the same time?
                    new Thread( this ).start();
                    send();
            /******** NEW ************/
            public void run()
                while( keepListening )
                    // It's the assumption that recieve() is
                    // throwing the IOException from some net calls
                    try {
                       recieve();
                    } catch( IOException ioe ) {
                       System.out.println( "IOException in run()\n" + ioe.getMessage();
    }

  • Some general questions about multi-threading

    Hey Everybody,
    I have a dilemma with a multi-threaded program that I have written.
    Well to be truthful I actually wrote the program with no consideration whatsoever for multithreading.
    As a result of this complete lack of concern I get a completely hung user interface.
    My program performs a lot of network communications over URL��s and also writes information from URL��s to disk. The combination of networking and I/O in my program and the fact that I have not built multi-threading into the program has lead to complete failure of the user interface. When I say complete failure I mean complete failure. If it were only button��s not responding then I wouldn��t be all that worried, however the entire drawing area of my programs ��Frame�� completely freezes. It��s cool if nothing is maximized or minimized over the frame but as soon as this happens my programs drawing area has a ��serious hang over!��.
    I have begun learning about threads, in principle they sound wicked however in practice they have proven to be a brain tease (oops �K.. honesty).
    The difficulty of threads should not be all that daunting to me, however I have a couple of very simple questions that I would love to have answered�K..anybody out there!!!!!!!!!
    This is the normal basic method of running a thread that I have been attempting to incorporate into my program:
    1). Extend the thread class,
    2). Override the run() method in the subclass (created from step 1),
    3). Create an instance of the subclass,
    4). Call the start() method on the instance (from step 3).
    I have read that every statement the thread will execute is contained within it��s run() method.
    Question 1). This being the case is it possible to have member variables or methods inside a class that extends thread? Please explain!
    Question 2). Can a class that extends thread contain a constructor? Please explain!
    Question 3). If a subclass of thread cannot contain a constructor as I assume to be the case then how can code executing within the newly spawned thread reference information from the object that spawned it?
    If anybody out there on the great net can answer even half of one of these questions I will be more than grateful. Thanks for your time, and rock on Java!
    David

    Thread t = new Thread(MyRunnableDerivedClass);
    t.start();I hope it is understood that MyRunnableDerivedClass is actually an object of the MyRunnableDerivedClass. sorry for the confusion.
    so here's a thread that reads from a file using constructors, member variables, other funcs. It's not optimal but shows use of all of the above. I just typed this in so there are probably syntax errors, but you should get the point.
    public class ThreadedFileReader implements Runnable
        private File m_File;
        byte[] contents = new byte[0];
        public ThreadedFileReader( File f )
           m_File = f;
        public void run()
            BufferedInputStream bis = null;
            try
                bis = new BufferedInputStream( new FileInputStream( m_File ));
                int avail = bis.available();
                while (avail > 0)
                    int oldLen = contents.length();
                    contents = expand( contents, avail );
                    bis.read( contents, oldLen, avail );
                    avail = bis.available();
            catch (Exception e)
            { //do something witty
            finally
                try{ if (bis != null) bis.close(); } catch (Exception e){}
       private byte[] expand( byte[] oldBuf, int addedLen )
          byte[] newBuf = new char[oldBuf.length + addedLen];
          System.arrayCopy( newBuf, 0, oldBuf, 0, oldBuf.length );
          return newBuf;
       public byte[] getContents()
           return contents;
    //here's where we use it
    File f = new File( "c:\myfile" );
    ThreadedFileReader tfr = new ThreadedFileReader( f );
    Thread t = new Thread( tfr );
    t.start();
    t.join();
    // At this point the thread has died, but the thread object still exists
    byte [] data = tfr.getContents();

  • Question about Java vm interprocess communication.

    I was doing an interprocess communication test for fun recently and bump into a questions. My intention is to start two separate Java virtual machines in two separate processes and have them do some simple interaction. This should be done without socket programming. I can do it with sockets but is this test I just want to test how can and if it is possible to do IO between java vm without sockets (or RMI, or MPI or whatever). Just process IOstreams.
    While most documentation says that Java ProcessBuilder is meant to start an external process, I want to start a java vm process and do some IO with another java vm. Most examples demonstrate how to start a command shell or an external non-java program from Java, and say how to avoid the pitfall of IO streams and do it in separate threads. I can do that with Microsoft vbscript and have it talk to Java vm. That is easy. I have created an easy one to start Microsoft Voice to read something while Java is busy with number crunching.
    So I thought it should be easy for multiple Java virtual machines, too. It turns out, I am wrong. I post the test codes below. The Java experts in the forum, please review and give your expert thoughts. The code is ugly, I have to say.
    import java.io.*;
    import java.util.concurrent.*;
    class write_q implements Runnable {
    private LinkedBlockingQueue<String> out_q=null;
    private Process vm=null;
    public write_q(Process p){
    out_q=new LinkedBlockingQueue<String>(64);
    vm=p;
    public void write(String m){
    try {
    if (m !=null) out_q.put(m);
    catch(InterruptedException e){}
    return;
    public void run(){
    OutputStream o=vm.getOutputStream();
    try {
         String vv=out_q.take();
         //System.out.println(vv);
         byte[] b=vv.getBytes();
         o.write(b);
         o.flush();
         //System.out.println(vv);
         Thread.sleep(100);
    catch(IOException e1){
         System.out.println(e1.getMessage());
    catch(InterruptedException e2){
         System.out.println(e2.getMessage());
    return;
    class read_q implements Runnable {
    private LinkedBlockingQueue<String> in_q=null;
    private Process vm=null;
    public read_q(Process p){
    vm=p;
    in_q=new LinkedBlockingQueue<String>(64);
    public String read(){
    String v=null;
    try {
         v=in_q.take();
    catch(InterruptedException e){}
    return v;
    public void run(){
    byte[] b=new byte[256];
    InputStream ins=vm.getInputStream();
    try {
    while(true){
         int s=ins.read(b);
         if (s>0){
              String t=new String(b, 0, s).trim();
              in_q.put(t);
         //System.out.println("Read: "+t);
              if(t.equals("<>")) break;
         Thread.sleep(100);
    catch(IOException e){}
    catch(InterruptedException e3){}
    // end of class read_q
    public class morep{
    private static ExecutorService es=null;
    public morep(){
    es=Executors.newFixedThreadPool(2);
    public String read(){
    String v=null;
    return v;
    public void write(String msg){
    String v=this.read();
    return;
    public static void main(String[] args){
    ProcessBuilder pb=new ProcessBuilder("java", args[0]);
    pb.redirectErrorStream(true);
    pb.directory(new File(".//"));
    Process vm=null;
    morep mp=null;
    read_q reader=null;
    write_q writer=null;
    try {
         vm=pb.start();
         mp=new morep();
         writer=new write_q(vm);
         reader=new read_q(vm);
         es.execute(reader);
         es.execute(writer);
         System.out.println(reader.read());
         writer.write("Hello");
         System.out.println("Read: "+reader.read());
         writer.write("<>");
         System.out.println(reader.read());
         vm.waitFor();
         es.shutdown();
    catch(IOException e1){
         System.out.println(e1.getMessage());
    catch(InterruptedException e2){
         System.out.println(e2.getMessage());
    System.out.print("Press any key....");
    try {
         while(System.in.read()==-1);
    catch(IOException e3){}
    // end of main(String[] args)
    // end of class morep
    // this is the one started by morep.java
    import java.io.*;
    class talker {
    public static void main(String[] args){
    System.out.println("Ok, let\'s talk.");
    System.out.println("Since I am very talkative, be aware of the nuances.");
    System.out.println("Since I am not a bad guy, be aware of the nonscense.");
    BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
    try {
    while(true){
         String x=br.readLine();
         if (x!=null) {
              System.out.println("+++ "+x);
              if (x.equals("<>")) break;
    catch(IOException e1){
         System.out.println("+++ "+e1.getMessage());
    // end of main(String[] args)
    // end of class talker
    Compiling the files will generate morep.class, talker.class, write_q.class and read_q.class. Then the talker.class will be started by morep.class, and managed by read_q.class and write_q.class.
    Run from the command line in Windows, the program hangs after initial messages. In Task Manager, two VMs are started by the program dead locked. I was expecting both VMs close down upon receiving "<>".
    C:\myjava\loader>java morep talker
    Ok, let's talk.
    Since I am very talkative, be aware of the nuances.
    Since I am not a bad guy, be aware of the nonscense.
    Hello
    Edited by: EJP on 13/04/2011 10:44: added code tags. Please use them.

    import java.io.*;
    import java.util.concurrent.*;
    class write_q implements Runnable {
    private LinkedBlockingQueue<String> out_q=null;
    private Process vm=null;
    public write_q(Process p){
    out_q=new LinkedBlockingQueue<String>(64);
    vm=p;
    public void write(String m){
    try {
    if (m !=null) out_q.put(m);
    catch(InterruptedException e){}
    return;
    public void run(){
    OutputStream o=vm.getOutputStream();
    try {
         String vv=out_q.take();
         //System.out.println(vv);
         byte[] b=vv.getBytes();
         o.write(b);
         o.flush();
         System.out.println(vv);
         Thread.sleep(100);
    catch(IOException e1){
         System.out.println(e1.getMessage());
    catch(InterruptedException e2){
         System.out.println(e2.getMessage());
    return;
    class read_q implements Runnable {
    private LinkedBlockingQueue<String> in_q=null;
    private Process vm=null;
    public read_q(Process p){
    vm=p;
    in_q=new LinkedBlockingQueue<String>(64);
    public String read(){
    String v=null;
    try {
         v=in_q.take();
    catch(InterruptedException e){}
    return v;
    public void run(){
    byte[] b=new byte[256];
    InputStream ins=vm.getInputStream();
    try {
    while(true){
         int s=ins.read(b);
         if (s>0){
              String t=new String(b, 0, s).trim();
              in_q.put(t);
         //System.out.println("Read: "+t);
              if(t.equals("<>")) break;
         Thread.sleep(100);
    catch(IOException e){}
    catch(InterruptedException e3){}
    // end of class read_q
    public class morep{
    private static ExecutorService es=null;
    public morep(){
    es=Executors.newFixedThreadPool(2);
    public String read(){
    String v=null;
    return v;
    public void write(String msg){
    String v=this.read();
    return;
    public static void main(String[] args){
    ProcessBuilder pb=new ProcessBuilder("java", args[0]);
    pb.redirectErrorStream(true);
    pb.directory(new File(".//"));
    Process vm=null;
    morep mp=null;
    read_q reader=null;
    write_q writer=null;
    try {
         vm=pb.start();
         mp=new morep();
         writer=new write_q(vm);
         reader=new read_q(vm);
         es.execute(reader);
         es.execute(writer);
         System.out.println(reader.read());
         writer.write("Hello");
         System.out.println("Read: "+reader.read());
         writer.write("<>");
         System.out.println(reader.read());
         vm.waitFor();
         es.shutdown();
    catch(IOException e1){
         System.out.println(e1.getMessage());
    catch(InterruptedException e2){
         System.out.println(e2.getMessage());
    System.out.print("Press any key....");
    try {
         while(System.in.read()==-1);
    catch(IOException e3){}
    // end of main(String[] args)
    // end of class morep
    }

  • Question about Java Micro Edition

    Hello,
    I am interested about writing a program for PDAs. These seem to be running the Java Micro Edition, so I guess this is a good choice. But what about programming the GUI with the j2me? Afaik, it does not support swing, and the specifications are so full of abbreviations that I do not undertand that I really don't know other than to simply ask here about the possibilities of GUI programming with j2me, is there a "standard" gui library for j2me, or is it device-dependant, and is it possible to install the j2me under windows/linux for developing and testing purposes?
    Help please.. ;-)
    Thanks
    Jan

    thx :) J2ME seems to be very interesting. But zeb is right with the post in the discussion thread for this article, "where to start" is an important questions. So please, sun, make it easier for us to us (hobby-)programmers to adopt J2ME..
    I found this one alternatively:
    www.ewesoft.com
    does anyone have experiences with it?
    Jan

Maybe you are looking for