Java Threads
Operating Systems
Lab Class 3 – Model Solutions
1 Exercise (a): Primes
Primes.java
1
PrimesTask.java
Reflections: 1. No.
2. If the program has to react to user inputs. In this case the computation can be done in the background.
2 Exercise (b): Letters
Letters.java
LettersTask.java
Reflections:
1. Data parallelism.
2. Ask the lab tutor for feedback on your experiences.
3. To record whether a word exists we only had to set a value to true in the shared data
structure. Even though there is a concurrent write, there is no race condition because all writing threads write the same value. However, when we count the number of words we have to increment the value in the shared data structure. That means that we have to read and write the data, which can cause a race condition. Therefore synchronisation is required to be thread safe.
NB: Data structures such as HashMap are not thread-safe even when the threads write to different elements! Always read carefully the documentation of the Java Library to understand the limitations of the data structures that you are using.