Java Design Issue: Enforce method call sequence - java

There is a question which was recently asked to me in an interview.
Problem: There is a class meant to profile the execution time of the code. The class is like:
Class StopWatch {
long startTime;
long stopTime;
void start() {// set startTime}
void stop() { // set stopTime}
long getTime() {// return difference}
}
The client is expected to create an instance of the StopWatch and call methods accordingly. User code can mess up the use of the methods leading to unexpected results. Ex, start(), stop() and getTime() calls should be in order.
This class has to be "reconfigured" so that user can be prevented from messing up the sequence.
I proposed use of custom exception if stop() is called before start(), or doing some if/else checks, but interviewer was not satisfied.
Is there a design pattern to handle these kind of situations?
Edit: The class members and method implementations can be modified.

First there is the fact that implementing an own Java profiler is a waste of time, since good ones are available (maybe that was the intention behind the question).
If you want to enforce the correct method order at compile time, you have to return something with each method in the chain:
start() has to return a WatchStopper with the stop method.
Then WatchStopper.stop() has to return a WatchResult with the getResult() method.
External Construction of those helper classes as well as other ways of accessing their methods have to be prevented of course.

With minor changes to the interface, you can make the method sequence the only one that can be called - even at compile time!
public class Stopwatch {
public static RunningStopwatch createRunning() {
return new RunningStopwatch();
}
}
public class RunningStopwatch {
private final long startTime;
RunningStopwatch() {
startTime = System.nanoTime();
}
public FinishedStopwatch stop() {
return new FinishedStopwatch(startTime);
}
}
public class FinishedStopwatch {
private final long elapsedTime;
FinishedStopwatch(long startTime) {
elapsedTime = System.nanoTime() - startTime;
}
public long getElapsedNanos() {
return elapsedTime;
}
}
The usage is straightforward - every method returns a different class which only has the currently applicable methods. Basically, the state of the stopwatch is encapsuled in the type system.
In comments, it was pointed out that even with the above design, you can call stop() twice. While I consider that to be added value, it is theoretically possible to screw oneself over. Then, the only way I can think of would be something like this:
class Stopwatch {
public static Stopwatch createRunning() {
return new Stopwatch();
}
private final long startTime;
private Stopwatch() {
startTime = System.nanoTime();
}
public long getElapsedNanos() {
return System.nanoTime() - startTime;
}
}
That differs from the assignment by omitting the stop() method, but that's potentially good design, too. All would then depend on the precise requirements...

We commonly use StopWatch from Apache Commons StopWatch check the pattern how they've provided.
IllegalStateException is thrown when the stop watch state is wrong.
stop
public void stop()
Stop the stopwatch.
This method ends a new timing session, allowing the time to be retrieved.
Throws:
IllegalStateException - if the StopWatch is not running.
Straight forward.

Maybe he expected this 'reconfiguration' and question was not about method sequence at all:
class StopWatch {
public static long runWithProfiling(Runnable action) {
startTime = now;
action.run();
return now - startTime;
}
}

Once given more thought
In hindsight it sounds like they were looking for the execute around pattern. They're usually used to do things like enforce closing of streams. This is also more relevant due to this line:
Is there a design pattern to handle these kind of situations?
The idea is you give the thing that does the "executing around" some class to do somethings with. You'll probably use Runnable but it's not necessary. (Runnable makes the most sense and you'll see why soon.) In your StopWatch class add some method like this
public long measureAction(Runnable r) {
start();
r.run();
stop();
return getTime();
}
You would then call it like this
StopWatch stopWatch = new StopWatch();
Runnable r = new Runnable() {
#Override
public void run() {
// Put some tasks here you want to measure.
}
};
long time = stopWatch.measureAction(r);
This makes it fool proof. You don't have to worry about handling stop before start or people forgetting to call one and not the other, etc. The reason Runnable is nice is because
Standard java class, not your own or third party
End users can put whatever they need in the Runnable to be done.
(If you were using it to enforce stream closing then you could put the actions that need to be done with a database connection inside so the end user doesn't need to worry about how to open and close it and you simultaneously force them to close it properly.)
If you wanted, you could make some StopWatchWrapper instead leave StopWatch unmodified. You could also make measureAction(Runnable) not return a time and make getTime() public instead.
The Java 8 way to calling it is even simpler
StopWatch stopWatch = new StopWatch();
long time = stopWatch.measureAction(() - > {/* Measure stuff here */});
A third (hopefully final) thought: it seems what the interviewer was looking for and what is being upvoted the most is throwing exceptions based on state (e.g., if stop() is called before start() or start() after stop()). This is a fine practice and in fact, depending on the methods in StopWatch having a visibility other than private/protected, it's probably better to have than not have. My one issue with this is that throwing exceptions alone will not enforce a method call sequence.
For example, consider this:
class StopWatch {
boolean started = false;
boolean stopped = false;
// ...
public void start() {
if (started) {
throw new IllegalStateException("Already started!");
}
started = true;
// ...
}
public void stop() {
if (!started) {
throw new IllegalStateException("Not yet started!");
}
if (stopped) {
throw new IllegalStateException("Already stopped!");
}
stopped = true;
// ...
}
public long getTime() {
if (!started) {
throw new IllegalStateException("Not yet started!");
}
if (!stopped) {
throw new IllegalStateException("Not yet stopped!");
}
stopped = true;
// ...
}
}
Just because it's throwing IllegalStateException doesn't mean that the proper sequence is enforced, it just means improper sequences are denied (and I think we can all agree exceptions are annoying, luckily this is not a checked exception).
The only way I know to truly enforce that the methods are called correctly is to do it yourself with the execute around pattern or the other suggestions that do things like return RunningStopWatch and StoppedStopWatch that I presume have only one method, but this seems overly complex (and OP mentioned that the interface couldn't be changed, admittedly the non-wrapper suggestion I made does this though). So to the best of my knowledge there's no way to enforce the proper order without modifying the interface or adding more classes.
I guess it really depends on what people define "enforce a method call sequence" to mean. If only the exceptions are thrown then the below compiles
StopWatch stopWatch = new StopWatch();
stopWatch.getTime();
stopWatch.stop();
stopWatch.start();
True it won't run, but it just seems so much simpler to hand in a Runnable and make those methods private, let the other one relax and handle the pesky details yourself. Then there's no guess work. With this class it's obvious the order, but if there were more methods or the names weren't so obvious it can begin to be a headache.
Original answer
More hindsight edit: OP mentions in a comment,
"The three methods should remain intact and are only interface to the programmer. The class members and method implementation can change."
So the below is wrong because it removes something from the interface. (Technically, you could implement it as an empty method but that seems to be like a dumb thing to do and too confusing.) I kind of like this answer if the restriction wasn't there and it does seem to be another "fool proof" way to do it so I will leave it.
To me something like this seems to be good.
class StopWatch {
private final long startTime;
public StopWatch() {
startTime = ...
}
public long stop() {
currentTime = ...
return currentTime - startTime;
}
}
The reason I believe this to be good is the recording is during object creation so it can't be forgotten or done out of order (can't call stop() method if it doesn't exist).
One flaw is probably the naming of stop(). At first I thought maybe lap() but that usually implies a restarting or some sort (or at least recording since last lap/start). Perhaps read() would be better? This mimics the action of looking at the time on a stop watch. I chose stop() to keep it similar to the original class.
The only thing I'm not 100% sure about is how to get the time. To be honest that seems to be a more minor detail. As long as both ... in the above code obtain current time the same way it should be fine.

I suggest something like:
interface WatchFactory {
Watch startTimer();
}
interface Watch {
long stopTimer();
}
It will be used like this
Watch watch = watchFactory.startTimer();
// Do something you want to measure
long timeSpentInMillis = watch.stopTimer();
You can't invoke anything in wrong order. And if you invoke stopTimer twice you get meaningful result both time (maybe it is better rename it to measure and return actual time each time it invoked)

Throwing an exception when the methods are not called in the correct order is common. For example, Thread's start will throw an IllegalThreadStateException if called twice.
You should have probably explained better how the instance would know if the methods are called in the correct order. This can be done by introducing a state variable, and checking the state at the start of each method (and updating it when necessary).

This can also be done with Lambdas in Java 8. In this case you pass your function to the StopWatch class and then tell the StopWatch to execute that code.
Class StopWatch {
long startTime;
long stopTime;
private void start() {// set startTime}
private void stop() { // set stopTime}
void execute(Runnable r){
start();
r.run();
stop();
}
long getTime() {// return difference}
}

Presumably the reason for using a stopwatch is that the entity that's interested in the time is distinct from the entity that's responsible for starting and stopping the timing intervals. If that is not the case, patterns using immutable objects and allowing code to query a stop watch at any time to see how much time has elapsed to date would likely be better than those using a mutable stopwatch object.
If your purpose is to capture data about how much time is being spent doing various things, I would suggest that you might be best served by a class which builds a list of timing-related events. Such a class may provide a method to generate and add a new timing-related event, which would record a snapshot of its created time and provide a method to indicate its completion. The outer class would also provide a method to retrieve a list of all timing events registered to date.
If the code which creates a new timing event supplies a parameter indicating its purpose, code at the end which examines the list could ascertain whether all events that were initiated have been properly completed, and identify any that had not; it could also identify if any events were contained entirely within others or overlapped others but were not contained within them. Because each event would have its own independent status, failure to close one event need not interfere with any subsequent events or cause any loss or corruption of timing data related to them (as might occur if e.g. a stopwatch had been accidentally left running when it should have been stopped).
While it's certainly possible to have a mutable stopwatch class which uses start and stop methods, if the intention is that each "stop" action be associated with a particular "start" action, having the "start" action return an object which must be "stopped" will not only ensure such association, but it will allow sensible behavior to be achieved even if an action is started and abandoned.

I know this already has been answered but couldn't find an answer invoking builder with interfaces for the control flow so here is my solution :
(Name the interfaces in a better way than me :p)
public interface StartingStopWatch {
StoppingStopWatch start();
}
public interface StoppingStopWatch {
ResultStopWatch stop();
}
public interface ResultStopWatch {
long getTime();
}
public class StopWatch implements StartingStopWatch, StoppingStopWatch, ResultStopWatch {
long startTime;
long stopTime;
private StopWatch() {
//No instanciation this way
}
public static StoppingStopWatch createAndStart() {
return new StopWatch().start();
}
public static StartingStopWatch create() {
return new StopWatch();
}
#Override
public StoppingStopWatch start() {
startTime = System.currentTimeMillis();
return this;
}
#Override
public ResultStopWatch stop() {
stopTime = System.currentTimeMillis();
return this;
}
#Override
public long getTime() {
return stopTime - startTime;
}
}
Usage :
StoppingStopWatch sw = StopWatch.createAndStart();
//Do stuff
long time = sw.stop().getTime();

As Per Interview question ,It seems to like this
Class StopWatch {
long startTime;
long stopTime;
public StopWatch() {
start();
}
void start() {// set startTime}
void stop() { // set stopTime}
long getTime() {
stop();
// return difference
}
}
So now All user need to create object of StopWatch class at beginning and getTime() need to call at End
For e.g
StopWatch stopWatch=new StopWatch();
//do Some stuff
stopWatch.getTime()

I'm going to suggest that enforcing the method call sequence is solving the wrong problem; the real problem is a unfriendly interface where the user must be aware of the state of the stopwatch. The solution is to remove any requirement to know the state of the StopWatch.
public class StopWatch {
private Logger log = Logger.getLogger(StopWatch.class);
private boolean firstMark = true;
private long lastMarkTime;
private long thisMarkTime;
private String lastMarkMsg;
private String thisMarkMsg;
public TimingResult mark(String msg) {
lastMarkTime = thisMarkTime;
thisMarkTime = System.currentTimeMillis();
lastMarkMsg = thisMarkMsg;
thisMarkMsg = msg;
String timingMsg;
long elapsed;
if (firstMark) {
elapsed = 0;
timingMsg = "First mark: [" + thisMarkMsg + "] at time " + thisMarkTime;
} else {
elapsed = thisMarkTime - lastMarkTime;
timingMsg = "Mark: [" + thisMarkMsg + "] " + elapsed + "ms since mark [" + lastMarkMsg + "]";
}
TimingResult result = new TimingResult(timingMsg, elapsed);
log.debug(result.msg);
firstMark = false;
return result;
}
}
This allows a simple use of the mark method with a result returned and logging included.
StopWatch stopWatch = new StopWatch();
TimingResult r;
r = stopWatch.mark("before loop 1");
System.out.println(r);
for (int i=0; i<100; i++) {
slowThing();
}
r = stopWatch.mark("after loop 1");
System.out.println(r);
for (int i=0; i<100; i++) {
reallySlowThing();
}
r = stopWatch.mark("after loop 2");
System.out.println(r);
This gives the nice result of;
First mark: [before loop 1] at time 1436537674704
Mark: [after loop 1] 1037ms since mark [before loop 1]
Mark: [after loop 2] 2008ms since mark [after loop 1]

Related

Creating 2 threads and each running different tasks

I want to create two threads in my application that'll run two methods. I'm using the builder design pattern where inside the build method I have something like this, request is the Object that is passed:
Rules rule;
Request build() {
Request request = new Request(this);
//I want one threat to call this method
Boolean isExceeding = this.rule.volumeExceeding(request);
//Another thread to call this method
Boolean isRepeating = this.rule.volumeRepeating(request);
//Some sort of timer that will wait until both values are received,
//If one value takes too long to be received kill the thread and continue with
//whatever value was received.
..Logic based on 2 booleans..
return request;
}
Here's how this class looks like:
public class Rules {
public Boolean volumeExceeding(Request request) {
...some...logic...
return true/false;
}
public Boolean volumeRepeating(Request request) {
...some...logic...
return true/false;
}
}
I have commented in the code what I'd like to happen. Basically, I'd like to create two threads that'll run their respective method. It'll wait until both are finished, however, if one takes too long (example: more than 10ms) then return the value that was completed. How do I create this? I'm trying to understand the multithreading tutorials, but the examples are so generic that it's hard to take what they did and apply it to something more complicated.
One way to do that is to use CompletableFutures:
import java.util.concurrent.CompletableFuture;
class Main {
private static final long timeout = 1_000; // 1 second
static Boolean volumeExceeding(Object request) {
System.out.println(Thread.currentThread().getName());
final long startpoint = System.currentTimeMillis();
// do stuff with request but we do dummy stuff
for (int i = 0; i < 1_000_000; i++) {
if (System.currentTimeMillis() - startpoint > timeout) {
return false;
}
Math.log(Math.sqrt(i));
}
return true;
}
static Boolean volumeRepeating(Object request) {
System.out.println(Thread.currentThread().getName());
final long startpoint = System.currentTimeMillis();
// do stuff with request but we do dummy stuff
for (int i = 0; i < 1_000_000_000; i++) {
if (System.currentTimeMillis() - startpoint > timeout) {
return false;
}
Math.log(Math.sqrt(i));
}
return true;
}
public static void main(String[] args) {
final Object request = new Object();
CompletableFuture<Boolean> isExceedingFuture = CompletableFuture.supplyAsync(
() -> Main.volumeExceeding(request));
CompletableFuture<Boolean> isRepeatingFuture = CompletableFuture.supplyAsync(
() -> Main.volumeRepeating(request));
Boolean isExceeding = isExceedingFuture.join();
Boolean isRepeating = isRepeatingFuture.join();
System.out.println(isExceeding);
System.out.println(isRepeating);
}
}
Notice that one task takes significantly longer than the other.
What's happening? You supply those tasks to the common pool by using CompletableFuture for execution. Both tasks are executed by two different threads. What you've asked for is that a task is stopped when it takes too long. Therefore you can simply remember the time when a task has started and periodically check it against a timeout. Important: Do this check when the task would return while leaving the data in a consistent state. Also note that you can place multiple checks of course.
Here's a nice guide about CompletableFuture: Guide To CompletableFuture
If I understand your question correctly, then you should do this with a ticketing system (also known as provider-consumer pattern or producer-consumer pattern), so your threads are reused (which is a significant performance boost, if those operations are time critical).
The general idea should be:
application initialization
Initialize 2 or more "consumer" threads, which can work tickets (also called jobs).
runtime
Feed the consumer threads tickets (or jobs) that will be waited on for (about) as long as you like. However depending on the JVM, the waiting period will most likely not be exactly n milliseconds, as most often schedulers are more 'lax' in regards to waiting periods for timeouts. e.g. Thread.sleep() will almost always be off by a bunch of milliseconds (always late, never early - to my knowledge).
If the thread does not return after a given waiting period, then that result must be neglected (according to your logic), and the ticket (and thus the thread) must be informed to abort that ticket. It is important that you not interrupt the thread, since that can lead to exceptions, or prevent locks from being unlocked.
Remember, that halting or stopping threads from the outside is almost always problematic with locks, so I would suggest, your jobs visit a possible exit point periodically, so if you stop caring about a result, they can be safely terminated.

avoid race condition by making tasks depend on a nontask object

This question comes from section sharing resources of Think in java.
Note that in this example the class that can be canceled is not Runnable. Instead, all the EvenChecker tasks that depend on the IntGenerator object test it to see whether it’s been canceled, as you can see in run( ).
And
For example, a task cannot depend on another task, because task
shutdown order is not guaranteed. Here, by making tasks depend on a
nontask object, we eliminate the potential race condition.
How to understand it?
public abstract class IntGenerator {
private volatile boolean canceled = false;
public abstract int next();
public void cancel() { canceled = true; }
public boolean isCanceled() { return canceled; }
}
public class EvenChecker implements Runnable {
private IntGenerator generator;
private final int id;
public EvenChecker(IntGenerator g, int ident) {
generator = g;
id = ident;
}
public void run() {
while(!generator.isCanceled()) {
int val = generator.next();
if(val % 2 != 0) {
System.out.println(val + " not even!");
generator.cancel();
}
}
}
// ...
}
A race condition occurs when two or more tasks start parallel and, depending on which task comes first, cause your program to react differently, inexpectedly or even crash. Without appropriate precautions (ExecutorService, for example) you can't control the order entirely as the underlying operating system always is the last to decide then.
For example. Your have an
ArrayList<String> listA
and you have 3 independed Runnables.
Runnable A is supposed to add 20 Strings to that list.
Runnable B has to put them all to lower case.
Runnable C drops duplicates.
Starting them parallel would cause chaos.
Maybe the wanted order is given. Then the expected result will be a list with no duplicates and all Strings have lower case.
But what if Runnable C comes first and even B is faster than A?
Then your listA would neither be free from duplicates nor would your Strings be brought to lower case.
This is what race condition is generally about. (put in simple words)
So back to your example.
Would IntGenerator be a Runnable too, you'd surely have a lot of trouble to harmonize both Runnables to interact properly with each other. I wouldn't go that far to say that it is impossible, but troublesome.

How to wait for some period of time and after that just return default value?

I have below code which tells me whether my data is PARTIAL or FULL. It works fine most of the time.
public static String getTypeOfData {
DataType type = new SelectTypes().getType();
if (type == DataType.partial || type == DataType.temp) {
return "partial";
}
return "full";
}
But sometimes, this line DataType type = new SelectTypes().getType(); just hangs and it keeps on waiting forever. This code is not in my control as it is developed by some other teams.
What I want to do is if this line DataType type = new SelectTypes().getType(); takes more than 10 second (or any default number of second), my method should return back a default string which can be partial.
Is this possible to do by any chance? Any example will help me to understand better.
I am using Java 7.
The ExecutorService provides methods which allow you to schedule tasks and invoke them with timeout options. This should do what you are after, however, please pay attention since terminating threads could leave your application in an inconsistent state.
If possible, you should contact the owners of the API and ask for clarification or more information.
EDIT: As per your comment, would caching be a possibility? Meaning that on start up, or some other point, you application goes through the SelectTypes and gets their type and stores them. Assuming that these do not change often, you can save them/update them periodically.
EDIT 2: As per your other comment, I cannot really add much more detail. You would need to add a method call which would allow your application to set these up the moment it is launched (this will depend on what framework you are using, if any).
A possible way would be to make the class containing the getTypeOfData() method as a Singleton. You would then amend the class to pull this information as part of its creation mechanism. Lastly, you would then create a Map<String, Type> in which you would throw in all your types. You could use getClass().getName() to populate the key for your map, and what you are doing now for the value part.
If you are not well aware of executor service then the easiest way to achieve this is by using Thread wait and notify mechanism:
private final static Object lock = new Object();
private static DataType type = null;
public static String getTypeOfData {
new Thread(new Runnable() {
#Override
public void run() {
fetchData();
}
}).start();
synchronized (lock) {
try {
lock.wait(10000);//ensures that thread doesn't wait for more than 10 sec
if (type == DataType.partial || type == DataType.temp) {
return "partial";
}else{
return "full";
}
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
return "full";
}
private static void fetchData() {
synchronized (lock) {
type = new SelectTypes().getType();
lock.notify();
}
}
You might have to do some little changes to make it work and looks better like instead of creating new thread directly you can use a Job to do that and some other changes based on your requirement. But the main idea remains same that Thread would only wait for max 10 sec to get the response.

How to create a Java function which Once called, cannot be called Again unless there is some DELAY?

I'm trying to make a function which can ONLY be called again after there is some amount of time delay between the two calls, (Say 5 seconds).
I require this functionality for an android app I'm creating.
Since it is possible that the user would be calling that function too frequently within a few seconds, it would destroy his experience. Hence, I'm desperately looking for an answer on this.
public void doSomethin(){
//code here which makes sure that this function has not been called twice within the specified delay of 5 seconds
//Some code here
}
Any help would be awesome!
Adit
You could hold the time in milliseconds and check if the current time is greater than or equal to the previous time + 5 seconds. If it is, execute the method and replace the previous time with the current time.
See System.currentTimeMillis()
public class FiveSeconds {
private static Scanner scanner = new Scanner(System.in);
private static long lastTime = 0;
public static void main(String[] args) {
String input = scanner.nextLine();
while(!input.equalsIgnoreCase("quit")){
if(isValidAction()){
System.out.println(input);
lastTime = System.currentTimeMillis();
} else {
System.out.println("You are not allowed to do this yet");
}
input = scanner.nextLine();
}
}
private static boolean isValidAction(){
return(System.currentTimeMillis() > (lastTime + 5000));
}
}
If the code runs on your main thread, Thread.sleep(5000) is not an option. The easiest way to go then would be:
private long previous = 0;
public void doSomething() {
long now = Calendar.getInstance().getTimeInMillis();
if (now - previous < 5000)
return;
previous = now;
// do something
}
use a static field, which saves the datetime of last execution and before executing check the current datetime against this timestamp.
I won't write code for you but if you think a bit about this it's not that hard. You want to make sure it's not called before 5 seconds has passed since last function call. Let's split this into parts.
1) Get current time
2) Compare to stored time that keeps it value between calls.
3) If less than 5 seconds has passed don't do anything
4) Otherwise store the new value and do stuff.
I never did coding in Android. But if Android has threads (which is most likely, it does). Then within this function sleep the thread for 5 seconds, it means even though it is called, it won't be executed further until 5 seconds are passed
public void doSomething()
{
Thread.sleep(5000); // Please find the corresponding Android method
}
make doSomethin() as a private method.
Expose another function say exposedDoSomething().
public void exposeDoSomething(){
// Add to a queue
}
In a separate thread read the queue in every 5 mins and call doSomethin()
Maybe a TimerTask will help you, more details here:
TimerTask|Android Developers
Example:
private TimerTask tiemrTast= new TimerTask() {
#Override
public void run() {
}
};
And then use this method: public void scheduleAtFixedRate (TimerTask task, long delay, long period)
One problem is that you'll have to have a session level timer for each and every user. This could be a fair amount of overhead depending on how many simultaneous users you have.
It's easy for one user: start a timer on request. It's distinguishing between users that's the problem. Your service is now stateful, which is usually a bad thing. You're giving away idempotence.
You could also maintain state in a database. Don't worry about calls; check persistent operations to make sure they don't happen too frequently.
It's not clear to me whether you mean to exclude all users for five seconds once the method is called by anyone, or if every user is prevented from calling the method again for five seconds once it's called the first time.
This sounds like a throughput killer. I'd reconsider this design.
you can use hander.postDalayed method to call method to run after specific delay
you can use your method something like this
int delay=5000;
int k;
int iDelayTimeInMiliSeconds=2000;
for( k=0;k<arrBatch.size();k++)
{
delay=delay+iDelayTimeInMiliSeconds;
callAllDocumentList(arrBatch.get(k),k,delay);
}
public void callAllDocumentList(final String strInvoiceId,final int count,int delay)
{
mHandler.postDelayed(new Runnable()
{
#Override
public void run()
{
// call your function here that you want to call after specific delay
//getOrderDetails(strInvoiceId,count,true);
}
}, delay);
}

Decrement at Regular Intervals in Java

I'm writing an application in Java, but need to know how to subtract from a variable once every second. What's the easiest way to do this? Thanks!
The name of the very Java class you need to use to do repeating operations is already sitting there in one of your tags! ;)
While the Timer class will work, I recommend using a ScheduledExecutorService instead.
While their usage is extremely similar, ScheduledExecutorService is newer, more likely to receive ongoing maintenance, fits in nicely with other concurrent utilities, and might offer better performance.
class YourTimer extends TimerTask
{
public volatile int sharedVar = INITIAL_VALUE;
public void run()
{
--sharedVar;
}
public static void main(String[] args)
{
Timer timer = new Timer();
timer.schedule(new YourTimer(), 0, 1000);
// second parameter is initial delay, third is period of execution in msec
}
}
Remeber that Timer class is not guaranteed to be real-time (as almost everything in Java..)
What are you trying to achieve? I would not try relying on the timer to properly fire exactly once per second. I would simply record the start time, and whenever a timer fires, recalculate what the value of the variable should be. Here's how I would do it...
class CountdownValue {
private long startTime;
private int startVal;
public CountdownValue(int startVal)
{
startTime = System.currentTimeMillis();
}
public int getValue()
{
return startVal - (int)((System.currentTimeMillis() - startTime)/1000);
}
}
Use a java.util.Timer to create a TimerTask.

Categories

Resources