Conteúdo do Curso
Multithreading in Java
Multithreading in Java
Challenge ConcurrentMap
Task:
Realization of multithreaded system of accounting of site visits.
Description:
It is necessary to create a program to keep track of the number of visits to different pages of the site. The program should work correctly in a multithreaded environment, where several threads can simultaneously increase visit counters for different pages.
Requirements:
- Use
ConcurrentHashMap
to store data about page visits; - Implement a method that increments the visit count for a given page.
incrementVisit()
; - Implement a method that returns the current visit count for a given page.
getVisitCount()
; - Create multiple threads that will increment the visit counts simultaneously. (This is implemented in the
Main
class, you need to figure out what's going on there).
Hints:
- Use
ConcurrentHashMap
to store data where the key is the URL of the page and the value is the visit count; - Use
compute()
ormerge()
methods to atomically update counters inConcurrentHashMap
.
You need to complete the methods in the PageVisitCounterImpl
class, and then run the tests in the PageVisitCounterTest
class.
After you have successfully completed the task, all tests should pass.
Note
After you have done everything correctly, you can try to edit the line where
ConcurrentMap
is declared in thePageVisitCounterImpl
class and see what happens.
That is, you need to replace this line here with the ConcurrentMap
implementation.
Main
private final ConcurrentMap<String, Integer> visitCounts = new ConcurrentHashMap<>();
On this one, with the realization of the usual Map
Main
private final Map<String, Integer> visitCounts = new HashMap<>();
Obrigado pelo seu feedback!