In my application I'm writing an abstraction layer on top of a JNI library that calls into native C code. This native library (FFmpeg to be exact) exposes some global functions to change logging behavior.
In particular, I'm using a callback that forwards log messages to custom handlers. The problem is that there can be only one such callback. Creating a new instance of this callback means the native library will call it instead, whether it has been registered as the new callback or not. If you want another then you have to create a different callback class just like you'd declare a new function in C.
To me there seems to be two alternatives:
(1) Allow multiple instances of this singleton class. I'm already using a private static instance of the callback class. It cannot be instantiated elsewhere, at least, my subclass of this callback.
(2) Some other way to restrict users from instantiating this singleton class more than once.
The issues I have with the first approach are:
(1) The API is misleading. It's simply a proxy object that operates on global state. Yet to the user, it seems like each instance operates on its own state.
(2) Synchronization. I cannot use multiple locks. Using a static private lock takes us back to issue #1. At least a lock cannot be mutated of course.
Should I just give up on the whole thing and use a singleton anyway? No matter how you cut it, the class will be mutating global state. It's just that this state is beyond my control.
What to do in such situations? Do I have any viable alternatives?
Aucun commentaire:
Enregistrer un commentaire