Database lock

  • A database lock is a mechanism to protect a shared piece of data from getting updated by two or more database users at the same time.
  • When a single database user or session has acquired a lock then no other database user or session can modify that data until the lock is released.

Shared Lock

  • A shared lock is required for reading a data item and many transactions may hold a lock on the same data item in a shared lock.
  • Multiple transactions are allowed to read the data items in a shared lock.

Exclusive lock

  • An exclusive lock is a lock on any transaction that is about to perform a write operation.
  • This type of lock doesn’t allow more than one transaction and hence prevents any inconsistency in the database.
@Getter
@Setter
class Boy {
	String name;
	List<Candy> candies;
}
 
class Candy {
	String id;
	String name;
}
 
 
class Run {
	private static void main() {
		Boy boy = new Boy();
		// retrieval
		List<Candy> candies = boy.getCandies();
 
		// update/create
		Candy c1 = new Candy();
		c1.setId("01");
		c1.setName("Ruby");
 
		Candy c2 = new Candy();
		c2.setId("01");
		c2.setName("Ruby");
		
		List<Candy> newCandies = List.of(c1, c2);
		boy.setCandies(newCandies)
		
	}
}

Optimistic Locking