perwendel / spark

A simple expressive web framework for java. Spark has a kotlin DSL https://github.com/perwendel/spark-kotlin
Apache License 2.0
9.64k stars 1.56k forks source link

Example on books on README.md (front page of github) has bugs #1142

Open mbauer7532 opened 5 years ago

mbauer7532 commented 5 years ago

I believe the second example in README.md on books that you have on the github front page has bugs in that it is not thread safe and it does not respect the Java memory model. You have a global variable called:

private static Map<String, Book> books = new HashMap<String, Book>();

and all commands read and write to it. First this is not thread safe you you will likely end up with a jumped map in case of concurrent requests.

Secondly even if your requests are not concurrent, there is no guarantee that all requests are executed by the same thread. So if one thread writes a book to the map (and finishes), and then another thread tries to execute a GET, there is no guarantee from the java memory model that this second thread can see the changes made by the first.

Both problems can be fixed by making the books map Concurrent:

private static Map<String, Book> books = new ConcurrentHashMap<String, Book>();

I know you were simply trying to show an example and perhaps you are aware of the issues, but to show buggy code on the front page is not good form...