1

Is there any way to create kind of transactions using only Java SE? For example, we have some class with main and an input method. What we do is putting in console some numbers, adding'em to a list and then return this list. But, if user doesn't put any number in console for a 5 sec - program clears out our list, returns this empty list and stops.

And dummy code for example:

public class SomeClass {
    public static void main(String[] args) {
        inputNumbers().forEach(System.out::println);
    }

    public List<String> inputNumbers() {
        Scanner scanner = new Scanner(System.in);
        List<String> result = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            result.add(scanner.nextLine());

            //if nothing happen within 5 sec
            //result.clear();
            //return out empty result;    
        }

        return result;
    }
}

2 Answers2

1

Take a look into the Java TimerTask class documentation. There are provided methods for executing such things on a schedule.

Dustin
  • 693
  • 8
  • 20
1

Here is one option using Timer task and AWT Robot.

public class SomeClass {

    private volatile boolean exitFlag = false;

    public static void main(String[] args) {
        new SomeClass().inputNumbers().forEach(System.out::println);
    }

    public List<String> inputNumbers() {
        Scanner scanner = new Scanner(System.in);
        List<String> result = new ArrayList<>();
        Timer t = setTimer(5000);
        for (int i = 0; i < 10; i++) {
            result.add(scanner.nextLine());
            if(exitFlag) {
                break;
            }
        }
        scanner.close();
        t.cancel();
        return result;
    }

    private Timer setTimer(int delay) {
        Timer t = new Timer();
        t.schedule( 
                new java.util.TimerTask() {
                    @Override
                    public void run() {
                        Robot robot;
                        try {
                            robot = new Robot();
                            robot.keyPress(KeyEvent.VK_ENTER);
                            exitFlag = true;
                        } catch (AWTException e) {
                            e.printStackTrace();
                        }

                    }
                }, 
                delay 
        );
        return t;
    }
}
vmaroli
  • 613
  • 9
  • 21