How it works...

In this recipe, we implemented the Event class. This class has a unique attribute, the activation date of the events, and it implements the Delayed interface. You can store Event objects in the DelayQueue class.

The getDelay() method returns the number of nanoseconds between the activation date and the actual date. Both dates are objects of the Date class. You used the getTime() method that returns a date converted into milliseconds. Then, you converted this value into TimeUnit, which was received as a parameter. The DelayQueue class works in nanoseconds, but at this point, it's transparent to you.

The compareTo() method returns a value less than zero if the delay of the object executing the method is smaller than the delay of the object passed as a parameter. It returns a value greater than zero if the delay of the object executing the method is bigger than the delay of the object passed as a parameter. It returns 0 if both the delays are equal.

You also implemented the Task class. This class has an integer attribute named id. When a Task object is executed, it adds the number of seconds that is equal to the ID of the task to the actual date, and this refers to the activation date of the events stored by this task in the DelayQueue class. Each Task object stores 100 events in the queue using the add() method.

Finally, in the main() method of the Main class, you created five Task objects and executed them in their corresponding threads. When these threads finished their execution, you wrote all the events using the poll() method in the console. This method retrieves and removes the first element of the queue. If the queue does not have any active element, it returns the null value. You call the poll() method, and if it returns an Event class, you increment a counter. When it returns the null value, you write the value of the counter in the console and put the thread to sleep for half a second to wait for more active events. When you obtained the 500 events stored in the queue, the execution of the program finished.

The following screenshot shows part of the output of an execution of the program:

You can see how the program only gets 100 events when it is activated.

You must be very careful with the size() method. It returns the total number of elements in the list that includes both active and non-active elements.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.137.184.102