| 1 | /* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- |
| 2 | * |
| 3 | * This Source Code Form is subject to the terms of the Mozilla Public |
| 4 | * License, v. 2.0. If a copy of the MPL was not distributed with this |
| 5 | * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ |
| 6 | |
| 7 | // API class |
| 8 | |
| 9 | package org.mozilla.javascript; |
| 10 | |
| 11 | /** |
| 12 | * This class provides support for implementing Java-style synchronized |
| 13 | * methods in Javascript. |
| 14 | * |
| 15 | * Synchronized functions are created from ordinary Javascript |
| 16 | * functions by the <code>Synchronizer</code> constructor, e.g. |
| 17 | * <code>new Packages.org.mozilla.javascript.Synchronizer(fun)</code>. |
| 18 | * The resulting object is a function that establishes an exclusive |
| 19 | * lock on the <code>this</code> object of its invocation. |
| 20 | * |
| 21 | * The Rhino shell provides a short-cut for the creation of |
| 22 | * synchronized methods: <code>sync(fun)</code> has the same effect as |
| 23 | * calling the above constructor. |
| 24 | * |
| 25 | * @see org.mozilla.javascript.Delegator |
| 26 | * @author Matthias Radestock |
| 27 | */ |
| 28 | |
| 29 | public class Synchronizer extends Delegator { |
| 30 | |
| 31 | private Object syncObject; |
| 32 | |
| 33 | /** |
| 34 | * Create a new synchronized function from an existing one. |
| 35 | * |
| 36 | * @param obj the existing function |
| 37 | */ |
| 38 | public Synchronizer(Scriptable obj) { |
| 39 | super(obj); |
| 40 | } |
| 41 | |
| 42 | /** |
| 43 | * Create a new synchronized function from an existing one using |
| 44 | * an explicit object as synchronization object. |
| 45 | * |
| 46 | * @param obj the existing function |
| 47 | * @param syncObject the object to synchronized on |
| 48 | */ |
| 49 | public Synchronizer(Scriptable obj, Object syncObject) { |
| 50 | super(obj); |
| 51 | this.syncObject = syncObject; |
| 52 | } |
| 53 | |
| 54 | /** |
| 55 | * @see org.mozilla.javascript.Function#call |
| 56 | */ |
| 57 | @Override |
| 58 | public Object call(Context cx, Scriptable scope, Scriptable thisObj, |
| 59 | Object[] args) |
| 60 | { |
| 61 | Object sync = syncObject != null ? syncObject : thisObj; |
| 62 | synchronized(sync instanceof Wrapper ? ((Wrapper)sync).unwrap() : sync) { |
| 63 | return ((Function)obj).call(cx,scope,thisObj,args); |
| 64 | } |
| 65 | } |
| 66 | } |