Skip to main content
summaryrefslogtreecommitdiffstats
blob: fb56f29d5acf05c05859637fef60a1e24edb4f59 (plain) (blame)
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
/**
 * Copyright (c) 2004 - 2009 Eike Stepper (Berlin, Germany) and others.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 * 
 * Contributors:
 *    Simon McDuff - initial API and implementation
 *    Eike Stepper - maintenance
 */
package org.eclipse.net4j.util.concurrent;

/**
 * Allow synchronization between many threads for a specific value, e.g.:
 * 
 * <pre>
 * MainThread cv.set(1);
 * Thread1 cv.acquire(3);
 * Thread2 cv.acquire(4);
 * Thread3 cv.acquire(100);
 * Thread4 cv.acquire(new Object()
 *   {
 *     public boolean equals(Object other)
 *     {
 *       return other.equals(2) || other.equals(3);
 *     }
 *   });
 * Thread5 cv.acquire(1);
 * ...
 * // Thread 1,2,3 and 4 are blocked
 * // Thread 5 isn't blocked.
 * 
 * MainThread cv.set(3); 
 * 
 * // Thread 1 and 4 are unblocked.
 * // Thread 2 and 3 are still blocked.
 * </pre>
 * 
 * @author Simon McDuff
 * @since 2.0
 */
public final class ConcurrentValue<T>
{
  private Object notifier = new Object();

  private T value;

  public ConcurrentValue(T value)
  {
    this.value = value;
  }

  public T get()
  {
    return value;
  }

  /**
   * Specify the new value.
   */
  public void set(T newValue)
  {
    synchronized (notifier)
    {
      value = newValue;
      notifier.notifyAll();
    }
  }

  /**
   * Reevaluate the condition. It is only useful if a thread is blocked at {@link ConcurrentValue#acquire()} and the
   * parameter passed changed. {@link ConcurrentValue#acquire()} generates a reevaluation automatically.
   */
  public void reevaluate()
  {
    synchronized (notifier)
    {
      notifier.notifyAll();
    }
  }

  /**
   * Blocking call.
   * <p>
   * Return when value accept is equal to {@link ConcurrentValue#get()}.
   */
  public void acquire(Object accept) throws InterruptedException
  {
    if (accept == null)
    {
      throw new IllegalArgumentException("accept == null");
    }

    synchronized (notifier)
    {
      while (!accept.equals(value))
      {
        notifier.wait();
      }
    }
  }
}

Back to the top