C
C
Core Java
Search…
Operations you should care about
To safeguard your data, you might think you only need to worry about methods that modify the value of a variable. Think again. Methods that only read shared variable values can also return incorrect or inconsistent data.
Imagine that agents Shreya and Harry (two threads) manage renting an exhibition ground, say, Axiom (shared resource). Harry has agreed to rent it to a customer and is in the process of signing the legal papers (one thread is updating the shared resource). Shreya has no clue about this development. Just before Harry completes signing the rental agreement, Shreya receives an enquiry about the availability of Axiom and she confirms that it’s available (another thread reads data while the shared resource is being modified). In this case, Shreya accessed inconsistent data.
Similarly, threads that access shared objects can report inconsistent memory. Referring back to the previous example of class Book (with an instance variable copiesSold), imagine two threads are accessing the same Book instance. One thread updates the count of copiesSold and the other thread retrieves the value of copiesSold. If the second thread retrieves the value of copiesSold just before the first thread completes the modification, the second thread returns a dirty value that is inconsistent. For instance
In the preceding example, the thread enquire might read inconsistent data if it happens to execute eBook .getCopiesSold() before the thread buy executes eBook.newSale(). Depending on how the threads are scheduled, you might see either of the outputs shown in figure .
Probable outputs of class InconsistentMemory
Imagine a thread that produces data and another thread that consumes it. What happens if the producer thread lags behind, leaving the consumer thread without any data to process? Let’s work with this situation in the next section.
Last modified 2yr ago
Copy link