Thread safety in Android libraries
Asked Answered
C

3

10

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?

Cheerly answered 10/9, 2014 at 21:18 Comment(1)
I 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.Chewy
H
4

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

Hemipode answered 30/8, 2015 at 5:45 Comment(0)
P
1

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.

Pyridoxine answered 4/9, 2015 at 13:6 Comment(0)
L
0

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.

Labiche answered 5/9, 2015 at 0:29 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.