Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Сhallenge BlockingQueue | Synchronized Collections
Multithreading in Java
course content

Зміст курсу

Multithreading in Java

Multithreading in Java

1. Multithreading Basics
2. Synchronized Collections
3. High-level Synchronization Mechanisms
4. Multithreading Best Practices

bookСhallenge BlockingQueue

Task

You'll just need to implement some BlockingQueue methods to better understand how the collection itself works and to better learn the material!

You need to go to BlockingQueueueImpl, in the class itself there will be 2 unrealized methods that you need to implement yourself. You don't need to come up with some complicated solution, you just need to repeat the functionality of a regular BlockingQueueue.

Note

You also have a Main class in which you will have to test your BlockingQueueueImpl to make sure it works correctly.

You can check this by adding more than 10 items to the queue (or more than the limit you initialized in the constructor) and the next item will have to wait until there are less items in the queue than the limit and only then write the next item.

put() - synchronized method that adds items to the queue if the queue limit is not exceeded, if it is, it pauses the queue

take()- synchronized method that takes an item from the queue, returns it and removes it, if the queue is empty, pauses it

Solution Tip

To implement put() you should check if the queue is full, i.e. if it is not equal to limit and if it is, pause the thread. If it is not full, you should check the queue for emptiness(isEmpty()) and if the thread is empty call the method that releases all threads(notifyAll()). Then add the item to the queue.

To implement take() you need to check if the queue is empty, if it is empty you pause the thread (because there is nothing to read), if the queue is not empty you make another check for the list completeness and if the list size is equal to limit, then release all threads and return the first item in the queue (the one that was added later than the others).

Methods you will need to execute

  • wait() - pauses the thread;
  • notifyAll()- wakes up all threads that are paused;
  • queue.isEmpty() - Checks queue for empty (true - queue is empty).

After doing these methods and testing in the Main class, go to /src/test/java/BlockingQueueueImplTest.java and run all the tests.

If they run successfully, congratulations you did everything right! If not, you either have the wrong solution or you have changed something that should not have been changed.

Note

Also try to solve the problem yourself, but if you don't succeed and you want to know the answer, there is a link to the solution. Just don't just copy the code, but try to figure it out!

Все було зрозуміло?

Як ми можемо покращити це?

Дякуємо за ваш відгук!

Секція 2. Розділ 4
some-alt