Advices on concurrency JAVA

Viewed 97

I am kind of new at concurrency (I believe i am doing good with Monitors, Semaphores and reentrantLocks) so i can't use them. I have to use any class or interface from concurrent package.

Point 1.- Few threads must access an array and make a sumatory of its elements (I used Atomic Variables here, there is an atomic variable used as a pointer for the array).

Point 2.- Here, a number of Threads (cars), in a shore have, to cross a river. There is a Thread that simulates a boat. When 10 cars are in the boat it sails to the other shore. This secuance is repeated until all cars crosses the river. I don't really know which ones to use here.

Point 3.- Here, some Threads have to read some information and other Threads have to modify that information (any number of times). I believe here I have to use ReadWriteLock.

Point 4.- A producer / consumer like problem. Here I used BlockingQueue.

Point 5.- Made up an exchanger like problem and solve it (done, really simple one... 2 threads exchanging a String variable).

If you have any recomendation on which method to use in a certain points (like "No, use atomic variables in point 3 and cyclicBarrier in point 1"), will help me a lot!

Thanks!

2 Answers

Atomic Variables

Atomic Variables are proceed with CAS algorithm and they have can be consumed by multiple threads safely :

CAS :

A typical CAS operation works on three operands: The memory location on which to operate (M) The existing expected value (A) of the variable The new value (B) which needs to be set The CAS operation updates atomically the value in M to B, but only if the existing value in M matches A, otherwise no action is taken.

You can use Exchanger which could be used to swap , exchange some information between two threads

https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/Exchanger.html

Blocking queue is consumer producer model a you mentioned , So for using it you need to create two threads one will be Producer it will put to the Blocking queue , consumer will consume (read) from it . There are many implementations of BlockingQueue
Here is more detailed information:

http://tutorials.jenkov.com/java-util-concurrent/blockingqueue.html

So from you list is all on their places.

Also you can reed something here about java.util.concurrent I think this will be helpful :

http://tutorials.jenkov.com/java-util-concurrent/index.html

Point 2: if the thread is a boat, it should take cars on one bank of the river and unload them on the other bank. Looks like most natural representation of cars on a bank is a BlockingQueue and ArrayList for cars on the boat. Generally, always consider BlockingQueue first.

Point 3: this is usually done by synchronized methods, or ReentrantLocks.

Related