Two threads acessing same LinkedList - java

I am new to Java, and have come across a problem when trying to implement a simple game.
The premise of the game currently is, a timer is used to add a car, and also more frequently to update the movement of the car. A car can be selected by touch, and directed by drawing it's path. The update function will move the car along the path.
Now, the game crashes with an IndexOutOfBoundsException, and I am almost certain this is because occasionally, when a car is reselected, the current path is wiped and it allows a new path to be drawn. The path is stored as a LinkedList, and cleared when the car is touched.
I imagine if the path is cleared via a touch event, whilst the timer thread is updating the cars movement along the path, this is where the error occurs (There are also similar other issues that could arise with two threads accessing this one list.
My question, in Java, what would be the best way of dealing with this? Are there specific types of lists I should be using rather than LinkedList, or are there objects such as a Mutex in c++, where I can protect this list whilst working with it?

In Java, this is usually accomplished using synchronization
A small example might look something like this:
LinkedList list = //Get/build your list
public void doStuffToList()
{
synchronized(list)
{
//Do things to the list
}
}
public void clearList()
{
synchronized(list)
{
list.clear();
}
}
This code won't let the clear operation be performed if there's another thread currently operating on the list at that time. Note that this will cause blocking, so be careful for deadlocks.
Alternatively, if your List is a class that you've built yourself, it probably makes sense to make the data structure thread safe itself:
public class SynchroLinkedList
{
//Implementation details
public synchronized void doThingsToList()
{
//Implementation
}
public synchronized void clearList()
{
//Implementation
}
}
These two approaches would effectively work the same way, but with the second one your thread safety is abstracted into the datatype, which is nice because you don't have to worry about thread safety all over the place when you're using the list.

Instead of recreating your own thread safe list implementation, you have several built-in options, essentially:
use a synchronized list:
List list = Collections.synchronizedList(new LinkedList());
Note that you need to synchronize on the list (synchronized(list) { }) for iterations and other combined operations that need to be atomic)
use a thread safe collection, for example a CopyOnWriteArrayList or a ConcurrenLinkedQueue, which could be a good alternative if you don't need to access items in the middle of the list, but only need to add an iterate.
Note that a CopyOnWriteArrayList might have a performance penalty depending on your use case, especially if you regularly add items (i.e. every few microseconds) and the list can become big.

Related

Java ConcurrentModificationException problems with classes

I am essentially doing the following:
Creating an object (for example a weapon object), that automatically adds that object to a list off all of those types of objects (ArrayList<Weapons>).
JPanel paints every 10 seconds with an updater thread that iterates through the ArrayList<Weapons>. I am also sending 'questions' to a server on another machine, i.e. asking if that weapon is allowed. If it is not, the weapon object is modified by the client computer. However, whenever I modify it, I receive a ConcurrentModificationException. Instead of crashing, which I actually hope it would do at this point, since the method that changes the weapon object is on a different thread, the whole program just locks up.
I have more than 1000 lines of code in this program, and more than three threads running that access the list, so if you need any code please ask but I'd rather not post right now because in my mind this seems like a trivial question for an expert at threads.
Thanks!
(Object is made >> added to list of objects >> JPanel's "Updater" thread is constantly painting all objects every 10 ticks...
Server says that object isn't allowed >> A thread on the client computer removes that object (or toggles a boolean that says it is not visible) >> ConcurrentModificationException).
Quoting the Javadoc of ArrayList
Note that this implementation is not synchronized. If multiple threads access an ArrayList instance concurrently, and at least one of the threads modifies the list structurally, it must be synchronized externally.
You describe multiple threads accessing the list, and at least one of them modifying it. So, all accesses to the list must be done in mutually synchronized blocks.
e.g. to iterate the list:
synchronized (list) {
for (Weapons weapons : list) {
// ...
}
}
e.g. to remove an item from the list:
synchronized (list) {
list.remove(0);
}
I think you can use a synchronised version of collection or list, i.e. java.util.Collections.synchronizedCollection(Collection<>), java.util.Collections.synchronizedList(List<>). Also, if you iterate over the list and remove items, ensure that use an implementation that enable remove item from the iterator. A good candidate is java.util.ArrayList.
Other technique is use "monitors", you can declare an attribute like: private static Object monitor = new Object(); then when the code tries to access to the list, protect the code inside a synchronized(monitor) block. Using this technique you ensure that no other thread will be able to modify your list until no protected code is running.
Please, excuse my English :).

Add running thread objects in to an arraylist

I am creating a small tank game using java. In that game, lifepacks and coin piles are generated at a random place on the game grid time to time. They both have a limited lifetime and after lifetime expires they are vanished from the field. When they visible on the grid, any tank can acquire them before vanish. And I want to keep the list of lifepack objects and coinpile objects in an ArrayList in order to access them by the game AI algorithm. I hope to implement the above concept as follows using simple java knowledge.
Following is my LifePack class.CoinPile class behaves in a similar manner:
public class LifePack extends Thread{
public int healthBonus;
public int lifetime;
public String type;
public Point location;
public boolean visible;
public LifePack(int x,int y,int lifetime){
location=new Point(x, y);
this.lifetime=lifetime;
this.type="health_pack";
this.visible=true;
this.start();
}
public void run(){
while(true){
if(this.lifetime>0){
try{
Thread.sleep(1);
if(lifetime%1000==0){
System.out.println("Life pack "+this.getId()+" will be disappeared in "+this.lifetime/1000+" s");
}
this.lifetime--;
}
catch(Exception ex){
ex.printStackTrace();
}
}
else{
this.visible=false;
this.interrupt();
break;
}
}
System.out.println("Life pack visibility = "+this.visible);
}
}
I want to add the newly created LifePack Objects into an arraylist as follows:
public ArrayList<LifePack> lifePacks;
lifePacks = new ArrayList<LifePack>();
lifePacks.add(new LifePack(x, y, lifeTime));
Each time a new lifepack is created I add that lifepack object into the arraylist above. Once the lifepack's lifetime expires, I want to set the 'visible' boolean variable in the above class to 'false' so that I can check that variable for other purposes.
But I don't get my desired output. Can I add running thread objects into an arraylist as above and keep the thread state running or Will I have to move to a different implementation? Please somebody help me to clear this out if there is a solution.
Thank you.
I agree with dirkk that you will spin up too many threads. But to answer your question maybe you should consider using AtomicBoolean for visible.
http://docs.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/atomic/AtomicBoolean.html
From what I see, one Thread checks if some entry in a list is false, some other thread sets it to false, this needs to be thread safe.
You could do that by synchronizing the list itself during the update operation
synchronized(list){
//update the needed entry to false
}
As already pointed out, creating threads is a bad idea. In particular, once your application comes to a point at which very many lifepacks exist. Also note that starting a thread in a constructor is very bad practice. If you want to use plain threads, implementing a runnable (java.lang.Runnable) is advisable.
In general, however, I would strongly encourage you to use the Java concurrency abstractions available in the java.util.concurrent package: http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/package-summary.html Using an ExecutorService to run callables (java.util.concurrent.Callable) allows you to vary the number of threads quite easily.
I would also question your idea of storing all the lifepacks in the same collection and assigning each of them a state (visiblity). Spontaneously, I could think of the following scenario: once the game runs for quite some time, you will end up with a large collection of lifepacks, most of which are not used anymore. Therefore, you might want to think about having different collections for the different states a lifepack can be in. This would also make throwing away object quite easy (without traversing a collection). Aussuming that those collections would be accessed by more than one thread, you'd want them to be thread-safe. For that, you'll find various types of collections in the java.util.concurrent package as well.

How to Maintain single copy of List among st all threads in Java

class A implements Callable{
List result // want to share this List amongst thread and their function call
public Search call() {
List<Job> Jobs = api. Jobs(a,b,c); // Multiple threads
}
}
class API{
public void jobs(a,b,c){
// want to access the A.Result and populate the result
}
}
How can i share an array List amogst all threds, I dont want to use the Static ,
as it will keep accumilating the result every time it runs ,
Is Thread Local is a good choice over here ?
Trying to avoid an extra object and its respective getters / setters ?
What ever you have right now is thread shared list. All threads operating on this object
(assuming only one instance of this object exists) share same list unless you synchronize.
I know you have your answer, but I did not understand the answer or the question, thus need to ask. So, you problem looks like this? You have a bunch of Callables that will perform some work on a SINGLE list, thus this list is shared among Threads? Then you need to make this List Thread Safe, and making a List of Objects Thread Safe is not that trivial (on your own), unless you use something already given by Java

Thread safe graph libraries

I am looking for a good Java Graph Library which is thread safe for concurrent access.
JGraphT, JUNG, JTS are very good but again for concurrent access I will have to synchronize it externally which is becoming a pain.
It is a pain because say If thread A have to access 50 vertices, Thread B for another 50 with the intersection of vertices being 20 vertices. Now while writing code I need to know this 20 before so that I can synchronize it accordingly.
Pl suggest
Have you considered Neo4J
Here is a snippet describing their product.
Neo4j is a high-performance, NOSQL graph database with all the features of a mature and robust database.
I'm afraid what you're looking for is impossible, because thread-safety is a property of algorithms, not a property of data structures. Here's an example:
Let's say your graph library has a main Graph class with a number of methods, all of which are synchronized. For example, addVertex(), removeVertex(), addEdge(), removeEdge(), etc. Let's also say that the Vertex class has some useful methods like getAdjacentEdges(), for example, also synchronized on the containing Graph instance.
Now clearly because everything is synchronized, it's impossible to corrupt the data structure. For example, you'll never have a situation where v.getAdjacentEdges() gives you an edge that's not actually in the graph containing vertex v. The graph structure is always internally consistent thanks to its internal synchronization.
However, your algorithms operating on the graph can still easily break. For example, let's say you write:
for (Edge e : v.getAdjacentEdges()) {
g.removeEdge(e);
}
The call to getAdjacentEdges() is atomic, as is each call to removeEdge() in the loop, but the algorithm itself is not. Another thread may add a new edge adjacent to v while this loop is running, or remove an edge, or whatever. To be safe, you still need a way of ensuring that the loop as a whole is atomic, and the graph itself cannot provide that.
My best advice, I think, is to use JGraphT in combination with Akka's STM implementation (or similar), so that you can write your algorithms without needing to determine ahead of time which objects will require locking. If you're not familiar with STM and its performance characteristics, Wikipedia's article on the topic does a decent job of explaining.
JGraphT now provides a concurrent AsSynchronizedGraph graph implementation which is thread safe. In addition, JGraphT has a number of algorithmic implementations that take advantage of multiple threads. See for instance the DeltaSteppingShortestPath algorithm.
How about letting several threads do whatever they can do and then submit there solution to one master controller that collects results and comes up with the best solution.
The simplest solution is to create one big monitor.
public Object theBigGraphMonitor = new Object();
Before doing ANY operation on the graph, synchronize on that single monitor.
Fiddling with indivudial verticles seems to be hard to get right... To say the least.
If you only want to change nodes locally, you can maintain an individual lock for each node. The simplest way to do this would be to implement a custom node class with synchronized methods (you could use ReentrantLock as well) i.e. something like this:
public class SynchronizedNode extends Node {
public synchronized void localOp1() { ... }
public synchronized void localOp2() { ... }
}
or
public class SynchronizedNode extends Node {
ReentrantLock lock ....;
public synchronized void localOp1() { lock.lock() try { ... } finally { lock.unlock } }
public synchronized void localOp2() { lock.lock() try { ... } finally { lock.unlock } }
}
Have a look at charts4j API. We are using it in our application with reasonable no of concurrent users and there has been no problems yet. I am not sure if the API is thread safe or not.
One problem we have noticed is that the url of the graph generated will point to http://www.google.com/... which can be a problem if you are working inside a VPN and the internet is not available.(May be there is a way out it of it).

Determining synchronization scope?

in trying to improve my understanding on concurrency issues, I am looking at the following scenario (Edit: I've changed the example from List to Runtime, which is closer to what I am trying):
public class Example {
private final Object lock = new Object();
private final Runtime runtime = Runtime.getRuntime();
public void add(Object o) {
synchronized (lock) { runtime.exec(program + " -add "+o); }
}
public Object[] getAll() {
synchronized (lock) { return runtime.exec(program + " -list "); }
}
public void remove(Object o) {
synchronized (lock) { runtime.exec(program + " -remove "+o); }
}
}
As it stands, each method is by thread safe when used standalone. Now, what I'm trying to figure out is how to handle where the calling class wishes to call:
for (Object o : example.getAll()) {
// problems if multiple threads perform this operation concurrently
example.remove(b);
}
But as noted, there is no guarantee that the state will be consistent between the call to getAll() and the calls to remove(). If multiple threads call this, I'll be in trouble. So my question is - How should I enable the developer to perform the operation in a thread safe manner? Ideally I wish to enforce the thread safety in a way that makes it difficult for the developer to avoid/miss, but at the same time not complicated to achieve. I can think of three options so far:
A: Make the lock 'this', so the synchronization object is accessible to calling code, which can then wrap the code blocks. Drawback: Hard to enforce at compile time:
synchronized (example) {
for (Object o : example.getAll()) {
example.remove(b);
}
}
B: Place the combined code into the Example class - and benefit from being able to optimize the implementation, as in this case. Drawback: Pain to add extensions, and potential mixing unrelated logic:
public class Example {
...
public void removeAll() {
synchronized (lock) { Runtime.exec(program + " -clear"); }
}
}
C: Provide a Closure class. Drawback: Excess code, potentially too generous of a synchronization block, could in fact make deadlocks easier:
public interface ExampleClosure {
public void execute(Example example);
}
public Class Example {
...
public void execute(ExampleClosure closure) {
synchronized (this) { closure.execute(this); }
}
}
example.execute(new ExampleClosure() {
public void execute(Example example) {
for (Object o : example.getAll()) {
example.remove(b);
}
}
}
);
Is there something I'm missing? How should synchronization be scoped to ensure the code is thread safe?
Use a ReentrantReadWriteLock which is exposed via the API. That way, if someone needs to synchronize several API calls, they can acquire a lock outside of the method calls.
In general, this is a classic multithreaded design issue. By synchronizing the data structure rather than synchronizing concepts that use the data structure, it's hard to avoid the fact that you essentially have a reference to the data structure without a lock.
I would recommend that locks not be done so close to the data structure. But it's a popular option.
A potential technique to make this style work is to use an editing tree-walker. Essentially, you expose a function that does a callback on each element.
// pointer to function:
// - takes Object by reference and can be safely altered
// - if returns true, Object will be removed from list
typedef bool (*callback_function)(Object *o);
public void editAll(callback_function func) {
synchronized (lock) {
for each element o { if (callback_function(o)) {remove o} } }
}
So then your loop becomes:
bool my_function(Object *o) {
...
if (some condition) return true;
}
...
editAll(my_function);
...
The company I work for (corensic) has test cases extracted from real bugs to verify that Jinx is finding the concurrency errors properly. This type of low level data structure locking without higher level synchronization is pretty common pattern. The tree editing callback seems to be a popular fix for this race condition.
I think everyone is missing his real problem. When iterating over the new array of Object's and trying to remove one at a time the problem is still technically unsafe (though ArrayList implantation would not explode, it just wouldnt have expected results).
Even with CopyOnWriteArrayList there is the possibility that there is an out of date read on the current list to when you are trying to remove.
The two suggestions you offered are fine (A and B). My general suggestion is B. Making a collection thread-safe is very difficult. A good way to do it is to give the client as little functionality as possible (within reason). So offering the removeAll method and removing the getAll method would suffice.
Now you can at the same time say, 'well I want to keep the API the way it is and let the client worry about additional thread-safety'. If thats the case, document thread-safety. Document the fact that a 'lookup and modify' action is both non atomic and non thread-safe.
Today's concurrent list implementations are all thread safe for the single functions that are offered (get, remove add are all thread safe). Compound functions are not though and the best that could be done is documenting how to make them thread safe.
I think j.u.c.CopyOnWriteArrayList is a good example of similar problem you're trying to solve.
JDK had a similar problem with Lists - there were various ways to synchronize on arbitrary methods, but no synchronization on multiple invocations (and that's understandable).
So CopyOnWriteArrayList actually implements the same interface but has a very special contract, and whoever calls it, is aware of it.
Similar with your solution - you should probably implement List (or whatever interface this is) and at the same time define special contracts for existing/new methods. For example, getAll's consistency is not guaranteed, and calls to .remove do not fail if o is null, or isn't inside the list, etc. If users want both combined and safe/consistent options - this class of yours would provide a special method that does exactly that (e.g. safeDeleteAll), leaving other methods close to original contract as possible.
So to answer your question - I would pick option B, but would also implement interface your original object is implementing.
From the Javadoc for List.toArray():
The returned array will be "safe" in
that no references to it are
maintained by this list. (In other
words, this method must allocate a new
array even if this list is backed by
an array). The caller is thus free to
modify the returned array.
Maybe I don't understand what you're trying to accomplish. Do you want the Object[] array to always be in-sync with the current state of the List? In order to achieve that, I think you would have to synchronize on the Example instance itself and hold the lock until your thread is done with its method call AND any Object[] array it is currently using. Otherwise, how will you ever know if the original List has been modified by another thread?
You have to use the appropriate granularity when you choose what to lock. What you're complaining about in your example is too low a level of granularity, where the lock doesn't cover all the methods that have to happen together. You need to make methods that combine all the actions that need to happen together within the same lock.
Locks are reentrant so the high-level method can call low-level synchronized methods without a problem.

Categories