01: /*
02: * @(#)sync.java 1.2 04/12/06
03: *
04: * Copyright (c) 2003,2004 Sun Microsystems, Inc. All Rights Reserved.
05: *
06: * See the file "LICENSE.txt" for information on usage and redistribution
07: * of this file, and for a DISCLAIMER OF ALL WARRANTIES.
08: */
09: package org.pnuts.multithread;
10:
11: import java.util.Collections;
12: import java.util.Collection;
13: import java.util.List;
14: import java.util.Set;
15: import java.util.SortedSet;
16: import java.util.Map;
17: import java.util.SortedMap;
18: import pnuts.lang.PnutsFunction;
19: import pnuts.lang.Context;
20:
21: public class sync extends PnutsFunction {
22:
23: public sync() {
24: super ("sync");
25: }
26:
27: public boolean defined(int nargs) {
28: return nargs == 1 || nargs == 2;
29: }
30:
31: static Object sync(Object arg) {
32: return sync(arg, arg);
33: }
34:
35: static Object sync(Object arg, Object lock) {
36: if (arg instanceof PnutsFunction) {
37: PnutsFunction func = (PnutsFunction) arg;
38: return new SynchronizedFunction(func, lock);
39: } else if (arg instanceof Collection) {
40: if (arg instanceof List) {
41: return Collections.synchronizedList((List) arg);
42: } else if (arg instanceof Set) {
43: if (arg instanceof SortedSet) {
44: return Collections
45: .synchronizedSortedSet((SortedSet) arg);
46: } else {
47: return Collections.synchronizedSet((Set) arg);
48: }
49: } else {
50: return Collections
51: .synchronizedCollection((Collection) arg);
52: }
53: } else if (arg instanceof Map) {
54: if (arg instanceof SortedMap) {
55: return Collections
56: .synchronizedSortedMap((SortedMap) arg);
57: } else {
58: return Collections.synchronizedMap((Map) arg);
59: }
60: } else {
61: throw new IllegalArgumentException(String.valueOf(arg));
62: }
63: }
64:
65: protected Object exec(Object[] args, Context context) {
66: int nargs = args.length;
67: if (nargs == 1) {
68: return sync(args[0]);
69: } else if (nargs == 2) {
70: return sync(args[0], args[1]);
71: } else {
72: undefined(args, context);
73: return null;
74: }
75: }
76:
77: public String toString() {
78: return "function sync(func | collection | map {, lock } )";
79: }
80: }
|