java - How would I avoid using Thread.sleep()? -
i have below snippet of code, designed check if message sent phone number:
public static boolean checkmessages(long sendtime, string phone) { boolean gotmessage = false; while (!gotmessage) { try { thread.sleep(5000); } catch (interruptedexception ex) { thread.currentthread().interrupt(); } gotmessage = messagehandler.getresponse(sendtime, phone); } return gotmessage; }
this code called through completablefuture
, can run in parallel check. if neither check satisfied within amount of time, both expire.
now, according ide , site, using thread.sleep()
bad number of reasons, i'd remove code somehow.
is there way such method ever return true, is?
messagehandler.getresponse()
handler wrote check if received text message containing specific (hardcoded) string of text specific phone number. block execution until finishes checking, api i'm using has aggressive rate limits. api offers no callbacks -- must manually called.
it's not clear whole code does. commented others, knowing messagehandler
add context.
the thread.sleep
static invocation make current thread sleep @ least given amount of time,
subject precision , accuracy of system timers , schedulers
(see api)
if messagehandler.getresponse
invocation blocks before returning, don't need sleep @ all.
however, if task repeated "endlessly", want use scheduledexecutorservice
instead, , run based on schedule.
bottomline, thread.sleep
not "bad practice" per se, seldom need use it.
Comments
Post a Comment