Question: Good day to all of you .

I have a Thread as shown below , which in its while true condition , continuously checks data inside a HashSet , if it present it extracts those and does something and incase there were no symbols for 5 minutes in HashSet (here is my question how can i keep such a condition in below else block is that possible )

```
package com;

import java.util.HashSet;

public class Tester extends Thread

{

    HashSet<String> set = new HashSet<String>();

    public void run() {

        while (true) {

            try {

                if (set.size() > 0) {

                    // extract those and do something
                    set.clear();
                }

                else {

                    // if there were no elements in set for more than 5 minutes than execute a task
                    // here is my question , to keep such a check is possible or not 

                }

                Thread.sleep(2000);
            } catch (Exception e) {

            }

        }
    }

    public static void main(String args[]) {
        try {
            Tester qT = new Tester();
            qT.start();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

```

Answer: 
You can initialize a timestamp before your loop. Then, if `set.size() > 0` is true, you update the timestamp to the current time. In the else you check whether the saved timestamp is at least 5 minutes older than the current timestamp. 

You probably want something like this:

```
package com;

import java.util.HashSet;
import java.util.Date;

public class Tester extends Thread
{
    HashSet<String> set = new HashSet<String>();

    public void run() {
        Date d = new Date();
        while (true) {
            try {
                if (set.size() > 0) {
                    d = new Date();
                    set.clear();
                }
                else {
                    if(new Date().getTime() - d.getTime() > 300000){
                        d = new Date();
                        //execute your method
                    }
                }

                Thread.sleep(2000);
            } catch (Exception e) {
            }
        }
    }

    public static void main(String args[]) {
        try {
            Tester qT = new Tester();
            qT.start();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

```
First, create a timer:

```
Timer timer = new Timer(300000, new ActionListener() {
    public void actionPerformed(ActionEvent event) {
        <preform the task here>
    }
});
timer.setRepeats(false);

```

When the thread starts, start the timer:

```
timer.start();

```

If there are items in the set:

```
timer.restart();

```

There is no need for an else, the timer takes care of that. You should check `timer.isRunning` in the main loop condition so the checks for set elements stop after 5 minutes.