Created
May 31, 2013 21:08
-
-
Save charlierm/5688023 to your computer and use it in GitHub Desktop.
Thread safe linked list written in java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.