I have a problem in my Java native audio library but first, here is my current approach:

1. With a native method I'm opening a 'global' stream, which receives data over a callback function.
2. The callback function runs until there is no data.
3. If there is no data, the stream only stops, but does not get closed.
4. Now I wanted to feed the stream with data again [trying to start stream again(this operation is allowed)], but the stream has already been deleted.

So now I tried to figure out how to prevent deletion of the stream from C++ or Java.

One solution was to create a thread in the stream, which prevents the deletion.

But I don't like this solution...

So I searched how to keep such objects alive and found out, that there are so called "global references" which can be made with the JNI. But I did not understand whether they are only for java objects or for both.

Also I tried out whether another pointer type of C++ could help.

I appreciate any help or ideas, it does not have to be JNI only. C++ standard library methods/functions/classes etc. are also good :) !

System information:

* Compiler: MinGW64 over MSYS2
* JDK8u91
* Of course 64bit operation system (Does not have to be named xD)

With global stream is meant, that the stream is accessible to all JNI methods.

EDIT:

Okay, 'to let the cat out of the back' I'm using RtAudio.
[Realtime C++ Audio Library](http://www.music.mcgill.ca/~gary/rtaudio/index.html)

Example:

```
//THIS IS C++ CODE
RtAudio audio(RtAudio::WASAPI);

int callback(//Buffer stuff etc.){
  //do something
 if(data.isEmpty())return 1;//invokes audio.closeStream() but this does NOT closes the stream!
 else return 0; //Go on with the stream rather wait for the next call
}    

JNIEXPORT void JNICALL openStream(jintArray data){
   //This is a outputstream
   audio.openStream(&outputParams,....., &callback,....);
   audio.startStream();
}

JNIEXPORT void JNICALL fillData(jintArray data){
    //filldata again!
    stream.start(); //Starts the stream but does nothing, because the stream is deleted because of Java 
}

```

If I would change the openStream method to this, the stream won't be deleted but I look for a better solution...

```
JNIEXPORT void JNICALL openStream(jintArray data){
   //This is a outputstream
   audio.openStream(&outputParams,....., &callback,....);
   audio.startStream();
 **while(true); //ADD THIS AND THE STREAM WON'T BE DELETED!**  
}

```

Another solution is to add into the RtAudio API a "keepInstanceAliveThread" which is called after the stopStream() method and deleted after calling startStream() or closeStream(). I would rather prefer another solution but at all, there isn't any yet.

Pre-outcomes:

Thanks to @marcinj:

> 
> global object are known to cause many problems, its hard to control their construction/destruction.
> 
> 
> 

EDIT:
I found out in the internet (also on stackoverflow), that the destructor is called after the return of a JNI method.