Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / General / April 2008

Tip: Looking for answers? Try searching our database.

Interactive tracing ...

Thread view: 
Andreas Leitgeb - 04 Apr 2008 21:07 GMT
I've got a program that searches a large search-space
for some "solution", and this search can take a lot of time.
The search is done with a recursive function.  At the moment
I have an if-statement that causes some progress information
to be written out only at a certain recursion level.

What I really want is, that the program just runs quietly,
and when I press <Enter>-key (or perhaps at regular wallclock
time intervalls), it should answer me with snapshot progress
information and continue.

I believe I will have to spawn a second thread that will
just wait for input from stdin, and set some volatile boolean
variable to true, and the recursive function in the main
thread would check this variable at appropriate times, and
if it is set, then print out the info and unset it.  I don't
really care that - if I press <Enter> twice faster than the
other thread sees it - I will still only see one reaction,
but apart from that, is there anything else I should look
out for?

If instead I polled stdin for available data inside the
main (and only) thread, would it necessarily make it all
slower, or is there a way to do a real quick-check for
available data on a stream, that would be at least almost
as efficient as checking the volatile variable?

PS: Btw., it's a console-app without GUI.
Knute Johnson - 05 Apr 2008 00:58 GMT
> I've got a program that searches a large search-space
> for some "solution", and this search can take a lot of time.
[quoted text clipped - 24 lines]
>
> PS: Btw., it's a console-app without GUI.

Look at the code below.  The BufferedReader is created from System.in
and then is blocked in the loop until a line terminator is received,
<ENTER>.  It is simple and should do what you want.  If you are using
1.6 you can look at the Console class.  It has some convenient methods
to get Readers and Writers for the console.

import java.io.*;

public class test {
    public static void main(String[] args) {
        Runnable r = new Runnable() {
            public void run() {
                try {
                    BufferedReader br = new BufferedReader(
                     new InputStreamReader(System.in));
                    while (true) {
                        // blocks until newline is received

                        br.readLine();
                        // set your flag here
                    }
                } catch (IOException ioe) {
                    ioe.printStackTrace();
                }
            }
        };
        new Thread(r).start();
    }
    // your other code can go here
}

Signature

Knute Johnson
email s/nospam/linux/

     ------->>>>>>http://www.NewsDem

Andreas Leitgeb - 05 Apr 2008 23:58 GMT
> Look at the code below. ...
>          Runnable r = new Runnable() {
[quoted text clipped - 7 lines]
>          };
>          new Thread(r).start();

Thanks a lot. I (almost) took it "as is", except for the following
two changes:
 while (br.readLine() != null) { flag=true; }
(to make sure, that EOF on stdin will not cause a busy loop)
and
 Thread t=new Thread(r); t.setDaemon(true); t.start();
(daemonizing the thread, so it will not keep the prog running after
the main thread is done.)

Especially finding the right stacking of streams and readers is something
that would have taken me a lot of time to get right - Thanks for saving me
that work! :-)
Mark Space - 07 Apr 2008 00:31 GMT
> Especially finding the right stacking of streams and readers is something
> that would have taken me a lot of time to get right - Thanks for saving me
> that work! :-)

This is perennial complaint of mine as well.

In general, the Stream classes are older, and there were some
deficiencies found.  So therefore the Reader and Writer classes were
introduced.

To bridge the two, use InputStreamReader and OutputStreamWriter.  These
both go from an older style IO (the Stream) to the newer version
(Readers and Writers), just what you would expect for a class system
that's been upgraded.

Check out this tutorial, paying particular attention to the the section
on Character Streams.  That's where the important bit is.

<http://java.sun.com/docs/books/tutorial/essential/io/index.html>

After that, you just look up which IO Stream does what you want, which
Reader or Writer gives you the final result you want, and put those two
together with an IO Stream Reader/writer object if needed.  Notice that
this is just what Knute has done.

Sometimes, you put a BufferedReader or -Writer in between a outer
Reader/Writer and the IO Stream Reader/Writer.  These last two
paragraphs will get you 90% of what you need from Java IO.

P.S. _Learning Java_ by O'Reilly.  It goes into all this. ;-)
Lew - 07 Apr 2008 03:15 GMT
>> Especially finding the right stacking of streams and readers is something
>> that would have taken me a lot of time to get right - Thanks for
[quoted text clipped - 6 lines]
> deficiencies found.  So therefore the Reader and Writer classes were
> introduced.

The Stream classes may be slightly older, in that it took all the way until
Java 1.1 [1] until they introduced Readers and Writers, but by no means does
that mean that Streams are deficient or no longer relevant.  (What
"deficiencies" were found in Streams, anyway?)

The real difference, and the important one, is that Streams handle bytes and
Readers/Writers handle characters and their encodings.  If you aren't handling
characters, do NOT use Readers and Writers.  Streams are most emphatically not
obsolete.

> To bridge the two, use InputStreamReader and OutputStreamWriter.  These
> both go from an older style IO (the Stream) to the newer version
> (Readers and Writers), just what you would expect for a class system
> that's been upgraded.

It's not about "upgrades", it's about whether you're processing binary or text
data.

> Check out this tutorial, paying particular attention to the the section
> on Character Streams.  That's where the important bit is.
>
> <http://java.sun.com/docs/books/tutorial/essential/io/index.html>

You'll note that there's nothing in there about Streams' "deficiencies" or
about Readers/Writers substituting for Streams.

> After that, you just look up which IO Stream does what you want, which
> Reader or Writer gives you the final result you want, and put those two
> together with an IO Stream Reader/writer object if needed.  Notice that
> this is just what Knute has done.

If you are reading character streams.

> Sometimes, you put a BufferedReader or -Writer in between a outer
> Reader/Writer and the IO Stream Reader/Writer.  These last two
> paragraphs will get you 90% of what you need from Java IO.

Or you put the BufferedReader/Writer on top, not the middle.

> P.S. _Learning Java_ by O'Reilly.  It goes into all this. ;-)

Again, it's Streams for binary data, Readers and Writers for encoded character
data, nothing to do with newer or older.

[1] I'll bet that very nearly all the Java programmers reading this post
learned Java at or after version 1.1.  I myself started learning Java during
1.1 and started practicing it professionally with version 1.2.  By that time,
Hashtable and Vector were already obsolete and the Reader and Writer classes
were well established.

Signature

Lew

Andreas Leitgeb - 07 Apr 2008 19:08 GMT
>>> Especially finding the right stacking of streams and readers is something
>>> that would have taken me a lot of time to get right - Thanks for saving me
[quoted text clipped - 5 lines]
> that mean that Streams are deficient or no longer relevant.  (What
> "deficiencies" were found in Streams, anyway?)

I guess he means the unlucky decision to add a (since deprecated) readLine()
to the *InputStream-family.

> The real difference, and the important one, is that Streams handle bytes and
> Readers/Writers handle characters and their encodings.
So far it's clear, but it's not trivially obvious which *Reader class
can be wrapped on what *Stream class, and what interims-wrappers I need
to be finally able to read a whole line (->BufferedReader) from System.in .

I love the Scanner, though.  Just pass it a File or System.in or a
String, and you get all the tokens you want.


Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.