1

Hello I have this custom TimerTask :

public class TimerTaskPerso extends TimerTask {
private static boolean i =  false;
@Override
public void run() {
    System.out.println(i);
    if(i){
        System.out.println("m here");
        return;
    }
    i= true;
    System.out.println("ok");

    try {
        Thread.sleep(3000);
    } catch (InterruptedException ignored) {

    }
    System.out.println("bye");
    i= false;
}
}

And I am calling it like that :

new Timer().schedule(new TimerTaskPerso(), 1,500);

But the task keeps showing :

false
ok
bye
false
ok
false

I am supposed to see "m here" message, I tried this without creating Custom TimerTask and by using AtomicBoolean but same result.

Thanks in advance,

2 Answers 2

0

Why you are thinking it will print "m here" as output. You are setting i=false again. So it will not print that message. In order to print that message you should comment this line i= false;. After commenting this line the output in my IDE is:

false
ok
bye
true
m here
true
m here

Please go through these for more information on static variables: static variables in multithreading and this also Are static variables shared between threads?

Sign up to request clarification or add additional context in comments.

6 Comments

Please see my comment to @user7 response
You want that some other thread should see the updated i value as true, but it will not because static variable makes local cache and it won't reflect in other thread.
I don't know a cache mechanism behind static variables, can you explain more please
The link gave me interesting information about what I wanted to know, In fact variables values are not updated instantly unless they are synchronized, or they are volatile, please respond to the question with the link so I accept it
|
0

When the TimerTask's run method starts, i will be false. Then it is set to true. But after sleeping for 3 seconds, i is again set to false.

During the next run, i will start off as false. And this goes on..

You have to remove you last assignment to i to make it become true after the first run. With this, it will print m here on subsequent runs.

1 Comment

But when sleeping for 3000 millis, there will be other tasks executed at a rate of 1 every 500 millis, based on this, some run() calls should occurs while i is true, check the timer schedule I've included in the question

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.