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?

- 245
- 3
- 12
-
1I am afraid you misunderstood the article. Android bionic implementation of **pthreads** is quite complete. It is not fully POSIX compliant, but good for all practical purposes. The mutexes and condition vars that "are not supported" are *inter-process* ones, which are not relevant for your native shared library, working in a sandboxed Android app. Android defines other inter-process communication and synchronization mechanisms. – Alex Cohn Dec 21 '15 at 22:15
3 Answers
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
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.