聊聊高并发(三十二)实现一个基于链表的无锁Set集合

Set表示一种没有重复元素的集合类,在JDK里面有HashSet的实现,底层是基于HashMap来实现的。这里实现一个简化版本的Set,有以下约束:

1. 基于链表实现,链表节点按照对象的hashCode()顺序由小到大从Head到Tail排列。

2. 假设对象的hashCode()是唯一的,这个假设实际上是不成立的,这里为了简化实现做这个假设。实际情况是HashCode是基于对象地址进行的一次Hash操作,目的是把对象根据Hash散开,所以可能有多个对象地址对应到一个HashCode,也就是哈希冲突,要做冲突的处理。常见的处理就是使用外部拉链法,在对应的Hash的节点再创建1个链表,相同HashCode的节点在这个链表上排列,再根据equals()方法来识别是否是同一个节点。这个是HashMap的基本原理。


有了以上假设,这篇从最简单的加锁的方式到最终的无锁展示一下如何一步一步演进的过程,以及最终无锁实现要考虑的要点。

1. 粗粒度锁

2. 细粒度锁

3. 乐观锁

4. 懒惰锁

5. 无锁


先看一下Set接口,1个添加方法,1个删除方法,1个检查方法

package com.lock.test;

public interface Set<T> {
	public boolean add(T item);
	
	public boolean remove(T item);
	
	public boolean contains(T item);
}

第一个实现的是使用粗粒度的锁,就是对整个链表加锁,这样肯定是线程安全的,但是效率肯定是最差的

链表节点类的定义,三个元素

1. 加入节点的元素

2. next指针指向下一个节点,明显这是个单链表结构

3. key表示item的HashCode

class Node<T>{
		T item;
		Node<T> next;
		int key;
		
		public Node(T item){
			this.item = item;
			this.key = item.hashCode();
		}
		
		public Node(){}
	}
粗粒度链表的实现

1. 链表维护了一个头节点,头节点始终指向最小的HashCode,头节点初始的next指针指向最大的HashCode,表示尾节点,整个链表是按照HashCode从小往大排列

2. 链表维护了一个整体的锁,add, remove, contains都加锁,保证线程安全,简单粗暴,但是效率低下

class CoarseSet<T> implements Set<T>{
		private final Node<T> head;
		private java.util.concurrent.locks.Lock lock = new ReentrantLock();
		
		public CoarseSet(){
			head = new Node<T>();
			head.key = Integer.MIN_VALUE;
			Node<T> MAX = new Node<T>();
			MAX.key = Integer.MAX_VALUE;
			head.next = MAX;
		}
		
		public boolean add(T item){
			Node<T> pred, curr;
			int key = item.hashCode();
			lock.lock();
			try{
				pred = head;
				curr = head.next;
				while(curr.key < key){
					pred = curr;
					curr = curr.next;
				}
				if(curr.key == key){
					return false;
				}
				Node<T> node = new Node<T>(item);
				node.next = curr;
				pred.next = node;
				return true;
			}finally{
				lock.unlock();
			}
		}
		
		public boolean remove(T item){
			Node<T> pred, curr;
			int key = item.hashCode();
			lock.lock();
			try{
				pred = head;
				curr = head.next;
				while(curr.key < key){
					pred = curr;
					curr = curr.next;
				}
				if(curr.key == key){
					pred.next = curr.next;
					curr.next = null;
					return true;
				}
				return false;
			}finally{
				lock.unlock();
			}
		}
		
		public boolean contains(T item){
			Node<T> pred, curr;
			int key = item.hashCode();
			lock.lock();
			try{
				pred = head;
				curr = head.next;
				while(curr.key < key){
					pred = curr;
					curr = curr.next;
				}
				return curr.key == key;
			}finally{
				lock.unlock();
			}
		}
	}

对粗粒度链表的优化可以细化锁的粒度,粗粒度锁的问题在于使用了一把锁锁住了整个链表,那么可以使用多把锁,每个节点维护一把锁,这样单个节点上锁理论上不会影响其他节点。

单链表最简单add操作需要做两步

1. 把新加入节点的next指向当前节点

2. 把前驱节点的next指向新加入的节点

node.next = curr;
pred.next = node

单链表的删除操作只需要做一步

pred.next = curr.next

如果使用细粒度锁的话,添加和删除操作要同时锁住两个节点才能保证添加和删除的正确性,不然有可能添加进来的节点指向了一个已经被删除的节点。所以需要同时控制两把锁,这也叫锁耦合,需要先获取前驱节点的锁,再获取当前节点的锁。

由于这种锁的获取是按照从前往后的顺序获取的,是一个方向的,所以不会引起死锁的问题。

死锁有两种:

1. 由获取锁的顺序引起的,顺序形成了环

2. 由资源问题引起的

来看看细粒度锁的实现,首先是带锁的Node


                
  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
好的,以下是基于模板的双向循环链表实现代码,注释详细: ```c++ #include <iostream> using namespace std; // 定义节点结构体 template<typename T> struct Node { T data; // 节点中存储的数据 Node<T>* next; // 指向下一个节点的指针 Node<T>* prev; // 指向前一个节点的指针 }; // 定义双向循环链表类 template<typename T> class DoublyLinkedList { private: Node<T>* head; // 头节点指针 Node<T>* tail; // 尾节点指针 int size; // 链表大小 public: // 构造函数 DoublyLinkedList() { head = nullptr; tail = nullptr; size = 0; } // 析构函数 ~DoublyLinkedList() { Node<T>* current = head; while (current != nullptr) { Node<T>* temp = current; current = current->next; delete temp; } size = 0; } // 获取链表大小 int getSize() { return size; } // 判断链表是否为空 bool isEmpty() { return size == 0; } // 在链表头部添加元素 void addFirst(T data) { Node<T>* newNode = new Node<T>; newNode->data = data; if (head == nullptr) { // 如果链表为空 head = newNode; tail = newNode; head->prev = tail; tail->next = head; } else { // 如果链表不为空 newNode->next = head; head->prev = newNode; head = newNode; head->prev = tail; tail->next = head; } size++; } // 在链表尾部添加元素 void addLast(T data) { Node<T>* newNode = new Node<T>; newNode->data = data; if (tail == nullptr) { // 如果链表为空 head = newNode; tail = newNode; head->prev = tail; tail->next = head; } else { // 如果链表不为空 newNode->prev = tail; tail->next = newNode; tail = newNode; head->prev = tail; tail->next = head; } size++; } // 在指定位置插入元素 void add(int index, T data) { if (index < 0 || index > size) { cout << "Index out of range." << endl; return; } if (index == 0) { // 在链表头部插入元素 addFirst(data); return; } if (index == size) { // 在链表尾部插入元素 addLast(data); return; } Node<T>* current = head; for (int i = 0; i < index - 1; i++) { current = current->next; } Node<T>* newNode = new Node<T>; newNode->data = data; newNode->next = current->next; current->next->prev = newNode; current->next = newNode; newNode->prev = current; size++; } // 删除链表头部元素 void removeFirst() { if (head == nullptr) { cout << "LinkedList is empty." << endl; return; } if (head == tail) { // 链表中只有一个节点 delete head; head = nullptr; tail = nullptr; } else { // 链表中有多个节点 Node<T>* temp = head; head = head->next; head->prev = tail; tail->next = head; delete temp; } size--; } // 删除链表尾部元素 void removeLast() { if (tail == nullptr) { cout << "LinkedList is empty." << endl; return; } if (head == tail) { // 链表中只有一个节点 delete tail; head = nullptr; tail = nullptr; } else { // 链表中有多个节点 Node<T>* temp = tail; tail = tail->prev; tail->next = head; head->prev = tail; delete temp; } size--; } // 删除指定位置的元素 void remove(int index) { if (index < 0 || index >= size) { cout << "Index out of range." << endl; return; } if (index == 0) { // 删除链表头部元素 removeFirst(); return; } if (index == size - 1) { // 删除链表尾部元素 removeLast(); return; } Node<T>* current = head; for (int i = 0; i < index; i++) { current = current->next; } current->prev->next = current->next; current->next->prev = current->prev; delete current; size--; } // 获取指定位置的元素 T get(int index) { if (index < 0 || index >= size) { cout << "Index out of range." << endl; return NULL; } Node<T>* current = head; for (int i = 0; i < index; i++) { current = current->next; } return current->data; } // 修改指定位置的元素 void set(int index, T data) { if (index < 0 || index >= size) { cout << "Index out of range." << endl; return; } Node<T>* current = head; for (int i = 0; i < index; i++) { current = current->next; } current->data = data; } // 打印链表 void printList() { if (head == nullptr) { cout << "LinkedList is empty." << endl; return; } Node<T>* current = head; while (current != tail) { cout << current->data << " "; current = current->next; } cout << current->data << endl; } }; int main() { // 创建双向循环链表对象 DoublyLinkedList<int> dll; // 在链表头部添加元素 dll.addFirst(1); dll.addFirst(2); dll.addFirst(3); dll.printList(); // 输出: 3 2 1 // 在链表尾部添加元素 dll.addLast(4); dll.addLast(5); dll.addLast(6); dll.printList(); // 输出: 3 2 1 4 5 6 // 在指定位置插入元素 dll.add(2, 7); dll.printList(); // 输出: 3 2 7 1 4 5 6 // 删除链表头部元素 dll.removeFirst(); dll.printList(); // 输出: 2 7 1 4 5 6 // 删除链表尾部元素 dll.removeLast(); dll.printList(); // 输出: 2 7 1 4 5 // 删除指定位置的元素 dll.remove(2); dll.printList(); // 输出: 2 7 4 5 // 获取指定位置的元素 cout << dll.get(2) << endl; // 输出: 4 // 修改指定位置的元素 dll.set(2, 8); dll.printList(); // 输出: 2 7 8 5 return 0; } ``` 这里实现了双向循环链表的基本操作,包括在链表头部、尾部和指定位置插入元素,删除链表头部、尾部和指定位置的元素,获取指定位置的元素和修改指定位置的元素等。在实现过程中,我们采用了模板化编程,使得该链表可以存储任意类型的数据。同时,为了更好地理解和使用该链表,我们在每个函数中都添加了详细的注释。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值