1 4 package com.tctest; 5 6 import com.tc.object.BaseDSOTestCase; 7 8 import java.io.ByteArrayInputStream ; 9 import java.io.ByteArrayOutputStream ; 10 import java.io.IOException ; 11 import java.io.ObjectInputStream ; 12 import java.io.ObjectOutputStream ; 13 import java.io.Serializable ; 14 import java.util.concurrent.ConcurrentHashMap ; 15 import java.util.concurrent.LinkedBlockingQueue ; 16 import java.util.concurrent.locks.ReentrantLock ; 17 18 22 public class JDK15SerializationTest extends BaseDSOTestCase { 23 public void testConcurrentHashMapSerialization() throws Exception { 24 ConcurrentHashMap m = new ConcurrentHashMap (); 25 26 m.put("key1", "value1"); 27 m.put("key2", "value2"); 28 29 checkSerialization(m); 30 31 } 32 33 public void testLinkedBlockingQueueSerialization() throws Exception { 34 LinkedBlockingQueue q = new LinkedBlockingQueue (); 35 q.put("value1"); 36 q.put("value2"); 37 38 checkSerialization(q); 39 } 40 41 public void testReentrantLockSerialization() throws Exception { 42 ReentrantLock lock = new ReentrantLock (); 43 44 lock.lock(); 45 try { 46 ReentrantLock deserializedLock = (ReentrantLock )checkSerialization(lock); 47 assertFalse(deserializedLock.isLocked()); 48 assertTrue(lock.isLocked()); 49 } finally { 50 lock.unlock(); 51 } 52 } 53 54 private Object checkSerialization(Object o) throws Exception { 55 if (!(o instanceof Serializable )) { 56 System.err.println("Skipping non-serializable " + o.getClass().getName()); 57 return null; 58 } 59 60 return validateSerialization(o); 61 } 62 63 private Object validateSerialization(Object o) throws Exception { 64 System.out.println("TESTING " + o.getClass()); 65 assertTrue(o instanceof Serializable ); 66 67 return deserialize(serialize(o)); 68 } 69 70 private static byte[] serialize(Object obj) throws IOException { 71 ByteArrayOutputStream baos = new ByteArrayOutputStream (); 72 ObjectOutputStream oos = new ObjectOutputStream (baos); 73 oos.writeObject(obj); 74 oos.close(); 75 return baos.toByteArray(); 76 } 77 78 private static Object deserialize(byte[] data) throws IOException , ClassNotFoundException { 79 ObjectInputStream ois = new ObjectInputStream (new ByteArrayInputStream (data)); 80 Object rv = ois.readObject(); 81 ois.close(); 82 return rv; 83 } 84 85 } 86 | Popular Tags |