Ad
Java Concurrency Barrier Example Deadlock
I am trying to implement custom Barrier
example in order to learn more about concurrency in Java. I have a runnable class:
public class Barrier implements Runnable {
private static Semaphore barrier = new Semaphore(0);
private static int toWait = 5;
private static int counter = 0;
private static long sleepTime;
public static int ID = 0;
private int id = ++ID;
public Barrier(long sleep){
sleepTime = sleep;
}
@Override
public void run() {
try {
Thread.sleep(sleepTime);
counter++;
if (counter == toWait){
barrier.release(counter);
}
barrier.acquire();
System.out.println("Thread with sleep: " + id + " proceeds");
} catch (InterruptedException ex) {
Logger.getLogger(Barrier.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
Then in the main
function, I create 5 threads and start them. Upon, running I get a deadlock, that I can't resolve. Can someone tell me what I am doing wrong?
Ad
Answer
There were no mutual exclusion. To solve it, I needed to add another semaphore and surround the counter increment with with acquire
release
of that semaphore.
Ad
source: stackoverflow.com
Related Questions
- → How to update data attribute on Ajax complete
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → Octobercms Component Unique id (Twig & Javascript)
- → Passing a JS var from AJAX response to Twig
- → Laravel {!! Form::open() !!} doesn't work within AngularJS
- → DropzoneJS & Laravel - Output form validation errors
- → Import statement and Babel
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM
Ad