View Javadoc

1   package cz.cuni.amis.utils.flag;
2   
3   import java.io.Serializable;
4   
5   /**
6    * This class is cruicial in order to have synchronized increments on the integer flag.
7    * <p><p>
8    * The .setFlag() mechanism is very complex and it is sometimes not viable to do .setFlag() call
9    * inside synchronized statements (deadlocks!) therefore we have to solve it inside the class.
10   * 
11   * @author Jimmy
12   *
13   */
14  public class FlagInteger extends Flag<Integer> implements Serializable {
15  	
16  	/**
17  	 * This class extends the DoInSync of the reason that was passed along.
18  	 */
19  	public static abstract class DoInSyncWithReason<T, R> extends DoInSync<T> {
20  		
21  		/**
22  		 * Tells you whether you operate over immutable flag (can't call setFlag() then) or not.
23  		 * @return
24  		 */
25  		protected boolean isImmutable() {
26  			return flag instanceof ImmutableFlag;
27  		}
28  		
29  		/**
30  		 * Set value in sync.
31  		 */
32  		protected void setFlag(T value, R reason) {
33  			if (flag instanceof ImmutableFlag) throw new UnsupportedOperationException("trying to set flag of the immutable flag!");
34  			flag.value = value;
35  			flag.notifier.setValue(value);
36  			flag.listeners.notify(flag.notifier);			
37  		}
38  		
39  		protected T getFlag() {
40  			return flag.getFlag();
41  		}
42  		
43  		/**
44  		 * @param flag
45  		 */
46  		public abstract void execute(T flagValue);
47  		
48  		/**
49  		 * @param flag
50  		 */
51  		public abstract void execute(T flagValue, R reason);
52  		
53  	}
54  	
55  	public FlagInteger() {
56  		super(0);
57  	}
58  	
59  	public FlagInteger(Integer initial) {
60  		super(initial);
61  	}
62  	
63  	public void increment(final int number) {
64  		inSync(
65  			new DoInSync<Integer>() {
66  	
67  				@Override
68  				public void execute(Integer flagValue) {
69  					setFlag(flagValue+number);
70  				}
71  				
72  			}
73  		);
74  	}
75  	
76  	public void decrement(final int number) {
77  		inSync(
78  			new DoInSync<Integer>() {
79  	
80  				@Override
81  				public void execute(Integer flagValue) {
82  					setFlag(flagValue-number);
83  				}
84  				
85  			}
86  		);
87  	}
88  
89  }