need little help in getting input from keyboard

13 views
Skip to first unread message

shweta sharma

unread,
Apr 9, 2012, 7:59:02 AM4/9/12
to bo...@googlegroups.com
Hi ,

I have a requirement where i need to get input from keyboard from user .
the max time till when user can wait is 8 seconds .
Here i used scanner to get input from system.in . I know this wont  be useful because  program will wait  for infinite time  to read IO .
It will create  forever lock & that's how it is behaving.

here is code
 String nayme="";  // Declare & initialize a String to hold input.
 Scanner input=new Scanner(System.in); // Decl. & init. a Scanner.
 while((ttime-ctime < 5000) || (nayme ==""))
    {
        ttime=System.currentTimeMillis();
        name=input.next();
    }
 if(name=="")
        System.out.println("u dint type");


How can i wait till 5 secs only  & stop the thread that is waiting for System.in ? Will multi threading work ?

Is it possible in java ?

Thanks in advance.

Best Regards
Shweta


Raghavan.30May1981_GMail

unread,
Apr 10, 2012, 3:20:17 AM4/10/12
to bo...@googlegroups.com
I think you can surely do it and Java does have a support for it.

An additional note is that the way you check for the String input is NOT appropriate. You are checking for an empty reference string. Instead you should check for the empty string (or invalid string).

You can instead do this : if(null==str || str.trim().length()<=0)

Cheers,

Raghavan alias Saravanan M.
SHaDE Website | Tribute to Parents

"To begin a work and to leave it half done and to start another work elsewhere, is not a very wholesome habit."- The Mother




Shweta


--
You received this message because you are subscribed to the Google Groups "Bangalore Open Java Users Group- BOJUG" group.
To post to this group, send email to bo...@googlegroups.com.
To unsubscribe from this group, send email to bojug+un...@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/bojug?hl=en.

William la Forge

unread,
Apr 10, 2012, 3:32:39 AM4/10/12
to bo...@googlegroups.com
You can interrupt the thread from another thread:  http://docs.oracle.com/javase/7/docs/api/java/lang/Thread.html#interrupt() 

Bill


Shweta


shweta sharma

unread,
Apr 10, 2012, 5:32:23 AM4/10/12
to bo...@googlegroups.com
Well,  I tried that interrupting thread .
but found  that  it wont be possible to interrupt / suspend any thread that is listening over blocking  I/O .
I guess it is not possible in my case since System.in is  a blocking I/O ..i need to listen it on some event
or need to use NIO .

Thanks
shweta

Yaswanth Ravella

unread,
Apr 10, 2012, 8:27:16 AM4/10/12
to bo...@googlegroups.com
I wouldn't say it is not possible to do this using IO. You can always invoke available() to see if input data is available before calling read(). In that way read() call won't be blocked. 


Try this :

InputStream in = System.in;

// you can spawn a new thread to interrupt the current thread after X time. 

while(!currentThread().isInterrupted()){  // Basically this will be your exit condition.. Here, it is just an interrupt from another thread as Bill suggested.

if(in.available() > 0){
// Input data is available. So read it .

while(in.available()>0){

int read = in.read();  // Since the input data is available, this won't block.

}
break; // Received the Input. Break the while loop. 
}
}


--
Yaswanth Ravella

singh.janmejay

unread,
Apr 10, 2012, 8:17:41 AM4/10/12
to bo...@googlegroups.com

Streams usually have a non blocking predicate to find out if stream has data, you can use a while loop around the predicate as condition ANDed with timeout condition. Or you can unused the blocking call in a different thread and take action based on timeout in another thread. The timeout thread can check buffer value for emptiness that the blocking thread is supposed to populate should user key-in something.

shweta sharma

unread,
Apr 10, 2012, 9:46:32 AM4/10/12
to bo...@googlegroups.com
Hi Yaswanth ,

Thanks  it works
I tried  a lot using 2 threads . where one thread counting timeout & interrupting  the other thread but that  didnt work.
I was missing break .

Thanks for sharing this code !!

now it interrupts  after 5 secs .....& i am bale to get value of string ..though i did a little modification to capture  string from inputstream
I had read several places that  I/O are blocking channels & hence go into deadlock so i thought this thing cann't be  solved.


Thanks again.

William la Forge

unread,
Apr 10, 2012, 10:39:57 AM4/10/12
to bo...@googlegroups.com
I just wanted to add that you can still use Scanner with this low-level code. Just subclass InputStream using this low-level code. :-)


Bill

On Tue, Apr 10, 2012 at 7:22 PM, William la Forge <lafo...@gmail.com> wrote:
Oh my! You're really burning the CPU cycles. Add a Thread.sleep(100) to the outer loop--doubtful that the user will notice.

Also, if you are going to poll, you don't need another thread. Calculate the timeout value before entering the outer loop, do the check in the outer while for timeout and update the value with each character read.

Gosh, I think it has been about 20 years since I've written code like this!

Bill


On Tue, Apr 10, 2012 at 5:57 PM, Yaswanth Ravella <ma...@yaswanth.org> wrote:

William la Forge

unread,
Apr 10, 2012, 9:52:09 AM4/10/12
to bo...@googlegroups.com
Oh my! You're really burning the CPU cycles. Add a Thread.sleep(100) to the outer loop--doubtful that the user will notice.

Also, if you are going to poll, you don't need another thread. Calculate the timeout value before entering the outer loop, do the check in the outer while for timeout and update the value with each character read.

Gosh, I think it has been about 20 years since I've written code like this!

Bill

On Tue, Apr 10, 2012 at 5:57 PM, Yaswanth Ravella <ma...@yaswanth.org> wrote:

Yaswanth Ravella

unread,
Apr 12, 2012, 6:12:33 AM4/12/12
to bo...@googlegroups.com
Shweta, glad it helped :)

Bill, that logic was concisely written to address the core problem. Idea there was to check for bytes available before doing a read.  Yes, adding sleep is definitely good at least when awaiting user input but I guess it is best to leave this to the developer on how he wants to handle it. 

--
Yaswanth Ravella

William la Forge

unread,
Apr 13, 2012, 2:11:24 AM4/13/12
to bo...@googlegroups.com
There are also power usage considerations, especially for laptop users. A poll loop without a sleep drains your battery excessively and needlessly, :-(

On Fri, Apr 13, 2012 at 11:38 AM, William la Forge <lafo...@gmail.com> wrote:
I mean, it was OK when people were using DOS as an operating systems. But for Linux and Windows users, no way!


On Fri, Apr 13, 2012 at 11:36 AM, William la Forge <lafo...@gmail.com> wrote:
Truth. I just hate using software which hogs the machine with a poll loop. Without the sleep, the application is pretty hostile. --b

William la Forge

unread,
Apr 13, 2012, 2:08:06 AM4/13/12
to bo...@googlegroups.com
I mean, it was OK when people were using DOS as an operating systems. But for Linux and Windows users, no way!

On Fri, Apr 13, 2012 at 11:36 AM, William la Forge <lafo...@gmail.com> wrote:
Truth. I just hate using software which hogs the machine with a poll loop. Without the sleep, the application is pretty hostile. --b

William la Forge

unread,
Apr 13, 2012, 2:06:31 AM4/13/12
to bo...@googlegroups.com
Truth. I just hate using software which hogs the machine with a poll loop. Without the sleep, the application is pretty hostile. --b

shweta sharma

unread,
Apr 13, 2012, 2:24:27 AM4/13/12
to bo...@googlegroups.com

>> A poll loop without a sleep drains your battery excessively and needlessly,

Oh !! is it .....wasn't aware about it .
I read that JVM on 32 bit OS occupies at most 2GB .So in worst case a loop can  occupy more memory .
 How memory is related to  power  ?

Thanks
Shweta

aayush

unread,
Apr 15, 2012, 12:02:24 PM4/15/12
to bo...@googlegroups.com

A JVM on a 32 bit OS can occupy a max of 4 GB RAM (theoretically)

On Apr 15, 2012 9:30 PM, "shweta sharma" <shwe...@gmail.com> wrote:


>> A poll loop without a sleep drains your battery excessively and needlessly,

Oh !! is it .....wasn't aware about it .
I read that JVM on 32 bit OS occupies at most 2GB .So in worst case a loop can  occupy more memory .
 How memory is related to  power  ?

Thanks
Shweta


On Fri, Apr 13, 2012 at 11:41 AM, William la Forge <lafo...@gmail.com> wrote:
>

> There are also ...

William la Forge

unread,
Apr 15, 2012, 12:47:48 PM4/15/12
to bo...@googlegroups.com
Modern CPUs reduce power consumption when idle. And even under heavy use, they are idle a lot.

When I do benchmarks, I've got all 4 hardware threads maxed out. Lots of heat is generated and the fans kick into high gear. (Heat == Power)

A poll loop without a sleep will keep 1 hardware thread maxed out. Most folk have 2 hardware threads in their laptop, so at least this kind of poll loop will not completely hog the machine. But you may see things slow down a bit.

--

singh.janmejay

unread,
Apr 15, 2012, 8:03:34 PM4/15/12
to bo...@googlegroups.com

Not memory, CPU time hog.

But even that is usually not as bad when you have your kernel running a good process scheduler like CFQ in Linux. But sleep makes your program a good userland citizen for less capable OSes. So its good anyway.

--

Yaswanth Ravella

unread,
Apr 15, 2012, 1:51:22 PM4/15/12
to bo...@googlegroups.com
There won't be any build up in memory because of this loop. So you don't have to worry about it. Please correct me if i am wrong :)

Basically the problem with the above loop (w/o sleep) is it burns the CPU cycles unnecessarily. For example, if you are running this program on a single core system, its CPU usage would go up close to 100% due to this loop and thus leaving no room for other programs to run.. This will result in bad user experience, may be even affecting the user entering the input. So it is better to have a little sleep in the middle.  

Also, most of the portable computing devices today use power aware techniques to efficiently use the energy. So the more the hardware is used by the programs the quicker the battery gets drained.

--
Yaswanth Ravella
Reply all
Reply to author
Forward
0 new messages