-
Notifications
You must be signed in to change notification settings - Fork 97
Expand file tree
/
Copy pathBlockingFlush.java
More file actions
73 lines (64 loc) · 1.96 KB
/
BlockingFlush.java
File metadata and controls
73 lines (64 loc) · 1.96 KB
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
package sample;
import com.segment.analytics.Analytics;
import com.segment.analytics.Callback;
import com.segment.analytics.MessageTransformer;
import com.segment.analytics.Plugin;
import com.segment.analytics.messages.Message;
import com.segment.analytics.messages.MessageBuilder;
import java.util.concurrent.Phaser;
/**
* The {@link Analytics} class doesn't come with a blocking {@link Analytics#flush()} implementation
* out of the box. It's trivial to build one using a {@link Phaser} that monitors requests and is
* able to block until they're uploaded.
*
* <pre><code>
* BlockingFlush blockingFlush = BlockingFlush.create();
* Analytics analytics = Analytics.builder(writeKey)
* .plugin(blockingFlush.plugin())
* .build();
*
* // Do some work.
*
* analytics.flush(); // Trigger a flush.
* blockingFlush.block(); // Block until the flush completes.
* analytics.shutdown(); // Shut down after the flush is complete.
* </code></pre>
*/
public class BlockingFlush {
public static BlockingFlush create() {
return new BlockingFlush();
}
BlockingFlush() {
this.phaser = new Phaser(1);
}
final Phaser phaser;
public Plugin plugin() {
return new Plugin() {
@Override
public void configure(Analytics.Builder builder) {
builder.messageTransformer(
new MessageTransformer() {
@Override
public boolean transform(MessageBuilder builder) {
phaser.register();
return true;
}
});
builder.callback(
new Callback() {
@Override
public void success(Message message) {
phaser.arriveAndDeregister();
}
@Override
public void failure(Message message, Throwable throwable) {
phaser.arriveAndDeregister();
}
});
}
};
}
public void block() {
phaser.arriveAndAwaitAdvance();
}
}