Search code examples
javacountdown

My countdown only drops by 1 and no more, why is that?


So , i want to create a countdown for a user inputed date in a service class.Right now i have problems with the countdown.It seems no matter what it only substracts 1 second and doesn't go further.Here is the code:

the logic for the countdown

package com.example.service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class CounterService {
    LocalDateTime dateTime;

    public LocalDateTime getDateTime(){
        return dateTime;
    }

    public void setDateTime(LocalDateTime dateTime) {
        this.dateTime = dateTime;
    }

    public LocalDateTime parseDate(String eventDate) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
        dateTime = LocalDateTime.parse(eventDate, formatter);
        return dateTime;
    }


    public static void main(String[] args) {

        CounterService cs = new CounterService();
        LocalDateTime a = LocalDateTime.of(2021,11,11,21,43,44);
        cs.setDateTime(a);

        Runnable r = new Counter(cs);
        new Thread(r).start();

    }
}

and the Runnable

package com.example.service;

import java.time.LocalDateTime;

public class Counter implements Runnable {
    CounterService counter;

    public Counter(CounterService cs) {
        this.counter = cs;
    }

    public void setCounter(CounterService cs) {
        this.counter = cs;
    }

    public void run() {
        LocalDateTime countFromThisDate = counter.getDateTime();
        try {
            boolean x = true;
            while (x) {
                LocalDateTime substracting = countFromThisDate.minusSeconds(1);
                Thread.sleep(1000);
                System.out.println(substracting);
            }
        } catch (InterruptedException ex) {
            ex.printStackTrace();
        }
    }
}

also how will i be able to add this counter (after it works) so that it refreshes dynamically and substracts each second one by one?


Solution

  • LocalDateTime is immutable.

    countFromThisDate.minusSeconds(1) returns a new instance, it does not update the instance it is called upon. You'd need to assign the result back to somewhere (for example by calling setDateTime on your service).

    This works just like as it does with String.

    That service also needs to be made thread-safe (for this, you should probably move the substraction logic into the service itself, so that it can become atomic instead of get/subtract/set).