Restricting method calls to 1 per sec with Java?
I am writing a program, and I would only like the user to be able to make certain method calls every 1 second. I'm having trouble figuring out the best way to do this in Java.
The best idea I can come up with is having a pointcut for the method calls I want to restrict and having some sort of static variable (stored where?) of when the last call was, and sleeping as necessary. Is this good practice?
Thanks!
Edit: the method calls are hitting a busy 开发者_StackOverflow社区webserver, and thus they should be restricted to 1 per second.
Edit2: I am writing a client to access a server. I do not have any control over the server.
This is pretty common for scenarios like "refresh", etc. where there it is desirable to limit the frequency.
I would use a separate worker thread. The method invocation signals the thread and returns immediately. The tread wakes up, checks how long it has been since the last execution and runs if necessary. The long field tracking last execution can be a member variable of the thread.
Why would you do this? If I had to give some kind of solution to something this quirky, I'd say you use
System.currentTimeMillis()
to keep track of the last time the method was called, and simply return if one second has not passed from now till the last time the method was called.
I would do it by using a queue of commands and then a fixed rate scheduler to dispatch those commands at the required rate. You could even build in some logic to detect if new commands entering the queue could be coalesced with existing un-dispatched commands. Take a look at java.util.concurrent.ScheduledExecutor and the command pattern
I assume the user has to press a button to call this method. I would disable the button until the user is allowed to click it again.
I am not sure why you would want to this. Are you trying conserve memory, or CPU? Assuming you have a web app with multiple threads you could use something like a java.util.concurrent.Semaphore which is a counting semaphore to to limit the number of threads that can execute that code to the number in the Semaphore http://download.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/Semaphore.html
You could also use some of the thread pooling schedulers that are part of java.util.concurrent to create a certain number of threads in a thread pool and then assign work to them that way you can limit how often a particular piece of code executes.
There are other data structures in java.util.concurrent that could be useful such as BlockingQueue
If you tell us more about the context of your application we can help you better.
精彩评论