Reference articles:
http://blog.csdn.net/aesop_wubo/article/details/8286215
http://www.aichengxu.com/view/24054
A recent encounter with the deadlock problem that arose in the domain class itself was plagued for several days,
After the resolution found too simple, really unexpected ah ...
When I hit a deadlock, the key code for the domain class is as follows, turning the database day table to find the columns that are generated by the association: parent_id
Class Day {
String Name
static Belongsto = [Parent:day]
static Hasmany = [Children:day]
}
The service code for Operation Day is simplified as follows
@Transactional
Class Dayservice {
Note: The Saveday method is invoked by multiple threads at the same time.
Parameter day is new in each thread,
So parameter day is thread-safe
Saveday (Def Day) {
This line of code may acquire the same dayparent when it is called at the same time by more than one thread
Here it is necessary to note that it is possible for multiple threads to manipulate the same row record in the database at the same time
def dayparent = GetParent (day.name)
The following line of code is generated: Deadlock found when trying to get lock; Try restarting transaction
Reason: Multiple threads simultaneously manipulate the same row record in the database, creating a deadlock while waiting for each other
Dayparent.addtochildren (dayparent)
}
Day GetParent (String name) {
Def day = day.where {
Name = = Name
}.get ()
Return Day
}
}
------------------------------------------------------------------
Workaround:
Note: The Saveday method is invoked by multiple threads at the same time.
Parameter day is new in each thread,
So parameter day is thread-safe
Saveday (Def Day) {
This line of code may acquire the same dayparent when it is called at the same time by more than one thread
Here it is necessary to note that it is possible for multiple threads to manipulate the same row record in the database at the same time
def dayparent = GetParent (day.name)
Dayparent.addtochildren (dayparent)//comment out the line code
Day.parent = dayparent//day is thread safe, so write can also achieve a class autocorrelation purposes, but also very reliable, why not ...
}