summaryrefslogtreecommitdiffstats
path: root/java/jau/direct_bt/DBTNativeDownlink.java
blob: e71d84598b99db967625e94f194549e66f912bcd (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
/**
 * Author: Sven Gothel <sgothel@jausoft.com>
 * Copyright (c) 2020 Gothel Software e.K.
 * Copyright (c) 2020 ZAFENA AB
 *
 * Permission is hereby granted, free of charge, to any person obtaining
 * a copy of this software and associated documentation files (the
 * "Software"), to deal in the Software without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to
 * the following conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

package jau.direct_bt;

import java.util.concurrent.atomic.AtomicBoolean;

/**
 * Java counterpart to C++ jau::JavaUplink
 *
 * Store the native `std::shared_ptr<T> *` long representation
 * and handles the lifecycles of
 * - Java object reference in the native object
 *   - `jau::JavaUplink`'s `std::shared_ptr<JavaAnon>` via `JavaUplink::setJavaObject()`
 * - Native object reference in the Java object
 *   - `std::shared_ptr<T> *` long representation in `long nativeInstance`
 *
 * Using a `shared_ptr<T>` ensures surviving of the native object when temporary copied
 * within JNI methods w/o locking.
 */
public abstract class DBTNativeDownlink
{
    /** native `std::shared_ptr<T> *` long representation. */
    private long nativeInstance;
    private final AtomicBoolean isNativeValid = new AtomicBoolean(false);
    private final Object nativeLock = new Object();

    /**
     *
     * @param nativeInstance
     */
    protected DBTNativeDownlink(final long nativeInstance)
    {
        this.nativeInstance = nativeInstance;
        isNativeValid.set(true);
        initNativeJavaObject(nativeInstance);
    }
    protected DBTNativeDownlink()
    {
        this.nativeInstance = 0;
        isNativeValid.set(false);
    }
    protected final void initDownlink(final long nativeInstance) {
        synchronized (nativeLock) {
            if( isNativeValid.compareAndSet(false, true) ) {
                this.nativeInstance = nativeInstance;
                initNativeJavaObject(nativeInstance);
            } else {
                System.err.println("DBTNativeDownlink.init2: Already valid, dropping nativeInstance 0x"+Long.toHexString(nativeInstance));
            }
        }
    }

    /**
     * Returns true if native instance is valid, otherwise false.
     */
    protected final boolean isNativeValid() { return isNativeValid.get(); }

    @Override
    protected void finalize()
    {
        delete();
    }

    /**
     * Deletes the {@code nativeInstance} in the following order
     * <ol>
     *   <li>Removes this java reference from the {@code nativeInstance}, i.e. `std::shared_ptr<JavaAnon>` via `JavaUplink::setJavaObject()`</li>
     *   <li>Deletes the {@code nativeInstance} via {@link #deleteImpl(long)}</li>
     *   <li>Zeros the {@code nativeInstance} reference</li>
     * </ol>
     */
    public final void delete() {
        synchronized (nativeLock) {
            if( !isNativeValid.compareAndSet(true, false) ) {
                if( DBTManager.DEBUG ) {
                    System.err.println("JAVA: delete: !valid -> bail: "+getClass().getSimpleName());
                }
                return;
            }
            if( DBTManager.DEBUG ) {
                System.err.println("JAVA: delete.0: "+getClass().getSimpleName()+": valid, handle 0x"+Long.toHexString(nativeInstance));
            }
            final long _nativeInstance = nativeInstance;
            nativeInstance = 0;
            deleteNativeJavaObject(_nativeInstance); // will issue notifyDeleted() itself!
            deleteImpl(_nativeInstance);
            if( DBTManager.DEBUG ) {
                System.err.println("JAVA: delete.X: "+getClass().getSimpleName()+": handle 0x"+Long.toHexString(nativeInstance));
            }
        }
    }

    /**
     * Called from native JavaUplink dtor -> JavaGlobalObj dtor,
     * i.e. native instance destructed in native land.
     */
    private final void notifyDeleted() {
        synchronized (nativeLock) {
            final boolean _isValid = isNativeValid.get();
            final long _nativeInstance = nativeInstance;
            isNativeValid.set(false);
            nativeInstance = 0;
            if( DBTManager.DEBUG ) {
                System.err.println("JAVA: delete.notifyDeleted: "+getClass().getSimpleName()+", was: valid "+_isValid+", handle 0x"+Long.toHexString(_nativeInstance)+": "+toString());
            }
        }
    }

    /**
     * Deletes the native instance.
     * <p>
     * Called via {@link #delete()} and at this point
     * <ul>
     *  <li>this java reference has been removed from the native instance, i.e. {@code JavaUplink}'s {@code javaObjectRef = nullptr}</li>
     *  <li>the {@link #nativeInstance} reference has been zeroed, but passed as argument for this final native deletion task.</li>
     * </ul>
     * </p>
     * @param nativeInstance copy of {@link #nativeInstance} reference, which has been already zeroed.
     */
    protected abstract void deleteImpl(long nativeInstance);

    private native void initNativeJavaObject(final long nativeInstance);
    private native void deleteNativeJavaObject(final long nativeInstance);
}