Results 1 to 16 of 16
  1. #1
    GRPsuper9 is offline Member
    Join Date
    May 2015
    Posts
    16
    Rep Power
    0

    Default Multithreading (Background Task)

    Hey guys,

    I'm trying to make a program with a task that runs in the background of the main thread. This background task is in an infinite loop and checks for an object's getTime value in an ArrayList. It compares it to the current time and if they match, I want it to notify the user. It's for a "reminder" program I'm creating. The problem I'm having is that when I add a new item to the reminders ArrayList, the reminders.isEmpty() is false, but the program doesn't print the System.out.println("aaaa");. But when I uncomment the System.out.println("asdf");, it prints the "aaaa" once the value is false.

    Could anyone help me fix this and explain why this is happening so I can avoid this mistake in the future? Thanks!

    Java FX Code:
        @FXML
        private TableView<Reminder> tblReminders;
        @FXML
        private TableColumn<Reminder, String> colDate;
        @FXML
        private TableColumn<Reminder, String> colReminder;
        @FXML
        private Button btnAdd;
        
        private ObservableList<Reminder> reminders = FXCollections.observableArrayList();
        @FXML
        private DatePicker dpDate;
        @FXML
        private ComboBox cmbHour;
        @FXML
        private ComboBox cmbMinute;
        @FXML
        private ComboBox cmbAMPM;
        @FXML
        private TextArea txtReminder;
        /**
         * Initializes the controller class.
         */
        @Override
        public void initialize(URL url, ResourceBundle rb) {
                    
            colDate.setCellValueFactory(new PropertyValueFactory<>("date"));
            colReminder.setCellValueFactory(new PropertyValueFactory<>("reminder"));
            
            tblReminders.setItems(reminders);
            
            //reminders.add(new Reminder("2015/05/29 05:30:00 AM", "test"));
            
            //create a background task
            Task task = new Task() {
                @Override
                protected Object call() throws Exception {
                    while (true) {
                        Date currentTime = new Date();                    
                        if (reminders.isEmpty() == true) {
                            //System.out.println("asdf");
                        } else {
                            System.out.println("aaaa");
                        }
                    }
                }
                
            };
                    
            //assign that background task to a thread and start it
            Thread th = new Thread(task);
            th.setDaemon(true);
            th.start();
            
        }    
    
        @FXML
        private void btnAddClick(ActionEvent event) {        
            reminders.add(new Reminder(dpDate.getValue() + " " + cmbHour.getValue() + ":" + cmbMinute.getValue() + ":00 " + cmbAMPM.getValue(), txtReminder.getText()));
        }

  2. #2
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    19,965
    Rep Power
    31

    Default Re: Multithreading (Background Task)

    Using a while(true) loop is a big waste of resources. Try another design.
    For example: order the events by time and have a Timer wait for the time of the next event.
    If you don't understand my response, don't ignore it, ask a question.

  3. #3
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    6,226
    Rep Power
    13

    Default Re: Multithreading (Background Task)

    You might want to investigate the ExecutorService classes in the java.util.concurrent package.

    Regards,
    Jim
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

  4. #4
    GRPsuper9 is offline Member
    Join Date
    May 2015
    Posts
    16
    Rep Power
    0

    Default Re: Multithreading (Background Task)

    Quote Originally Posted by jim829 View Post
    You might want to investigate the ExecutorService classes in the java.util.concurrent package.

    Regards,
    Jim
    I saw something about that on the thread that I was reading when I was researching multithreading. It didn't go into any detail about it though and I did some more research but couldn't find anything useful to me. Would this be the correct way to execute that method?
    Java FX Code:
            //create a background task
            Task task = new Task() {
                @Override
                protected Object call() throws Exception {
                    while (true) {
                        Date currentTime = new Date();                    
                        if (reminders.isEmpty() == false) {
                            System.out.println("aaaa");
                        }
                    }
                }
                
            };
                    
            //assign that background task to a thread and start it
            ExecutorService exectService = Executors.newFixedThreadPool(1);
            exectService.submit(task);
    By doing that code, it still doesn't display "aaaa" when I click the button to add a new item.

    I feel like what is happening is that it is initially submitting the reminders array to the task and executing it, but when I add a new item to the reminders array, it updates on my class' level but doesn't update it on the task, thus, the task thinking its still the old reminders array from when it was first initialized.
    Last edited by GRPsuper9; 06-01-2015 at 02:57 PM.

  5. #5
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    19,965
    Rep Power
    31

    Default Re: Multithreading (Background Task)

    The code still has the wasteful while(true) loop. The design should be changed to get rid of that loop.
    If you don't understand my response, don't ignore it, ask a question.

  6. #6
    GRPsuper9 is offline Member
    Join Date
    May 2015
    Posts
    16
    Rep Power
    0

    Default Re: Multithreading (Background Task)

    Quote Originally Posted by Norm View Post
    The code still has the wasteful while(true) loop. The design should be changed to get rid of that loop.
    How would I change that while loop to something else so that my program would check the current time of the machine to the specific time a user inputs to be alerted at? I know this isn't proper syntax, but for demonstration purposes,
    Java FX Code:
    if (Date.now() == reminders.getDate()) {}
    I feel like I would need to check every moment if that statement is true since the value of Date.now() keeps changing.

  7. #7
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    19,965
    Rep Power
    31

    Default Re: Multithreading (Background Task)

    How would I change that while loop
    You wouldn't change the loop, you'd replace it with different logic.
    Use a Timer that waits for the time of the next event. When the Timer expires, start the event processor and start a new Timer for the next event. If a new event is added that is sooner than the current event, stop the Timer and restart it with the time to the new event. The events in the queue would be in time order, next one on top.
    If you don't understand my response, don't ignore it, ask a question.

  8. #8
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    6,226
    Rep Power
    13

    Default Re: Multithreading (Background Task)

    I looked more closely at the concurrent thread classes and don't believe they will easily solve your problem. I agree with Norm's approach. A suggestion would be to use a SortedSet or SortedMap implementation that is sorted based on the natural ordering of the key (which could be the desired date at some granularity). That way, the first element can be used to establish the timer for inspecting the set or map. Note: A map offers the advantage of maintaining a list of tasks that are scheduled to run at the same date or time. But using either could work.

    Regards,
    Jim
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

  9. #9
    GRPsuper9 is offline Member
    Join Date
    May 2015
    Posts
    16
    Rep Power
    0

    Default Re: Multithreading (Background Task)

    I ended up using the Timeline class to achieve what I was trying to do. This is working fine for me. Thanks for the advise. I tried using the timer class but I couldn't find examples of it with the way that I wanted to use it.
    Java FX Code:
        @Override
        public void initialize(URL url, ResourceBundle rb) {
                    
            colDate.setCellValueFactory(new PropertyValueFactory<>("date"));
            colReminder.setCellValueFactory(new PropertyValueFactory<>("reminder"));
            
            tblReminders.setItems(reminders);
            
            String strNum;
            for (int i = 0; i <= 59; i++) {
                if (i < 10) {
                    strNum = "0" + i;
                } else {
                    strNum = String.valueOf(i);
                }
                
                if (i <= 12 && i >= 1) { //add the hours
                    cmbHour.getItems().add(strNum);  
                }
              
                cmbMinute.getItems().add(strNum); //add the minutes
            }
            
            cmbAMPM.getItems().addAll("AM", "PM");
            
            timeline = new Timeline(new KeyFrame( 
                    Duration.millis(1000),
                    ae -> checkReminders()));
            timeline.setCycleCount(Timeline.INDEFINITE);
            timeline.play();
        }    
        
        private void checkReminders() {
            if (reminders.isEmpty() == false) {
                Date date = new Date();
                for (Reminder reminder : reminders) {
                    if (canContinue) {
                        if (date.getTime() >= Date.parse(reminder.getDate()) - 1000 && date.getTime() <= Date.parse(reminder.getDate())) {
                            System.out.println(reminder);
                        }
                    }
                }
            }
        }
    Last edited by GRPsuper9; 06-02-2015 at 03:32 AM.

  10. #10
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    19,965
    Rep Power
    31

    Default Re: Multithreading (Background Task)

    What package is the Timeline class in? I don't see it in the Java SE classes.
    If you don't understand my response, don't ignore it, ask a question.

  11. #11
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    6,226
    Rep Power
    13

    Default Re: Multithreading (Background Task)

    Quote Originally Posted by Norm View Post
    What package is the Timeline class in? I don't see it in the Java SE classes.
    The OP forgot to mention that s/he is using JavaFX. I had to search the web to find the class.

    Regards,
    Jim
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

  12. #12
    DarrylBurke's Avatar
    DarrylBurke is offline Forum Police
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    12,059
    Rep Power
    25

    Default Re: Multithreading (Background Task)

    Moved from Advanced Java to JavaFX.

    db
    If you're forever cleaning cobwebs, it's time to get rid of the spiders.

  13. #13
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    13,541
    Rep Power
    26

    Default Re: Multithreading (Background Task)

    Quote Originally Posted by jim829 View Post
    The OP forgot to mention that s/he is using JavaFX. I had to search the web to find the class.

    Regards,
    Jim
    Well, it is mentioned in the OP, to give them some dues...just not exactly front and center.
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  14. #14
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    6,226
    Rep Power
    13

    Default Re: Multithreading (Background Task)

    Quote Originally Posted by Tolls View Post
    Well, it is mentioned in the OP, to give them some dues...just not exactly front and center.
    Yeah. And as I re-read this I saw the code tags for JavaFX code. I must have been asleep.

    Regards.
    Jim
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

  15. #15
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    19,965
    Rep Power
    31

    Default Re: Multithreading (Background Task)

    I'm not familiar with JavaFX. Can JavaFX programs use Java SE classes like Thread, Timer and PriorityQueue?

    The OPs solution is slightly better than a forever while loop but still is spinning its wheels a lot by checking every second for a new entry.
    If you don't understand my response, don't ignore it, ask a question.

  16. #16
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    13,541
    Rep Power
    26

    Default Re: Multithreading (Background Task)

    A quick nose at FX to remind myself, but Timeline is an animation class...

    FX has a proper scheduling class:
    ScheduledService.
    Please do not ask for code as refusal often offends.

    ** This space for rent **

Similar Threads

  1. Doing background task in Swing application
    By Heatryn in forum Advanced Java
    Replies: 2
    Last Post: 07-05-2012, 01:27 AM
  2. SwingWorker background task pause
    By madroadbiker in forum Advanced Java
    Replies: 5
    Last Post: 05-07-2011, 07:00 PM
  3. multithreading
    By praveenbhushan1989 in forum Threads and Synchronization
    Replies: 8
    Last Post: 04-17-2011, 03:03 PM
  4. multithreading
    By praveenbhushan1989 in forum Threads and Synchronization
    Replies: 15
    Last Post: 03-01-2011, 01:17 AM
  5. multithreading
    By shilpa.krishna in forum New To Java
    Replies: 2
    Last Post: 06-27-2008, 04:18 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •