-
Notifications
You must be signed in to change notification settings - Fork 1.9k
/
ComputeFibonacciContinuationExample.java
185 lines (151 loc) · 7.4 KB
/
ComputeFibonacciContinuationExample.java
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
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.ignite.examples.computegrid;
import org.apache.ignite.*;
import org.apache.ignite.cluster.*;
import org.apache.ignite.compute.*;
import org.apache.ignite.examples.*;
import org.apache.ignite.internal.util.typedef.*;
import org.apache.ignite.lang.*;
import org.apache.ignite.resources.*;
import org.jetbrains.annotations.*;
import java.math.*;
import java.util.*;
import java.util.concurrent.*;
/**
* This example demonstrates how to use continuation feature of Ignite by
* performing the distributed recursive calculation of {@code 'Fibonacci'}
* numbers on the cluster. Continuations
* functionality is exposed via {@link ComputeJobContext#holdcc()} and
* {@link ComputeJobContext#callcc()} method calls in {@link FibonacciClosure} class.
* <p>
* Remote nodes should always be started with special configuration file which
* enables P2P class loading: {@code 'ignite.{sh|bat} examples/config/example-compute.xml'}.
* <p>
* Alternatively you can run {@link ComputeNodeStartup} in another JVM which will start node
* with {@code examples/config/example-compute.xml} configuration.
*/
public final class ComputeFibonacciContinuationExample {
/**
* Executes example.
*
* @param args Command line arguments, none required.
* @throws IgniteException If example execution failed.
*/
public static void main(String[] args) throws IgniteException {
try (Ignite ignite = Ignition.start("examples/config/example-compute.xml")) {
System.out.println();
System.out.println("Compute Fibonacci continuation example started.");
long N = 100;
final UUID exampleNodeId = ignite.cluster().localNode().id();
// Filter to exclude this node from execution.
final IgnitePredicate<ClusterNode> nodeFilter = new IgnitePredicate<ClusterNode>() {
@Override public boolean apply(ClusterNode n) {
// Give preference to remote nodes.
return ignite.cluster().forRemotes().nodes().isEmpty() || !n.id().equals(exampleNodeId);
}
};
long start = System.currentTimeMillis();
BigInteger fib = ignite.compute(ignite.cluster().forPredicate(nodeFilter)).apply(new FibonacciClosure(nodeFilter), N);
long duration = System.currentTimeMillis() - start;
System.out.println();
System.out.println(">>> Finished executing Fibonacci for '" + N + "' in " + duration + " ms.");
System.out.println(">>> Fibonacci sequence for input number '" + N + "' is '" + fib + "'.");
System.out.println(">>> If you re-run this example w/o stopping remote nodes - the performance will");
System.out.println(">>> increase since intermediate results are pre-cache on remote nodes.");
System.out.println(">>> You should see prints out every recursive Fibonacci execution on cluster nodes.");
System.out.println(">>> Check remote nodes for output.");
}
}
/**
* Closure to execute.
*/
private static class FibonacciClosure implements IgniteClosure<Long, BigInteger> {
/** Future for spawned task. */
private IgniteFuture<BigInteger> fut1;
/** Future for spawned task. */
private IgniteFuture<BigInteger> fut2;
/** Auto-inject job context. */
@JobContextResource
private ComputeJobContext jobCtx;
/** Auto-inject ignite instance. */
@IgniteInstanceResource
private Ignite ignite;
/** Predicate. */
private final IgnitePredicate<ClusterNode> nodeFilter;
/**
* @param nodeFilter Predicate to filter nodes.
*/
FibonacciClosure(IgnitePredicate<ClusterNode> nodeFilter) {
this.nodeFilter = nodeFilter;
}
/** {@inheritDoc} */
@Nullable @Override public BigInteger apply(Long n) {
if (fut1 == null || fut2 == null) {
System.out.println();
System.out.println(">>> Starting fibonacci execution for number: " + n);
// Make sure n is not negative.
n = Math.abs(n);
if (n <= 2)
return n == 0 ? BigInteger.ZERO : BigInteger.ONE;
// Node-local storage.
ConcurrentMap<Long, IgniteFuture<BigInteger>> locMap = ignite.cluster().nodeLocalMap();
// Check if value is cached in node-local-map first.
fut1 = locMap.get(n - 1);
fut2 = locMap.get(n - 2);
ClusterGroup p = ignite.cluster().forPredicate(nodeFilter);
IgniteCompute compute = ignite.compute(p).withAsync();
// If future is not cached in node-local-map, cache it.
if (fut1 == null) {
compute.apply(new FibonacciClosure(nodeFilter), n - 1);
fut1 = F.addIfAbsent(locMap, n - 1, compute.<BigInteger>future());
}
// If future is not cached in node-local-map, cache it.
if (fut2 == null) {
compute.apply(new FibonacciClosure(nodeFilter), n - 2);
fut2 = F.addIfAbsent(locMap, n - 2, compute.<BigInteger>future());
}
// If futures are not done, then wait asynchronously for the result
if (!fut1.isDone() || !fut2.isDone()) {
IgniteInClosure<IgniteFuture<BigInteger>> lsnr = new IgniteInClosure<IgniteFuture<BigInteger>>() {
@Override public void apply(IgniteFuture<BigInteger> f) {
// If both futures are done, resume the continuation.
if (fut1.isDone() && fut2.isDone())
// CONTINUATION:
// =============
// Resume suspended job execution.
jobCtx.callcc();
}
};
// CONTINUATION:
// =============
// Hold (suspend) job execution.
// It will be resumed in listener above via 'callcc()' call
// once both futures are done.
jobCtx.holdcc();
// Attach the same listener to both futures.
fut1.listenAsync(lsnr);
fut2.listenAsync(lsnr);
return null;
}
}
assert fut1.isDone() && fut2.isDone();
// Return cached results.
return fut1.get().add(fut2.get());
}
}
}