wangmengmeng
2025-04-26 96250617dbbefce55b5966c94880e2b07b6c98df
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
package com.dji.sdk.mqtt;
 
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.LockSupport;
 
/**
 * The demo is only for functional closure, which is not recommended.
 * @author sean.zhou
 * @date 2021/11/22
 * @version 0.1
 */
public class Chan {
 
    private static final ConcurrentHashMap<String, Chan> CHANNEL = new ConcurrentHashMap<>();
 
    private static final int UNIT = 1000_000;
 
    private volatile CommonTopicResponse data;
 
    private volatile Thread t;
 
    private Chan () {
 
    }
 
    public static Chan getInstance(String tid, boolean isNeedCreate) {
        if (!isNeedCreate) {
            return CHANNEL.get(tid);
        }
        Chan chan = new Chan();
        CHANNEL.put(tid, chan);
        return chan;
    }
 
    public CommonTopicResponse get(String tid, long timeout) {
        Chan chan = CHANNEL.get(tid);
        if (Objects.isNull(chan)) {
            return null;
        }
        chan.t = Thread.currentThread();
        LockSupport.parkNanos(chan.t, timeout * UNIT);
        chan.t = null;
        CHANNEL.remove(tid);
        return chan.data;
    }
 
    public void put(CommonTopicResponse response) {
        Chan chan = CHANNEL.get(response.getTid());
        if (Objects.isNull(chan)) {
            return;
        }
        chan.data = response;
        if (chan.t == null) {
            return;
        }
        LockSupport.unpark(chan.t);
    }
}