~statik/etherpad/trunk

« back to all changes in this revision

Viewing changes to infrastructure/net.appjet.oui/dynamicvar.scala

  • Committer: Elliot Murphy
  • Date: 2009-12-19 01:40:46 UTC
  • Revision ID: elliot@elliotmurphy.com-20091219014046-7icbb6oxc29ccdn3
Copied over from zero-history mercurial repo.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
/**
 
2
 * Copyright 2009 Google Inc.
 
3
 * 
 
4
 * Licensed under the Apache License, Version 2.0 (the "License");
 
5
 * you may not use this file except in compliance with the License.
 
6
 * You may obtain a copy of the License at
 
7
 * 
 
8
 *      http://www.apache.org/licenses/LICENSE-2.0
 
9
 * 
 
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
 
 
17
package net.appjet.oui;
 
18
 
 
19
class NoninheritedDynamicVariable[T](init: T) {
 
20
  private val tl = new ThreadLocal[T] {
 
21
    override def initialValue = init.asInstanceOf[T with AnyRef]
 
22
  }
 
23
 
 
24
  /** Retrieve the current value */
 
25
  def value: T = tl.get.asInstanceOf[T]
 
26
  
 
27
   
 
28
  /** Set the value of the variable while executing the specified
 
29
    * thunk.
 
30
    *
 
31
    * @param newval The value to which to set the fluid
 
32
    * @param thunk The code to evaluate under the new setting
 
33
    */
 
34
  def withValue[S](newval: T)(thunk: =>S): S = {
 
35
    val oldval = value
 
36
    tl.set(newval)
 
37
  
 
38
    try { thunk } finally {
 
39
      tl.set(oldval)
 
40
    }
 
41
  }
 
42
 
 
43
  /** Change the currently bound value, discarding the old value.
 
44
    * Usually <code>withValue()</code> gives better semantics.
 
45
    */
 
46
  def value_=(newval: T) = { tl.set(newval) }
 
47
  
 
48
  override def toString: String = "NoninheritedDynamicVariable(" + value  +")"
 
49
}