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());
}
}
@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