01 /*
02 * Copyright 2009-2012 the original author or authors.
03 *
04 * Licensed under the Apache License, Version 2.0 (the "License");
05 * you may not use this file except in compliance with the License.
06 * You may obtain a copy of the License at
07 *
08 * http://www.apache.org/licenses/LICENSE-2.0
09 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16 package griffon.util;
17
18 /**
19 * A Runnable that can have arguments. <p>
20 * Instances of this class can be seen as substitutes for Closures when dealing
21 * with non-Groovy languages. There are several Griffon core and Griffon plugin APIs
22 * that accept a {@code RunnableWithArgs} where a Closure would be used.</p>
23 * <p>Example:</p>
24 * <pre>
25 Runnable r = new RunnableWithArgs() {
26 public void run(Object[] args) {
27 System.out.println("Hello "+ args[0]);
28 }
29 };
30
31 r.setArgs("world!");
32 r.run();
33 // prints Hello world!
34 r.run(new Object[]{ "again" });
35 // prints Hello again
36 * </pre>
37 *
38 * @author Andres Almiray
39 */
40 public abstract class RunnableWithArgs implements Runnable {
41 private static final Object[] NO_ARGS = new Object[0];
42 private final Object[] lock = new Object[0];
43 private Object[] args = NO_ARGS;
44
45 public void setArgs(Object[] args) {
46 if (args == null) {
47 args = NO_ARGS;
48 }
49 synchronized (lock) {
50 this.args = new Object[args.length];
51 System.arraycopy(args, 0, this.args, 0, args.length);
52 }
53 }
54
55 public Object[] getArgs() {
56 synchronized (lock) {
57 return args;
58 }
59 }
60
61 public final void run() {
62 Object[] copy = null;
63 synchronized (lock) {
64 copy = new Object[args.length];
65 System.arraycopy(args, 0, copy, 0, args.length);
66 }
67 run(copy);
68 }
69
70 public abstract void run(Object[] args);
71 }
|