In a program (Java) I'm making I need to check for a specific pin in the parallel port. Whenever that pin goes from logical 0 to 1 (a positive edge clock) I have to read the data on the port and save it. This happens about every 10ms but can vary a little.
To do this I made a separate thread with a while loop that is constantly checking the port, but this makes the processor go nuts and I know it's because of the while loop. My question is, how can I constantly scan the port without using a processor intensive while loop? The program doesn't know precisely when a pin change will happen, only that it happens around every 10ms.
Fire a thread which is scheduled to execute the given Runnable at a fixed rate. You can use Timer#scheduleAtFixedRate() or ScheduledExecutorService#scheduleAtFixedRate() for this. The last one is preferred.
ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
scheduler.scheduleAtFixedRate(new PortScanner(), 0, 10, TimeUnit.MILLISECONDS); // Run every 10 ms.
Where PortScanner can look like this:
public class PortScanner implements Runnable {
#Override
public void run() {
// Scan port here.
}
}
Don't forget to call scheduler.shutdown() at the moment your application exits, else the thread may hang.
There might be a better solution, but worst case you could just Thread.sleep for 1-2ms every iteration of the while loop.
It is really tricky to catch hardware interrupts when your code is not running as a part of operating system. What you can do is to put Thread.Sleep ( 5 ). This will sleep for 10 milliseconds, and will let the other threads run or just keep CPU idle and cool. Having 5 ms delay should be enough to ensure won't miss any clock ticks.
This would work when your clock is alternating between 10 ms high and 10 ms low. For other patterns you have to adjust the parameter accordingly.
Related
I need to have a background thread that constantly does an action, sleep for X seconds and do the action etc.
Basically the run method is something like:
while(!isInterrupted()){
//do something
Thread.sleep(10);
}
My question is:
Does it make sense to use an executor in this case? Since I am not
spawning threads, is even in this case using an executor (single
threaded) better?
Additionally if I want a guarantee that the thread goes in the do
something part in exactly 10 seconds, is that possible via using
just a custom thread or more guaranteed via an executor? I mean if I have a hard limit of 10 seconds to perform an action, what can I do to achieve it? I assume that the time that the code goes back in do something may fluctuate due to scheduling etc. How could I get such a guarantee?
If you are using only a single thread which is a forever running task like yours then you can use your present logic.
But only when you have some small tasks that need to be run, then there is point in using SingleThreadPool.
How could I get such a guarantee?
There is no such guarantee from the OS side (Linux or Windows), that the thread will return from sleep at exact 10 seconds. Try increasing thread priority, but that too is not guaranteed to work.
Your logic should not be dependent on such hard timings IMO.
Here is my code
try{
System.out.println("Before");
thread.sleep(10000);//sleep for 10000 ms
System.out.println("After");
}
catch(ItrerruptedException ie){
//If this thread was intrrupted by nother thread
}
I just want to know whether the thread will sleep for exaclty 10 seconds and then print After or there is some delay?
From the javadocs: Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds, subject to the precision and accuracy of system timers and schedulers. Which means it will sleep for at least 10 seconds. It may sleep longer if the scheduler decides to not let it run after the 10 seconds is over.
Which may happen if more concurrent threads are in the runnable pool at the same time.
A non realtime scheduler won't guarantee timing.
If you are doing some kind of hardware communication that really relies on timing, you should probably use RTSJ.
If you are doing something each x milliseconds, you could use a TimeTask that will perform slightly better.
It will sleep for at least 10 seconds, and wake shortly after (unless interrupted). How soon after depends on the OS and the load on the machine.
It's more or less random because your OS task scheduler is usually not required to give your process all the attention it wants. Usually, you will not be able to sleep for very small amounts of time (for example, Thread.sleep(5) might resume your process later than 5 ms after the call), but as you increase the sleep time, the relative precision increases.
If you can tolerate some leeway, Thread.sleep(10000) will usually sleep for an amount of time that's close enough to 10 seconds.
I would say unless you have lots of threads running it's pretty close to exact. If you have several threads then it's a competition.
The overhead of the thread from sleep to running is very low.
I wrote a multi threading programme, which have two to four thread at the same time.
One of the thread is time critical thread, it will be called every 500 milliseconds, it is not allow to delay more than 10 milliseconds. But when other thread have more loading, I find that some delay, around two millisecond is occurred. (Print the timestamp to show it) So, I worry that after running for a long time it will delay more than 10 milliseconds, except from check the timestamp, and adjust the looping interval to make sure the time is not delay more than 10 milliseconds, is there any way to make it safe?
Thanks.
Sounds like you need Real-Time Java
If timing is critical, I use a busy wait on a core which is dedicated to that thread. This can give you << 10 micro-second jitter most of the time. Its a bit extreme and will result in the logical thread not being used for anything else.
This is the library I use. You can use it to reserve a logical thread or a whole core. https://github.com/peter-lawrey/Java-Thread-Affinity
By using isolcpus= in grub.conf on Linux you can ensure that the logical thread or core is not used for any else (except the 100 Hz timer and power management which are relatively small and < 2 us delay)
You can set your threads priorities:
myCriticalThread.setPriority(Thread.MAX_PRIORITY);
otherThread.setPriority(Thread.NORM_PRIORITY); // the default
yetAnotherThread.setPriority(Thread.MIN_PRIORITY);
It won't really guarantee anything though.
There is no guarantee that your thread isn't delayed, because the OS may decide to give other processes precedence (unless you put effort in setting up a complete real-time system including a modified OS). That being said, for basic tasks, you should use a ScheduledExecutorService like this:
class A {
private final ScheduledExecutorService exe = Executors.newScheduledThreadPool(1);
public void startCriticalAction(Runnable command) {
this.exe.scheduleAtFixedRate(command, 100, 100, TimeUnit.MILLISECONDS);
}
public void shutdown() {
this.exe.shutdown();
}
}
The executor service will do its best to execute the task every 100ms. You should not develop this functionality yourself, because a lot of things can go wrong.
Creep up on the timeout:
waitFor(int timeout)
{
dateTime wallTimeEnd;
wallTimeEnd=now()+(msToDateTime(timeout));
int interval=timeout/2;
while(true){
if(interval>10){
sleep(interval);
interval=dateTimeToMs(wallTimeEnd-now()) / 2;
}
else
{
do{
sleep(0);
interval=dateTimeToMs(wallTimeEnd-now());
}while(interval>0);
}
}
This only wastes a core for 5-10ms
I have to cache some db records some time period.
For example i am assuming huge traffic on my website at 4 pm today.I will cache the login table at around 3.50.Because i know that users will come at this time.
How can i go about it in java?I am thinking is running a thread at specific interval and then
running it at every 1 hr to check if i need something to be cached
Is the thread guaranteed to run?
class Mthread extends Thread{
run(){
//update cache
}
}
you may take a look on java Cron. I guess this should solve your problem.
http://www.sauronsoftware.it/projects/cron4j/
Cron jobs are used to trigger some action at particular time and is highly configurable like you can configure it to work daily at 3:50 PM.
Hopefully it should solve your problem
You can implement your run() method using a while loop that loops indefinitely. At the end of every iteration of the loop, calculate the number of milliseconds for your thread to sleep until the next update time (perhaps set a maximum sleep time if you want it to wake up periodically). The thread is guaranteed to run when you want it to, provided the following:
You tell it exactly how long it needs to sleep or wait until the next cache update time.
Your thread doesn't get interrupted before you want it to.
No exceptions cause your thread's run() method to return prematurely.
Your thread doesn't cause some weird error, like an OutOfMemoryError, to occur.
Consider the following code:
while(true) {
someFunction();
Thread.sleep(1000);
}
What I want is that, someFunction() be called once every 10 seconds. But this is not the case. It is being called every second. I tried Thread.wait(1000), but even that doesnt help. I removed of the while part, just kept the body, and at the end wrote :
Thread.start();
But it throwed an exception. Is there any other solution to this?
It's being called every second because you're sleeping for 1000 milliseconds, aka 1 second.
Change it to Thread.sleep(10000) and that'll be better for you.
Alternatively, use
Thread.sleep(TimeUnit.SECONDS.toMillis(10));
which means you don't have to do the arithmetic yourself. (Many APIs now take a quantity and a TimeUnit, but there doesn't appear to be anything like that for Thread.sleep unfortunately.)
Note that this will make the thread unresponsive for 10 seconds, with no clean way of telling it to wake up (e.g. because you want to shut it down). I generally prefer to use wait() so that I can pulse the same monitor from a different thread to indicate "I want you to wake up now!" This is usually from within a while loop of the form
while (!shouldStop())
EDIT: tvanfosson's solution of using a Timer is also good - and another alternative is to use ScheduledExecutorService which can be a bit more flexible (and easier to test).
Thread.sleep() takes the number of miliseconds to sleep. Thus, calling Thread.sleep(1000) sleeps 1000 miliseconds, which is 1 second. Make that Thread.sleep(10000) and it will sleep 10 seconds.
1 second is 1000 milliseconds, so if you want 10 seconds = 10 * 1000 = 10000 milliseconds
e.g.
try {
long numMillisecondsToSleep = 5000; // 5 seconds
Thread.sleep(numMillisecondsToSleep);
} catch (InterruptedException e) { }
What you probably want to do is use a Timer and set up a scheduled invocation of the function rather than sleeping. If you need more exactness with regard to the interval, you can keep track of how long it has been since the last run and adjust the new timer to keep your interval from drifting. See an example of a simple timer in this tutorial.
I won't go into detail about the issue with regard to the precision of the argument, since #Jon has already covered that -- you need milliseconds rather than seconds.
Consider 1000 milliseconds is 1 second. For that you should use Thread.sleep(10000) for acheiving pause your thread in 10 seconds. You can also use looping with how many seconds to wait your thread.
Ex. suppose you want to pause your thread in half-an-hour( 30 minutes). Then use,
for(i=0;i<1800;i++)
{
Thread.sleep(1000);
}
It will pause your thread in 30 minutes.
What I want is that, someFunction() be
called once every 10 seconds.
Then why do you call Thread.sleep() with 1000 as parameter? That's in milliseconds, so you're explicitly saying "wait 1 second".