Today finally again picked up the Java Concurrency in practice, before the abuse of the pieces, before reading this book, there is a part of their own code I did not realize that the thread is not safe, but also really want to be bad to fill this knowledge.
1.Java Monitor Mode
Monitor mode is very simple, is to use a private object lock or built-in lock to ensure the thread security of the owning object. An example is introduced here: Vehicle tracking
Public classMonitorvehicletracker {Private FinalMap<string, mutablepoint>locations; PublicMonitorvehicletracker (map<string, mutablepoint>locations) { This. Locations =locations; } Public synchronizedMap<string, mutablepoint>getlocations () {returndeepcopy (locations); } Public synchronizedmutablepoint getLocation (String id) {Mutablepoint loc=locations.get (ID); returnLOC = =NULL?NULL:Newmutablepoint (Loc); } Public voidsetlocation (String ID,intXinty) {mutablepoint loc=locations.get (ID); if(loc = =NULL) Throw NewIllegalArgumentException ("No such ID:" +ID); loc.x=x; Loc.y=y; } Private StaticMap<string, mutablepoint> deepcopy (map<string, mutablepoint>m) {Map<string, mutablepoint> result =NewHashmap<>(); for(String id:m.keyset ()) Result.put (ID,NewMutablepoint (M.get (ID))); returnCollections.unmodifiablemap (result);}
Here Mutablepoint is a mutable class, which is thread insecure:
Public class Mutablepoint { publicint x, y; Public Mutablepoint () {x = 0; y = 0;} Public mutablepoint (Mutablepoint p) { this. x = p.x; this. y = p.y; }}
The attentive reader must have found that almost every method in the Monitorvehicletracker class replicates the value of mutablepoint or locations, because the two are not thread-safe and cannot be published directly, so only one copy can be published. But this again
A new problem: Although the Monitorvehicletracker class is thread-safe, because the data is replicated, assume that thread A calls the Getlocations () method to get the position, where the car's position changes, and thread B calls setlocation () Internal variables have been modified
locations, the location of the vehicle has been modified, but thread a returns the old location. Of course, this is a good thing to keep the data consistent, but if you want to get the real-time location of the vehicle, you have to get the latest snapshot of the vehicle's location.
The above method can cause serious performance problems. So how to improve it? Here I give a hint: the reason for copying data is because the property is thread insecure and cannot be published directly, so if you publish a thread-safe property, does it solve the problem of real-time?
Java Concurrency in practice 4.1-4.2 related issues and understanding