Some logistical questions re: threads

Discussion in 'Java' started by Jeremy, Jun 29, 2003.

  1. Jeremy

    Jeremy Guest

    Well, just one question, primarily.

    Consider the following scenario: Two threads are running in parallel. Each
    thread has called System.setOut(PrintStream myOut) to redirect output from
    its own printstream ("myOut") to the output. So what happens when thread A
    writes to its System.out, and what happens when thread B writes to
    System.out? To which thread's "myOut" does the output go? I assume that
    the last thread to call System.setOut will get all everything to its myOut,
    but that hardly seems fair to the first thread?

    This situation should really never matter, but in my situation it does :)
    Also, it is an interesting question - System resources are not thread-safe
    and could be hijacked by another thread.

    And I guess the question is, is there a way to give different threads their
    own System.out, such that they can write to System.out and be able to
    predict where it is going?

    Thanks,
    -Jeremy
     
    Jeremy, Jun 29, 2003
    #1
    1. Advertisements

  2. Jeremy

    Keeger Guest


    Well, I don't know anything about the System object in terms of
    thread-safing, but if you have 2 threads and need to output to 2
    different sources, why not just write to a file? Or a GUI component?
    You could make 2 textPanes and just output there...
     
    Keeger, Jun 30, 2003
    #2
    1. Advertisements

  3. This is an easy question to test--try it out! System.setOut is universal,
    so it seems the last one wins, assuming the call itself is threadsafe and
    the does not itself conflict.

    Cheers,
    Matt Humphrey http://www.iviz.com/
     
    Matt Humphrey, Jun 30, 2003
    #3
  4. Write a print stream that uses the current thread to look up print
    streams in a hashtable. That way you can have a different print stream
    for each thread.
     
    David Zimmerman, Jun 30, 2003
    #4
  5. There is only one System.out stream. It is synchronized so that individual
    calls to print() and println() are atomic. I believe that in general, most
    system resources are synchronized where necessary - I can't think of any
    that are not. That doesn't prevent fights between threads at a higher
    level though, such as where to redirect System.out.

    Probably the best thing is for each thread to open and maintain its own
    PrintWriter to its own output stream.

    Steve
     
    Steve Horsley, Jun 30, 2003
    #5
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.