Skip to content

Instantly share code, notes, and snippets.

@charlierm
Created May 31, 2013 21:08
Show Gist options
  • Save charlierm/5688023 to your computer and use it in GitHub Desktop.
Save charlierm/5688023 to your computer and use it in GitHub Desktop.
Thread safe linked list written in java
import java.util.Iterator;
public class LinkedList<T>{
private Node head;
private int length;
public LinkedList(){
this.length = 0;
head = null;
}
public int length(){
return this.length;
}
public void add(T object){
Node node = new Node();
node.data = object;
node.next = this.head;
this.head = node;
this.length ++;
}
public T get(int index) throws Exception{
Node head = this.head;
for (int i=0; i<this.length(); i++) {
if (i == index) {
return (T) head.data;
}
else{
head = head.next;
}
}
throw new Exception("Item not found.");
}
}
class Node{
public Object data;
public Node next;
public boolean hasNext(){
if (this.next != null) {
return true;
}
else {
return false;
}
}
}
import java.lang.Math;
public class Main{
public static void main(String[] args) {
LinkedList<Float> list = new LinkedList<Float>();
for (int i=0; i<1000; i++) {
list.add(new Float(Math.random()));
}
System.out.println(list.length());
}
}
@M-machado
Copy link

M-machado commented Nov 27, 2016

Hello there.
I think I am not missing anything, but in the description it says your Linked List is thread safe. I'd rather say it isn't.
There are no concurrency statements or synchronized methods within your class, thus, any multiple access by threads will cause misbehaviour or unhandled exceptions.
Useful links:
Synchronized Statements and Methods
Synchronized Collections

@dadakhalandhar
Copy link

import java.util.Collection;
import java.util.LinkedList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class ThreadSafeLinkedList {

private LinkedList<E> list = new LinkedList<>();

ReentrantReadWriteLock lock = new ReentrantReadWriteLock();

public void add(E e) {
	lock.writeLock().lock();
	list.add(e);
	lock.writeLock().unlock();
}

public void add(int index, E e) {
	lock.writeLock().lock();
	list.add(index, e);
	lock.writeLock().unlock();
}

public void addAll(Collection<E> sourceList) {
	lock.writeLock().lock();
	list.addAll(sourceList);
	lock.writeLock().unlock();
}

public E get(int index) {
	E e;
	lock.readLock().lock();
	e = list.get(index);
	lock.readLock().unlock();
	return e;
}

public E getFirst() {
	E e;
	lock.readLock().lock();
	e = list.getFirst();
	lock.readLock().unlock();
	return e;
}

public E getLast() {
	E e;
	lock.readLock().lock();
	e = list.getLast();
	lock.readLock().unlock();
	return e;
}

public int size() {
	int size;
	lock.readLock().lock();
	size = list.size();
	lock.readLock().unlock();
	return size;
	
}

public static void main(String[] args) {
	ExecutorService service = Executors.newCachedThreadPool();
	ThreadSafeLinkedList threadSafeLinkedList = new ThreadSafeLinkedList<>();
	for(int i=0;i<10;i++) {
		service.submit(new Worker(threadSafeLinkedList, i));
	}
	service.shutdown();
	try {
		service.awaitTermination(10000, TimeUnit.MILLISECONDS);
	} catch (InterruptedException e) {
		e.printStackTrace();
	}
	
	System.out.println(threadSafeLinkedList.size());
}

static class Worker<E> implements Runnable{
	
	ThreadSafeLinkedList<E> list;
	E value;
	
	public Worker(ThreadSafeLinkedList<E> list, E i) {
		this.list = list;
		this.value = i;
	}
	
	@Override
	public void run() {
		for(int i=0;i<1000;i++) {
			list.add(value);
		}
	}
}

}


Implementation (partial) and usage.

@dipendra210
Copy link

Thank @dadakhalandhar
I think, the class which you post, uses coarse-grained locking to handle concurrent access for threads sharing an instance of the class.
What is it to implement a fine-grained solution for this class that optimizes concurrent access for threads.
Thanks in advice.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment