sundie
sundie

Reputation: 245

Thread safety in Android libraries

I'm trying to implement a native shared library(.so) for the Android system. Naturally, there are some code blocks that need to be thread-safe.

I found out here that pthreads locks, mutexes, or condition variables are not supported.

I'd like to know what is usually used at the library level to achieve thread-safety?

Upvotes: 10

Views: 864

Answers (3)

J-Boss
J-Boss

Reputation: 927

You could use a thread safe singleton. While this is not a very popular method of thread safe atomic operation anymore, since all things singleton are bad, (so I don't expect a lot of up votes). It's fast, lightweight, and still works, it was heavily used in smalltalk and for a time in Java and was considered a key design pattern.

public class ThreadSafeSingleton {

    private static final Object instance = new Object();

    protected ThreadSafeSingleton() {
    }

    // Runtime initialization

    public static Object getInstance() {
        return instance;
    }
}

This a lazy loaded version...

public class LazySingleton {
    private Singleton() {
    }

    private static class LazyInstance {
        private static final Singleton INSTANCE = new Singleton();
    }
        // Automatically ThreadSafe
    public static Singleton getInstance() {
        return LazyInstance.INSTANCE;
    }
}

You can check out this post on Thread Safe Singletons in Java for more Info.

Upvotes: 0

emidander
emidander

Reputation: 2403

There is a DevBytes video here that discusses threading in the NDK. One useful pattern discussed in the video is doing atomic writes using __atomic_swap in the native code.

Upvotes: 1

Kai
Kai

Reputation: 15476

How this can be achieves depends on whether you just want it to be thread safe when accessed by Java level threads, or you need to synchronize native threads with Java threads.

There are two ways to synchronize only Java level threads:

1.The easiest way is to add the synchronized keyword to the native methods that be accessed by multiple thread, i.e.

public native synchronized int sharedAccess();

2.Synchronization from the native side:

(*env)->MonitorEnter(env, obj);
...                      /* synchronized block */
(*env)->MonitorExit(env, obj);

Refer here on how to synchronize native threads with Java threads

Upvotes: 4

Related Questions