1 4 package gnu.text; 5 import java.io.*; 6 7 13 14 public class WriterManager implements Runnable 15 { 16 public static WriterManager instance = new WriterManager(); 17 18 Writer[] ports; 19 int[] freeList; 20 int freeListHead = -1; 21 22 public synchronized int register (Writer port) 23 { 24 if (freeListHead < 0) 25 { 26 int oldSize, newSize; 27 if (ports == null) 28 { 29 oldSize = 0; 30 newSize = 20; 31 } 32 else 33 { 34 oldSize = ports.length; 35 newSize = 2 * oldSize; 36 } 37 int[] newFreeList = new int[newSize]; 38 Writer[] newPorts = new Writer[newSize]; 39 if (oldSize > 0) 40 { 41 System.arraycopy(ports, 0, newPorts, 0, oldSize); 42 System.arraycopy(freeList, 0, newFreeList, 0, oldSize); 43 } 44 for (int i = oldSize; i < newSize; i++) 45 { 46 newFreeList[i] = freeListHead; 47 freeListHead = i; 48 } 49 ports = newPorts; 50 freeList = newFreeList; 51 } 52 int index = freeListHead; 53 ports[index] = port; 54 freeListHead = freeList[index]; 55 freeList[index] = -2; 56 return index + 1; 57 } 58 59 public synchronized void unregister (int index) 60 { 61 if (--index < 0) 62 return; 63 ports[index] = null; 64 freeList[index] = freeListHead; 65 freeListHead = index; 66 } 67 68 public void run() 69 { 70 if (ports == null) 71 return; 72 for (int i = ports.length; --i >= 0; ) 73 { 74 Writer port = ports[i]; 75 try 76 { 77 if (port != null) 78 port.close(); 79 } 80 catch (Exception ex) 81 { 82 } 84 } 85 } 86 87 90 public boolean registerShutdownHook() 91 { 92 try 93 { 94 Runtime runtime = Runtime.getRuntime(); 95 Class rclass = runtime.getClass(); 96 Class [] params = { Thread .class }; 97 java.lang.reflect.Method method 98 = rclass.getDeclaredMethod("addShutdownHook", params); 99 Object [] args = { new Thread (this) }; 100 method.invoke(runtime, args); 101 return true; 102 } 103 catch (Throwable ex) 104 { 105 return false; 106 } 107 } 108 } 109 | Popular Tags |