android java semaphore mutex isn’t working!! Activity crashed completely!!!

Posted: February 13, 2013 in android, mobile, snippets

I already created a semaphore in my java native activity. I needed it to add voice samples to a buffer from one thread and read and empty this buffer on other thread. Started to get data aborts so I investigated and found the semaphore isn’t working as I expected.

The code I use is this:

declare the semaphore:

static public final Semaphore SEMAPHORE = new Semaphore(1);

and than do




and it isn’t working… 😦

So I find this code which creates a class and looks and sleeps until lock is acquired, but I don’t like it. Can’t believe this is the solution and it looks kinda old (2004 old).

I tried to implement the code from this post, looks decent. The synchronized architecture looks very logic.

WOW this is a great improvement in performance too!!!! I guess the “old semaphore” didn’t work as well as I thought it would. The new code involves this:

public Class MyClass {
  private static Object lock = new Object();
  public void myMethod() {
    // Stuff that multiple threads can execute simultaneously.
    synchronized(MyClass.lock) {
      // Stuff that only one thread may execute at a time.

(taken from the very same post)

So just encapsulates all sync’d code in “synchronized(MyClass.lock) {}” and it does the semaphoring for you.
happy happy

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s