Resume the execution using any key press - thread-sleep

i'm very new to java coding. i have a thread.sleep () to pause the execution and would like to write a code to resume execution with a key press on console. here is my code:
int pausetime = 9000; //user input
if (pausetime!=0){
thread.sleep(pausetime)}
for example user enters 9000 and decides to resume the execution at 5 secs, code should resume the execution with any key press on the console.

If you are using Thread.sleep then you have to interrupt this thread which throws exception that you have to handle and it continues execution.
Here is a sample code in which I am pausing the thread in run method while waiting for the input in main method and then interrupting above thread after user input
void run(){
try {
Thread.sleep(15000);
System.out.println("sleeping");
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Runnig thread again");
}
...
main(...){
Thread t= new Thread(task,"start");
t.start();
a=new InputStreamReader(System.in);
char[] ac=new char[5];
try {
a.read(ac);
} catch (IOException e){
e.printStackTrace();
}
if(ac.length>0)
t.interrupt();
}

Related

Dart async*, yield* and exception handling

If I have nested async* streams, exceptions do not appear to be catchable, which is counterintuitive.
An example:
void main() {
getString().listen(print);
}
Stream<String> getString() async* {
try {
yield* asyncStarError();
yield await asyncError();
} catch (err) {
yield 'Crash';
}
}
Stream<String> asyncStarError() async* {
throw Exception('A Stream error happened');
}
Future<String> asyncError() async {
throw Exception('A Future error happened');
}
This outputs:
Uncaught Error: Exception: A Stream error happened
Crash
So the exception thrown by asyncStarError is not caught, while the Future is caught as expected. Can anyone explain why?
You can observe the behaviour in dartpad: https://dartpad.dartlang.org
The yield* forwards all events from the stream it yields, including errors.
So, asyncStarError() produces a stream with an error event, and yield* forwards that error to the stream returned by getString, and then the getString.listen(print); does not add a handler so the error becomes uncaught.
(I'm guessing you're running this in a browser since that uncaught error doesn't crash the program.)
After that, the yield await asyncError() never yield anything. The await asyncError() itself throws, before reaching the yield, and that error is then caught by the catch which yields crash.
If you want to catch the errors of a stream, you need to actually look at the events, not just use yield* to forward them all blindly, including error events.
For example:
await for (var _ in asyncStarError()) {
// Wohoo, event!
}
would make the error from the asyncStarError stream an error at the loop. It would then be caught and you'd print "Crash".
TL;DR: The yield* operation forwards error events, it doesn't raise them locally.
Since yield * forwards them like #lrn said, you can catch them in main just fine. Or wherever you are consuming them.
void main() {
getString().listen(print).onError((e) => print('error caught: $e'));
}
Stream<String> getString() async* {
try {
yield* asyncStarError();
yield await asyncError();
} catch (err) {
yield 'Crash';
}
}
Stream<String> asyncStarError() async* {
throw Exception('A Stream error happened');
}
Future<String> asyncError() async {
throw Exception('A Future error happened');
}
this prints:
error caught: Exception: A Stream error happened
Crash
The difference is that async generator (async*) exceptions cannot be caught by surrounding it with try/catch.
Instead, you should use the callback handleError to achieve the behaviour you are looking for.
To go further, you may be interested in using runZonedGuarded.

How to handle FileSystemException in dart when watching a directory

I have written a simple command line tool in dart that watches changes in a directory if a directory does not exits I get FileSystemsException.
I have tried to handle it using try and catch clause. When the exception occurs the code in catch clause is not executed
try {
watcher.events.listen((event) {
if (event.type == ChangeType.ADD) {
print("THE FILE WAS ADDED");
print(event.path);
} else if (event.type == ChangeType.MODIFY) {
print("THE FILE WAS MODIFIED");
print(event.path);
} else {
print("THE FILE WAS REMOVED");
print(event.path);
}
});
} on FileSystemException {
print("Exception Occurs");
}
I expect the console to print "Exception Occurs"
There are two possibilities:
The exception is happening outside this block (maybe where the watcher is constructed?)
The exception is an unhandled async exception. This might be coming from either the Stream or it might be getting fired from some other Future, like perhaps the ready Future.
You can add handlers for the async exceptions like this:
try {
// If this is in an `async` method, use `await` within the try block
await watcher.ready;
// Otherwise add a error handler on the Future
watcher.ready.catchError((e) {
print('Exception in the ready Future');
});
watcher.events.listen((event) {
...
}, onError: (e) {
print('Exception in the Stream');
});
} on FileSystemException {
print("Exception Occurs");
}
My guess would be it's an error surfaced through the ready Future.

Why does not the runOn() method execute map operator on the next available thread from the pool when the current executing threads go to wait state?

I am trying to execute the following code on a 4 core machine. I have 5 threads in the pool and within the map operator, I put the executing thread to sleep for a few seconds.
I expect that the core would put the executing thread on sleep and when the next event is available, should perform the map operation on the next available thread from the thread pool, BUT is not the behavior I see.
I see that the 4 threads from the pool go on wait for 13 seconds and process the next event only after the wait is complete.
Why is the runOn() method not executing the map operator on the next available thread from the pool when the threads go to wait state?
I am using reactor-core version '3.0.7.RELEASE'
CountDownLatch latch = new CountDownLatch(10);
ExecutorService executorService = Executors.newFixedThreadPool(5);
Flux<Integer> flux = Flux.just(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
flux.parallel()
.runOn(Schedulers.fromExecutorService(executorService))
.map(l -> {
Logger.log(ReactorParallelTest.class, "map1", "inside run waiting for 13 seconds");
try {
Thread.sleep(13000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Logger.log(ReactorParallelTest.class, "map1", "l=" + l);
latch.countDown();
return l;
}).subscribe(l -> {
Logger.log(ReactorParallelTest.class, "onNext", "l=" + l);
}, error -> System.err.println(error),
() -> {
Logger.log(ReactorParallelTest.class, "onComplete", "inside complete.");
executorService.shutdown();
});
try {
latch.await(60, TimeUnit.SECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
}
You are blocking all your rails with this code. 4 rails will be started (number of CPUs), and they will immediately request 1 element each from the source. Since you immediately block in the map when this is done, the rail cannot request more from upstream, so in effect you only get 4 elements at a time, block, get more, block... The parallelism is more limited than the capacity of the thread pool. If you want to put all threads to good use, do .parallel(5) (same configuration as the thread pool).
On a side note, the subscribe(lambda) from ParallelFlux will invoke the onComplete callback for each rail. If you want to merge back to a single sequence (and single complete), use a .sequential() just before .subscribe.

.Net Quartz Scheduler 2.3 does not work on the remote server

I am working on a windows service that works on my development machine, but when I deploy to a test server I find that the Quartz Scheduler I have set up does not work.
There are no exceptions thrown or any clues as to why this is.
Here is my code;
protected override void OnStart(string[] args)
{
try
{
this.SetDailySchedule();
}
catch (SchedulerException ex)
{
this.eventLog.WriteEntry("WMS FM Loader: Schedule Error - " + ex.Message);
throw ex;
}
catch (Exception ex)
{
this.eventLog.WriteEntry("WMS FM Loader: Unexpected Error - " + ex.Message);
throw ex;
}
}
private void SetDailySchedule()
{
this.eventLog.WriteEntry("On Start".Log());
var schedule = this.GetSchedule();
try
{
this.schedFact = new StdSchedulerFactory();
this.sched = this.schedFact.GetScheduler();
}
catch (Exception ex)
{
this.eventLog.WriteEntry(ex.Message.Log());
throw;
}
this.eventLog.WriteEntry(string.Format("Got a scheduler: {0}", schedule).Log());
try
{
ScheduleTheLoad(schedule);
}
catch (Exception ex)
{
this.eventLog.WriteEntry(ex.Message.Log());
throw;
}
this.eventLog.WriteEntry("WMS FM Loader: Scheduler ready");
}
private void ScheduleTheLoad(string schedule)
{
var job = JobBuilder.Create<LoadWorksOrders>().WithIdentity("LoadWorksOrdersJob").Build();
// Trigger the job to run now, and then every day
var trigger =
TriggerBuilder.Create()
.ForJob(job)
.WithIdentity("LoadWorksOrdersTrigger")
.StartNow()
.WithCronSchedule(schedule)
.Build();
this.sched.ScheduleJob(job, trigger);
this.sched.Start();
}
I manually start the service and the event log shows that the scheduler is ready, but LoadWorksOrdersJob doe snot get run.
How should I fix this?
Are you running the two methods in the windows service OnStart? Are you using a service account? Any exceptions in the event viewer/ have you started /stopped the service from services.msc?
I also had this problem. It took me a day to work it out.
For me it was that my assembly had dots/periods in its name. e.g.
Project.UpdateService
When I changed it to...
ProjectUpdateService
... it worked fine. It always worked on the development machine. It just would not work on the remote machine.
UPDATE: It may have been the length of the service that has caused this issue. By removing the dots I shortened the service name. It looks like the maximum length is 25 characters.

message queue full error in blackberry

I have coded to get the info from the user and send an email of clicking a button. The program is getting executed for a while and then the simulator is crashing showing error
"DE427"-Message queue full... Here's the code that i have done...
if(field==SendMail)
{
Message m = new Message();
Address a = null;
try {
a = new Address("user#xyz.com", "Rahul");
} catch (AddressException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Address[] addresses = {a};
try {
m.addRecipients(net.rim.blackberry.api.mail.Message.RecipientType.TO, addresses);
m.setContent("Name:"+Name.getText().toString()+"\n"+ "Phone :"+Phone.getText().toString()+
"\n"+ "Date & Time:"+DateShow.getText().toString()+"\n"+"Make:"+Make.getText().toString()+
"\n"+"Model:"+Model.getText().toString()+"\n"+"Miles:"+Miles.getText().toString()+"\n");
m.setSubject("Appointment Request (Via Blackberry app)");
} catch (MessagingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Invoke.invokeApplication(Invoke.APP_TYPE_MESSAGES, new MessageArguments(m));
}
Can anyone tell me what the error is and how to rectify the problem....Plz...
It seems there is an issue with certain versions of Windows XP and the Blackberry simulator version. Check this link http://supportforums.blackberry.com/t5/Testing-and-Deployment/Simulator-quot-device-Error-DE427-quot/m-p/556321
If you clean up the simulator (delete .dmp files from simulator directory) and restart the simulator it works fine

Resources