1 First, let's look at the difference between optimistic and pessimistic locking lock 2 3 optimistic locking general idea is to increase table version field, where the statement added version of the judgment of updates, be regarded as a CAS (Compare And Swep) operation, 4 commodities Stock scenario plays a version control number (corresponding version) action (the AND number = # {number}). 5 6 pessimistic lock reason is pessimistic, he believes that this operation complicated by conflict, so the outset of goods plus the lock (the SELECT ... the FOR UPDATE), 7 then you can feel at ease with judgment and update, because this time others will not have to update this commodity stocks. 8 9 from which we can know that as long as the updated data is data dependent read as a basic condition, there will be concurrent update problem, you need to take the optimistic locking or pessimistic locking to solve, 10 special performance was really counts. Another example is not dependent data queries in the update data will not be a problem, 11 such as to modify the user's name, people also modify the results are not dependent on the user's name before, this would not have concurrent update problem. 12 is 13 is 14 ================================ 15 . 1 . Pessimistic lock 16 . 17 As the name suggests is very pessimistic, each time to take the data will be considered by another thread modifies the data, the data will be locked; 18 19 so grab a thread running lock, take the data to do the operation, 20 21 other threads want this period when accessing the data block are blocked pending state, can not operate; 22 is 23 is the core that does not support multiple concurrent, single-threaded operation, by time slice manner using preemption right rob lock, the concurrent serial into . 24- 25 shared resources using a time to a thread, other thread is blocked, and then run out the transfer of resources to other threads. 26 Scenario: 27 28 pessimistic locking apply to write the scene to ensure the safety and data security thread 29 30 MySQL row locks, table locks, read locks, write locks; 31 32 the Java is synchronized. 33 is 34 is ================================= 35 2 . Optimistic locking 36 37 [ name suggests is very optimistic, took each data are considered another thread does not modify the data, so the data will not be locked; 38 39 But when the judge will look at the data update, during which other threads do not have to update the data, and finally get the ultimate value of the data by individually update multiple threads; 40 scenarios: 41 42 optimistic locking for multi-reading scene to obtain data not create, destroy the lock, the lock reducing overhead, increasing data throughput, 43 44 Redis and other non-relational database 45 46 PS: Redis is single-threaded operation, the transaction closed in a single thread, avoid the issue of thread safety, so there is no increase pessimistic locking; 47 48 but for Redis operations rely more complex operations, still need to lock, and there may be a distributed lock, you can also use LUA script, with problem-solving task queue multiple tasks concurrently. 49 50 51 is 52 is 53 is pessimistic locking on ======================== SQlserver solution ============== ================ 54 HTTPS: // blog.csdn.net/gudenren/article/details/4397291 55 56 === "" "pessimistic locking solutions 57 58@CardNo VARCHAR DECLARE ( 20 is ) 59 the Begin Tran 60 61 is - card selecting an unused 62 is SELECT Top . 1 @ CardNo = F_CardNo 63 is from Card with (the UPDLOCK) WHERE F_Flag = 0 // --- = 0 indicates no F_Flag this card was registered to use 64- 65 - delayed 50 seconds to simulate concurrent access. 66 waitfor delay ' 000: 00: 50 ' 67 68 - to just select out the card to register. 69 70 Update card 71 the SET F_Name = User, 72= F_Time getdate (), 73 F_Flag = 1 74 the WHERE F_CardNo = @CardNo 75 76 the commit 77 78 focus on the difference between them yet? With (UPDLOCK), yes, when we use the query with (UPDLOCK) option, Search record when 79 we recorded together with an update lock, to express our upcoming second record to be updated. pay attention to update locks and shared locks are not in conflict, that is, other users can also 80 query the contents of this table, however, and update locks and exclusive locks are in conflict, so other users will be updated obstruction. If we execute this code in another window, 81 the same without waifor delay clause after both sides finished, we found two successfully registered Zhang card 82 may we have discovered the shortcomings of pessimistic locking: when a user transaction updates, updating other users must wait in line, even if the user updates a record is not the same. 83 84 85 86 87 ==== == "" "optimistic lock 88 optimistic locking solutions 89 90 - First, we in the Card Table inside plus a F_TimeStamp column, the column is varbinary ( 8 ) type but this value is automatically updated when the growth.. 91 92 the ALTER the Table Card F_TimeStamp the Add timestamp not null 93 94 - pessimistic lock 95 DECLARE @CardNo VARCHAR ( 20 is ) 96 DECLARE @timestamp a varbinary ( . 8 ) 97 DECLARE the @rowcount int 98 99 the Begin Tran 100 101 - to obtain the original number and timestamp value 102 SELECT Top . 1 @ CardNo = F_CardNo, 103 @timestamp = F_TimeStamp 104 from Card 105 WHERE F_Flag = 0 106 107 - . 50 seconds delay, simulated concurrent access 108 WAITFOR Delay ' 000: 00: 50 ' 109 110 - registration card, but to compare whether the timestamp if a change does not occur. changes. updated successfully. If a change occurs, the update fails. 111 112 update Card 113 SET F_Name = User, 114 F_Time = getdate (), 115 F_Flag = . 1 1 16 WHERE F_CardNo CardNo and F_TimeStamp = @ = @timestamp 117 SET @ rowCount = @ The @rowcount 118 IFrowCount = @ . 1 119 the begin 120 Print ' updated successfully! ' 121 the commit 122 End 123 the else IF @ rowCount = 0 124 the begin 125 IF EXISTS ( SELECT . 1 from Card WHERE F_CardNo = @CardNo) 126 the begin 127 Print ' card has been additionally a registered user! ' 128 ROLLBACK Tran 129 End 130. the else 131 is the begin 132 Print 'This card does not exist! ' 133 ROLLBACK Tran 134 End 135 End 136 137 executed in another window inside the code does not waitfor, the registration is successful, return to the original window, we will find the time to prompt it shows the card to 138 prompted by another registered user. obviously, we also can avoid two users register the phenomenon of a card. at the same time, 139 Another advantage of using this method is not used to update locks, so the increase . the concurrent processing capabilities of the system 140 141 summary: top I specifically describes the use of optimistic and pessimistic locking in the actual production environment inside, if not the amount of concurrency, 142 we can use pessimistic locking method, because this the method is easy to use and simple. but if concurrent system is very large, 143 pessimistic locking will bring very large performance problem, so we have to choose the method of optimistic locking.