1 19 20 package org.netbeans.modules.masterfs; 21 22 import java.util.Collections ; 23 import java.util.WeakHashMap ; 24 25 29 final class SyncSection { 30 31 private int exclusiveCounter; 32 private int normalCounter; 33 final private ThreadLocal normalCounterPerThread = new ThreadLocal (); 34 final private ThreadLocal exclusiveCounterPerThread = new ThreadLocal (); 35 final private Object sync = new Object (); 36 private static SyncSection instance; 37 38 39 static SyncSection getDefault() { 40 synchronized (Cache.class) { 41 if (instance == null) { 42 instance = new SyncSection(); 43 } 44 } 45 return instance; 46 } 47 48 49 private SyncSection() { 50 } 51 52 void enterSection() { 53 synchronized (sync) { 54 try { 55 while ((exclusiveCounter - getValue(exclusiveCounterPerThread)) > 0) { 56 sync.wait(); 57 } 58 59 normalCounter++; 60 setValue(normalCounterPerThread, getValue(normalCounterPerThread) + 1); 61 } catch (InterruptedException iex) { 62 iex.printStackTrace(); 63 } 64 } 65 } 66 67 void finishSection() { 68 synchronized (sync) { 69 normalCounter--; 70 setValue(normalCounterPerThread, getValue(normalCounterPerThread) - 1); 71 sync.notifyAll(); 72 } 73 74 } 75 76 80 void enterExclusiveSection() { 81 synchronized (sync) { 82 try { 83 while ((normalCounter - getValue(normalCounterPerThread)) > 0 || 84 (exclusiveCounter - getValue(exclusiveCounterPerThread)) > 0) { 85 sync.wait(); 86 } 87 } catch (InterruptedException iex) { 88 iex.printStackTrace(); 89 } 90 exclusiveCounter++; 91 setValue(exclusiveCounterPerThread, getValue(exclusiveCounterPerThread) + 1); 92 93 } 94 } 95 96 void finishExclusiveSection() { 97 synchronized (sync) { 98 exclusiveCounter--; 99 setValue(exclusiveCounterPerThread, getValue(exclusiveCounterPerThread) - 1); 100 sync.notifyAll(); 101 } 102 } 103 104 private int getValue(ThreadLocal thrVal) { 105 Integer val = (Integer ) thrVal.get(); 106 return (val != null) ? val.intValue() : 0; 107 } 108 109 private void setValue(ThreadLocal thrVal, int value) { 110 thrVal.set(new Integer (value)); 111 } 112 113 } 114 | Popular Tags |