├── README.md ├── src ├── test │ ├── resources │ │ └── com │ │ │ └── shawn │ │ │ └── general │ │ │ └── obj │ └── java │ │ └── com │ │ └── shawn │ │ ├── general │ │ ├── ForkJoinTest.java │ │ ├── GenericTest.java │ │ ├── ThreadTest.java │ │ ├── ClassTest.java │ │ ├── ExceptionTest.java │ │ ├── SerializableTest.java │ │ ├── MethodTest.java │ │ ├── ObjectSizeTest.java │ │ ├── SerializeObject.java │ │ ├── GeneralTest.java │ │ ├── EnumTest.java │ │ ├── StringTest.java │ │ ├── AnnotationTest.java │ │ └── ObjTest.java │ │ ├── nio │ │ ├── WatcherTest.java │ │ ├── BufferTest.java │ │ ├── IOParadigmTest.java │ │ └── JacksonTest.java │ │ ├── template │ │ ├── TestString.java │ │ ├── TestTemplatePerformance.java │ │ ├── TestVariableSegment.java │ │ ├── RegexLearningTest.java │ │ ├── TestTemplateParse.java │ │ └── TestTemplate.java │ │ └── guava │ │ ├── ThrowablesTest.java │ │ ├── RateLimiterTest.java │ │ └── CacheTest.java └── main │ ├── resources │ ├── com │ │ └── shawn │ │ │ └── nio │ │ │ └── blahblah.txt │ └── stocks.txt │ └── java │ └── com │ └── shawn │ ├── object │ ├── Constant.class │ ├── AviodFinalizersTest.java │ ├── HeapOOM.java │ ├── NoninstantiabilityTest.java │ ├── Constant.java │ ├── SingletonTest.java │ ├── EliminateObsoleteRefTest.java │ ├── CreateNoUnecessaryObjTest.java │ ├── ObjectBuilder.java │ └── StaticFactory.java │ ├── template │ ├── Segment.java │ ├── MissingValueException.java │ ├── PlainText.java │ ├── Variable.java │ ├── TemplateParse.java │ └── Template.java │ ├── classNInterface │ ├── MinimizeAccessTest.java │ └── RegexMatchTest.java │ ├── general │ ├── Position.java │ ├── URLDocode.java │ ├── LongObject.java │ ├── TestDate.java │ ├── TestGuava.java │ ├── MinimizeScopeOfLV.java │ ├── PrimitiveVSReferenceType.java │ ├── JsonTest.java │ ├── enumTest.java │ ├── RegexTest.java │ └── GetRealNetworkAddr.java │ ├── nio │ ├── SocketAndChannel.java │ ├── FilterStreamTest.java │ ├── NetworkServer.java │ ├── NetworkClientTest.java │ ├── BufferCharView.java │ ├── InputStreamTest.java │ ├── DigestTest.java │ ├── ChannelCopy.java │ ├── DataSourceTest.java │ ├── ReadFileByChannel.java │ ├── BufferFillAndDrain.java │ ├── RandomPoll.java │ ├── AsyncIO.java │ ├── FileManipulation.java │ ├── FileAttribute.java │ ├── FilePath.java │ ├── GatheringChannelTest.java │ ├── FileModification.java │ ├── EcryptionTest.java │ └── JarFileTest.java │ ├── guru │ ├── Builder.java │ ├── StoreCredit.java │ └── ListTest.java │ ├── lambda │ └── CollectionLambda.java │ ├── enumNAnnotation │ ├── CheckValue.java │ ├── InstanceFieldTest.java │ └── ReplaceConstantTest.java │ ├── methods │ ├── MethodSignature.java │ ├── DefensiveCopies.java │ └── OverloadingTricks.java │ ├── collection │ └── GuavaCollection.java │ ├── concurrent │ ├── atomic │ │ ├── AtomicInteger.java │ │ └── ReorderingDemo.java │ ├── basic │ │ ├── InterruptDemo.java │ │ ├── ObjectLockTest.java │ │ ├── ThreadWithReturnValue.java │ │ ├── SimpleTest.java │ │ ├── ThreadInitExample.java │ │ ├── InterruptionExceptionDemo.java │ │ ├── PriceInfoWithReadWriteLockDemo.java │ │ ├── BasicThreadTest.java │ │ ├── ReentrantLockTest.java │ │ └── BackwardThread.java │ ├── collection │ │ └── AccessingMap.java │ ├── executor │ │ ├── ScheduleExecutor.java │ │ ├── SimpleExecutor.java │ │ └── FactorialCallable.java │ ├── util │ │ ├── PrintQueueWithSemaphore.java │ │ ├── SyncBankAccount.java │ │ ├── CountDownLatchDemo.java │ │ ├── Account.java │ │ ├── QueueLock.java │ │ ├── ExchangeDataInConTask.java │ │ ├── PrintQueueWithMultiRecSemaphore.java │ │ └── ExecutorServer.java │ └── divideAndConquer │ │ └── ComputePrimeNumber.java │ ├── leecode │ ├── Q58LengthOfLastWord.java │ ├── Q27RemoveElement.java │ ├── Q100SameTree.java │ ├── Q1TwoSum.java │ ├── Q83RemoveDuplicatesFromSortedList.java │ ├── Q66PlusOne.java │ ├── Q151ReverseWords.java │ ├── Q26RemoveDuplicatesfromSortedArray.java │ └── Q2AddTwoNumbers.java │ ├── GC │ ├── AllocationForInstance.java │ └── FinalizeEscapeGC.java │ ├── generic │ ├── FooType.java │ ├── UnboundWildcardTest.java │ └── GenericTest.java │ └── IOParadigm │ ├── TimeClient.java │ └── TimeServer.java └── .gitignore /README.md: -------------------------------------------------------------------------------- 1 | only for java test use :: 2 | -------------------------------------------------------------------------------- /src/test/resources/com/shawn/general/obj: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/main/resources/com/shawn/nio/blahblah.txt: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/main/java/com/shawn/object/Constant.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/biubiu/Test/master/src/main/java/com/shawn/object/Constant.class -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.DS_Store 2 | bin 3 | target 4 | .classpath 5 | .project 6 | .settings 7 | src/main/webapp/META-INF 8 | .idea 9 | *.iml 10 | -------------------------------------------------------------------------------- /src/test/java/com/shawn/general/ForkJoinTest.java: -------------------------------------------------------------------------------- 1 | package com.shawn.general; 2 | 3 | /** 4 | * Created by Shangfei on 3/4/16. 5 | */ 6 | public class ForkJoinTest { 7 | } 8 | -------------------------------------------------------------------------------- /src/main/java/com/shawn/template/Segment.java: -------------------------------------------------------------------------------- 1 | package com.shawn.template; 2 | 3 | import java.util.Map; 4 | 5 | public interface Segment { 6 | public String evaluate(Map variables); 7 | } 8 | -------------------------------------------------------------------------------- /src/main/java/com/shawn/classNInterface/MinimizeAccessTest.java: -------------------------------------------------------------------------------- 1 | package com.shawn.classNInterface; 2 | 3 | import java.util.Random; 4 | 5 | public class MinimizeAccessTest { 6 | public static void main(String[] args) { 7 | 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /src/main/java/com/shawn/object/AviodFinalizersTest.java: -------------------------------------------------------------------------------- 1 | package com.shawn.object; 2 | 3 | 4 | /** 5 | * finalizer generally are unpredictable,dangerous and unnecessary 6 | * @author shawncao 7 | */ 8 | public class AviodFinalizersTest { 9 | 10 | } 11 | -------------------------------------------------------------------------------- /src/main/java/com/shawn/template/MissingValueException.java: -------------------------------------------------------------------------------- 1 | package com.shawn.template; 2 | 3 | public class MissingValueException extends RuntimeException{ 4 | 5 | public MissingValueException(String message){ 6 | super(message); 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /src/main/java/com/shawn/general/Position.java: -------------------------------------------------------------------------------- 1 | package com.shawn.general; 2 | 3 | /** 4 | * User: Shawn cao 5 | * Date: 14-5-23 6 | * Time: AM10:11 7 | */ 8 | 9 | import lombok.Data; 10 | 11 | @Data public class Position { 12 | 13 | private String name ; 14 | private String company; 15 | } 16 | -------------------------------------------------------------------------------- /src/main/java/com/shawn/nio/SocketAndChannel.java: -------------------------------------------------------------------------------- 1 | package com.shawn.nio; 2 | 3 | import java.nio.channels.spi.SelectorProvider; 4 | 5 | /** 6 | * User: Shawn cao 7 | * Date: 13-9-13 8 | * Time: PM9:51 9 | */ 10 | public class SocketAndChannel { 11 | 12 | private static void selector(){ 13 | SelectorProvider provider = SelectorProvider.provider(); 14 | 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/main/java/com/shawn/object/HeapOOM.java: -------------------------------------------------------------------------------- 1 | package com.shawn.object; 2 | 3 | 4 | import java.util.ArrayList; 5 | import java.util.List; 6 | 7 | public class HeapOOM { 8 | 9 | static class OOMObject{ 10 | 11 | } 12 | 13 | public static void main(String[] args){ 14 | List list = new ArrayList<>(); 15 | while(true){ 16 | list.add(new OOMObject()); 17 | } 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/com/shawn/object/NoninstantiabilityTest.java: -------------------------------------------------------------------------------- 1 | package com.shawn.object; 2 | 3 | /** 4 | * write class just grouping of static methods and static field 5 | * made noninstantiable by including a private constructor 6 | * @author shawncao 7 | * 8 | */ 9 | public class NoninstantiabilityTest { 10 | 11 | } 12 | 13 | class Utility{ 14 | private Utility() { 15 | throw new AssertionError(); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/main/java/com/shawn/guru/Builder.java: -------------------------------------------------------------------------------- 1 | package com.shawn.guru; 2 | 3 | import java.lang.reflect.Field; 4 | 5 | public class Builder { 6 | 7 | static void classBuilder(Class clazz){ 8 | Field[] fields = clazz.getFields(); 9 | if(fields!=null && fields.length>0){ 10 | for (Field field:fields) { 11 | Class typeClass = field.getType(); 12 | String fieldName = field.getName(); 13 | System.out.println(); 14 | } 15 | } 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/main/java/com/shawn/lambda/CollectionLambda.java: -------------------------------------------------------------------------------- 1 | package com.shawn.lambda; 2 | 3 | import java.util.*; 4 | 5 | /** 6 | * User: Shawn cao 7 | * Date: 14-3-25 8 | * Time: PM12:37 9 | */ 10 | public class CollectionLambda { 11 | 12 | public static void main(String[] args){ 13 | List names = Arrays.asList("peter", "anna", "mike", "xenia"); 14 | Collections.sort(names, (String a, String b) -> b.compareTo(a)); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/test/java/com/shawn/nio/WatcherTest.java: -------------------------------------------------------------------------------- 1 | package com.shawn.nio; 2 | 3 | import org.junit.Test; 4 | 5 | import com.google.common.collect.Lists; 6 | 7 | public class WatcherTest { 8 | 9 | @Test 10 | public void watchProcess() { 11 | try { 12 | Watcher watcher = new Watcher(Lists.newArrayList("/opt/apache-tomcat-7.0.42/logs/catalina.out")); 13 | watcher.process(); 14 | } catch (Exception e) { 15 | } 16 | 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/test/java/com/shawn/template/TestString.java: -------------------------------------------------------------------------------- 1 | package com.shawn.template; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | import org.junit.Test; 7 | 8 | public class TestString { 9 | 10 | 11 | @Test(expected=OutOfMemoryError.class) 12 | public void testStringPadding(){ 13 | List list = new ArrayList<>(); 14 | int i=0; 15 | while(true){ 16 | list.add(String.valueOf(i++).intern()); 17 | } 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/test/java/com/shawn/nio/BufferTest.java: -------------------------------------------------------------------------------- 1 | package com.shawn.nio; 2 | 3 | import org.junit.Test; 4 | import static org.junit.Assert.*; 5 | 6 | public class BufferTest{ 7 | 8 | @Test 9 | public void testStringEqual(){ 10 | String str1 = new StringBuilder("计算机").append("软件").toString(); 11 | String str2 = new StringBuilder("ja").append("va").toString(); 12 | assertTrue(str1.intern() == str1); 13 | assertTrue(str2.intern() == str2); 14 | } 15 | 16 | } 17 | -------------------------------------------------------------------------------- /src/test/java/com/shawn/nio/IOParadigmTest.java: -------------------------------------------------------------------------------- 1 | package com.shawn.nio; 2 | 3 | import com.shawn.IOParadigm.TimeServer; 4 | import junit.framework.TestCase; 5 | import org.junit.Test; 6 | 7 | /** 8 | * User: Shawn cao 9 | * Date: 14-5-16 10 | * Time: PM4:59 11 | */ 12 | public class IOParadigmTest extends TestCase { 13 | 14 | @Test 15 | public void testSingleThreadModule(){ 16 | TimeServer timeServer = new TimeServer(); 17 | timeServer.start(8080); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/com/shawn/enumNAnnotation/CheckValue.java: -------------------------------------------------------------------------------- 1 | package com.shawn.enumNAnnotation; 2 | 3 | import java.lang.annotation.ElementType; 4 | import java.lang.annotation.Retention; 5 | import java.lang.annotation.RetentionPolicy; 6 | import java.lang.annotation.Target; 7 | 8 | /** 9 | * User: Shawn cao 10 | * Date: 13-3-24 11 | * Time: PM6:53 12 | */ 13 | @Target(value = ElementType.FIELD) 14 | @Retention(value = RetentionPolicy.RUNTIME) 15 | public @interface CheckValue { 16 | Class value(); 17 | } 18 | -------------------------------------------------------------------------------- /src/main/java/com/shawn/template/PlainText.java: -------------------------------------------------------------------------------- 1 | package com.shawn.template; 2 | 3 | import java.util.Map; 4 | 5 | public class PlainText implements Segment{ 6 | private String text; 7 | 8 | public PlainText(String text){ 9 | this.text = text; 10 | } 11 | 12 | @Override 13 | public String evaluate(Map variables){ 14 | return text; 15 | } 16 | 17 | 18 | public boolean equals(Object other){ 19 | return text.equals(((PlainText)other).text); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/main/java/com/shawn/template/Variable.java: -------------------------------------------------------------------------------- 1 | package com.shawn.template; 2 | 3 | import java.util.Map; 4 | 5 | public class Variable implements Segment{ 6 | 7 | private String name; 8 | public Variable(String name){ 9 | this.name = name; 10 | } 11 | 12 | @Override 13 | public String evaluate(Map variables){ 14 | return variables.get(name); 15 | } 16 | 17 | public boolean equals(Object other){ 18 | return name.equals(((Variable)other).name); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/main/java/com/shawn/methods/MethodSignature.java: -------------------------------------------------------------------------------- 1 | package com.shawn.methods; 2 | /** 3 | * 4 | * @author shawncao 5 | *choose name carefully 6 | *don't go overbroad in providing convenience methods 7 | *avoid long parameter lists---1.break into multiple methods 8 | * 2.create helper to hold group of params,static member class 9 | *for parameter types, favor interfaces over classes 10 | *prefer 2-elements enum types to boolean params 11 | * e.g. public enum scale{FAHERENHEIT,CELSIUS} 12 | */ 13 | public class MethodSignature { 14 | 15 | } 16 | -------------------------------------------------------------------------------- /src/main/resources/stocks.txt: -------------------------------------------------------------------------------- 1 | AAPL,2505 2 | AMGN,3406 3 | AMZN,9354 4 | BAC,9839 5 | BMY,5099 6 | CAT,8463 7 | C,1500 8 | CMCSA,6144 9 | CSCO,4589 10 | CVX,9696 11 | DELL,3908 12 | DIS,4804 13 | DOW,3654 14 | EMC,4835 15 | FDX,4753 16 | GD,3919 17 | GE,7003 18 | GOOG,6631 19 | HAL,2593 20 | HNZ,4277 21 | HPQ,6157 22 | IBM,1728 23 | INTC,4053 24 | JPM,1665 25 | KFT,3669 26 | LMT,4402 27 | MET,3712 28 | MO,3764 29 | MSFT,2813 30 | NKE,6447 31 | NSC,5537 32 | ORCL,7136 33 | PFE,659 34 | RTN,5063 35 | S,8219 36 | SO,7175 37 | TXN,1410 38 | USB,3099 39 | VZ,9826 40 | WMT,6478 -------------------------------------------------------------------------------- /src/test/java/com/shawn/template/TestTemplatePerformance.java: -------------------------------------------------------------------------------- 1 | package com.shawn.template; 2 | import static org.junit.Assert.assertTrue; 3 | public class TestTemplatePerformance { 4 | private Template template; 5 | public void templateWith100WordsAnd20Variables(){ 6 | long expected = 200L; 7 | long time = System.currentTimeMillis(); 8 | template.evaluate(); 9 | time = System.currentTimeMillis() - time; 10 | assertTrue("Rendering the template took " + time + " ms while the target was " + expected + "ms",time>=expected); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/main/java/com/shawn/general/URLDocode.java: -------------------------------------------------------------------------------- 1 | package com.shawn.general; 2 | 3 | import java.io.UnsupportedEncodingException; 4 | 5 | import java.net.URLDecoder; 6 | 7 | public class URLDocode { 8 | public static void main(String[] args) throws UnsupportedEncodingException { 9 | String decode = "keyword%3A%28%28%22js%E5%B7%A5%E7%A8%8B%E5%B8%88%22+%29%29+AND+flag%3A%28s+OR+t+OR+r%29&start=0&rows=100&sort=modifyTime+desc%2Cscore+desc"; 10 | System.out.println("decoded: "); 11 | System.out.println(new URLDecoder().decode(decode, "UTF-8").toString()); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /src/test/java/com/shawn/general/GenericTest.java: -------------------------------------------------------------------------------- 1 | package com.shawn.general; 2 | 3 | import com.google.common.collect.Lists; 4 | 5 | import java.util.ArrayList; 6 | import java.util.List; 7 | 8 | 9 | 10 | /** 11 | * @author Shawn Cao 12 | */ 13 | public class GenericTest { 14 | 15 | public void testParameterisedType(){ 16 | List list = new ArrayList(); 17 | list.add(12); 18 | 19 | List list2 = Lists.newArrayList(); 20 | list2.add(Double.valueOf(1.22)); 21 | list2.remove(Double.valueOf(1.22)); 22 | } 23 | 24 | 25 | 26 | } 27 | -------------------------------------------------------------------------------- /src/main/java/com/shawn/collection/GuavaCollection.java: -------------------------------------------------------------------------------- 1 | package com.shawn.collection; 2 | 3 | import java.util.Set; 4 | 5 | import com.google.common.collect.Sets; 6 | import com.google.common.collect.Sets.SetView; 7 | 8 | public class GuavaCollection { 9 | public static void main(String[] args) { 10 | Set setA = Sets.newHashSet(1,2,3,4,5,6); 11 | Set setB = Sets.newHashSet(1,2,3,4,5,6,7,8); 12 | SetView interSet = Sets.intersection(setA, setB); 13 | interSet = Sets.difference(setB, setA); 14 | for (Integer i: interSet) { 15 | System.out.println(i); 16 | } 17 | } 18 | 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/com/shawn/general/LongObject.java: -------------------------------------------------------------------------------- 1 | package com.shawn.general; 2 | 3 | import com.google.common.base.Stopwatch; 4 | import javafx.scene.paint.Stop; 5 | 6 | import java.util.concurrent.TimeUnit; 7 | 8 | /** 9 | * @author Shawn Cao 10 | */ 11 | public class LongObject { 12 | 13 | public static void main(String[] args){ 14 | Stopwatch stopwatch = Stopwatch.createStarted(); 15 | long sum = 0L; 16 | for(long i = 0; i0){ 21 | return strs[strs.length-1].length(); 22 | } 23 | return 0; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/test/java/com/shawn/general/ThreadTest.java: -------------------------------------------------------------------------------- 1 | package com.shawn.general; 2 | 3 | import java.util.concurrent.TimeUnit; 4 | 5 | /** 6 | * @author Shawn Cao 7 | */ 8 | public class ThreadTest { 9 | private static volatile boolean stopThread; 10 | 11 | public static void main(String[] args) throws InterruptedException { 12 | Thread backgroundThread = new Thread(new Runnable() { 13 | @Override 14 | public void run() { 15 | int i=0; 16 | while(!stopThread){ 17 | i++; 18 | } 19 | } 20 | }); 21 | backgroundThread.start(); 22 | TimeUnit.SECONDS.sleep(1); 23 | stopThread = true; 24 | } 25 | } 26 | 27 | 28 | -------------------------------------------------------------------------------- /src/main/java/com/shawn/general/TestDate.java: -------------------------------------------------------------------------------- 1 | package com.shawn.general; 2 | 3 | import org.joda.time.DateTime; 4 | import org.joda.time.DateTimeUtils; 5 | import org.joda.time.Days; 6 | 7 | public class TestDate { 8 | public static void main(String[] args) { 9 | DateTime dateTime = new DateTime(); 10 | DateTime threeDaysBefore = dateTime.minus(3*3600*24*1000); 11 | DateTime fifteenDaysBefore = dateTime.minus(15*3600*24*1000); 12 | DateTime thirtyDaysBefore = dateTime.minus(30L*3600L*24L*1000L); 13 | System.out.println("Days " + threeDaysBefore.toString() ); 14 | System.out.println("15 Days " + fifteenDaysBefore.toString()); 15 | System.out.println("30 Days " + "|"+ new Long(30*3600*24*1000) +"|" +thirtyDaysBefore.toString()); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/main/java/com/shawn/general/TestGuava.java: -------------------------------------------------------------------------------- 1 | package com.shawn.general; 2 | 3 | import java.util.List; 4 | 5 | import com.google.common.base.Function; 6 | import com.google.common.collect.Collections2; 7 | import com.google.common.collect.Lists; 8 | 9 | public class TestGuava { 10 | 11 | public static void main(String[] args) { 12 | List strs = Lists.newArrayList("shawnCao@tianji.com","millll@oaid.COM","ad@ad.com",""); 13 | List after = Lists.transform(strs, new Function() { 14 | public String apply(String input) { 15 | return input.toLowerCase(); 16 | } 17 | }); 18 | for (String t: after) { 19 | System.out.println(t.toString()); 20 | } 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/main/java/com/shawn/leecode/Q27RemoveElement.java: -------------------------------------------------------------------------------- 1 | package com.shawn.leecode; 2 | 3 | import java.util.Arrays; 4 | 5 | /** 6 | * User: Shawn cao 7 | * Date: 14/12/26 8 | * Time: PM3:31 9 | */ 10 | /* 11 | Given an array and a value, remove all instances of that value in place and return the new length. 12 | The order of elements can be changed. It doesn't matter what you leave beyond the new length. 13 | */ 14 | 15 | public class Q27RemoveElement { 16 | public int removeElement(int[] A, int elem) { 17 | int tail = A.length-1; 18 | int i = 0; 19 | while ( i<=tail ){ 20 | if (A[i]==elem){ 21 | A[i] = A[tail--]; 22 | continue; 23 | } 24 | i++; 25 | } 26 | 27 | return tail+1; 28 | 29 | 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/main/java/com/shawn/object/Constant.java: -------------------------------------------------------------------------------- 1 | package com.shawn.object; 2 | 3 | import java.lang.ref.WeakReference; 4 | 5 | /** 6 | * Created with IntelliJ IDEA. 7 | * User: caocao024 8 | * Date: 13-1-17 9 | * Time: PM12:38 10 | * To change this template use File | Settings | File Templates. 11 | */ 12 | public class Constant { 13 | static final int number1 = 5; 14 | 15 | static final int number2 = 6; 16 | 17 | static int number3 = 5; 18 | 19 | static int number4= 6; 20 | 21 | public static void main(String[ ] args) { 22 | 23 | WeakReference ints = new WeakReference(new Integer(4)); 24 | System.out.println(ints.get()); 25 | 26 | int product1 = number1 * number2; //line A 27 | 28 | int product2 = number3 * number4; //line B 29 | 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/main/java/com/shawn/leecode/Q100SameTree.java: -------------------------------------------------------------------------------- 1 | package com.shawn.leecode; 2 | 3 | /** 4 | * User: Shawn cao 5 | * Date: 15/1/4 6 | * Time: PM5:54 7 | */ 8 | 9 | import java.util.ArrayList; 10 | import java.util.Queue; 11 | import java.util.concurrent.ArrayBlockingQueue; 12 | 13 | /** 14 | * Given two binary trees, write a function to check if they are equal or not. 15 | 16 | Two binary trees are considered equal if they are structurally identical and the nodes have the same value. 17 | */ 18 | public class Q100SameTree { 19 | public boolean isSameTree(TreeNode p, TreeNode q) { 20 | 21 | 22 | return false; 23 | } 24 | 25 | public class TreeNode { 26 | int val; 27 | TreeNode left; 28 | TreeNode right; 29 | 30 | TreeNode(int x) { 31 | val = x; 32 | } 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/main/java/com/shawn/object/SingletonTest.java: -------------------------------------------------------------------------------- 1 | package com.shawn.object; 2 | 3 | /* 4 | * singleton -->class is instantiated exactly once,only one instance ,no more no less 5 | */ 6 | public class SingletonTest { 7 | 8 | } 9 | 10 | class Elvis{ 11 | 12 | //singleton : make member a final field 13 | public static final Elvis INSTANCE = new Elvis(); 14 | private Elvis(){} 15 | //singleton: public member is a static factory method 16 | public static Elvis getInstance(){ 17 | return INSTANCE; 18 | } 19 | 20 | //each time a serialized instance is deserializaed ,a new instance will be creted 21 | private Object readResolve(){ 22 | return INSTANCE; 23 | } 24 | 25 | //singleton:serialization mechinery for free, best way to implement a singleton 26 | public enum ElvisInstance{ 27 | INSTACE; 28 | } 29 | 30 | } 31 | -------------------------------------------------------------------------------- /src/test/java/com/shawn/guava/ThrowablesTest.java: -------------------------------------------------------------------------------- 1 | package com.shawn.guava; 2 | 3 | import com.google.common.base.Throwables; 4 | import org.junit.Test; 5 | 6 | import java.io.IOException; 7 | 8 | /** 9 | * User: Shawn cao 10 | * Date: 14-6-10 11 | * Time: AM9:38 12 | */ 13 | public class ThrowablesTest { 14 | 15 | @Test 16 | public void testThrowable(){ 17 | try{ 18 | throw new Exception(); 19 | }catch(Throwable t){ 20 | String ss = Throwables.getStackTraceAsString(t); 21 | System.out.println(ss); 22 | Throwables.propagate(t); 23 | } 24 | } 25 | 26 | @Test 27 | public void call() throws IOException{ 28 | try{ 29 | throw new IOException(); 30 | }catch(Throwable t){ 31 | Throwables.propagateIfInstanceOf(t,IOException.class); 32 | throw Throwables.propagate(t); 33 | } 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/main/java/com/shawn/concurrent/atomic/ReorderingDemo.java: -------------------------------------------------------------------------------- 1 | package com.shawn.concurrent.atomic; 2 | 3 | public class ReorderingDemo { 4 | 5 | static int x = 0, y = 0, a = 0, b = 0; 6 | 7 | public static void main(String[] args) throws Exception { 8 | 9 | for (int i = 0; i < 100; i++) { 10 | x=y=a=b=0; 11 | Thread one = new Thread() { 12 | public void run() { 13 | a = 1; 14 | x = b; 15 | } 16 | }; 17 | Thread two = new Thread() { 18 | public void run() { 19 | b = 1; 20 | y = a; 21 | } 22 | }; 23 | one.start(); 24 | two.start(); 25 | //one.join(); 26 | //two.join(); 27 | System.out.println(x + " " + y); 28 | 29 | } 30 | } 31 | 32 | } 33 | -------------------------------------------------------------------------------- /src/main/java/com/shawn/general/MinimizeScopeOfLV.java: -------------------------------------------------------------------------------- 1 | package com.shawn.general; 2 | 3 | import java.math.BigDecimal; 4 | 5 | /** 6 | * 7 | * @author shawncao 8 | *minimizing the scope of a local variable 9 | *1.declare it where it is first used 10 | *2.every local variable declaration should contain a initializer 11 | *3. prefer for loop over while(less local variable than while) 12 | *for each over for loops 13 | * 1.filtering:traverse and remove using iterator 14 | * 2.transforming: traverse and replacel,list iterator or array 15 | * 3.parallel: iteration:traverse multiple,explicity control over iterator or index 16 | */ 17 | public class MinimizeScopeOfLV { 18 | public static void main(String[] args) { 19 | System.out.println(1.00-(0.9*1.00)); 20 | 21 | BigDecimal bigDecimal = BigDecimal.valueOf(1.00); 22 | BigDecimal bigDecimal2 = BigDecimal.valueOf(0.9); 23 | System.out.println(bigDecimal.subtract(bigDecimal2).multiply(BigDecimal.valueOf(1.00))); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/main/java/com/shawn/leecode/Q1TwoSum.java: -------------------------------------------------------------------------------- 1 | package com.shawn.leecode; 2 | 3 | 4 | 5 | import java.util.LinkedHashMap; 6 | import java.util.Map; 7 | 8 | /** 9 | * User: Shawn cao 10 | * Date: 14/12/24 11 | * Time: PM12:08 12 | */ 13 | public class Q1TwoSum { 14 | 15 | public static int[] twoSum(int[] numbers, int target){ 16 | 17 | 18 | Map m = new LinkedHashMap<>((int)Math.ceil(numbers.length / 0.7)); 19 | int[] result = new int[2]; 20 | for(int i=0; i variables; 14 | 15 | @Before 16 | public void setUp(){ 17 | variables = new HashMap<>(); 18 | } 19 | 20 | @Test 21 | public void variableEvaluatsToValue(){ 22 | String name = "myvar"; 23 | String value = "myvalue"; 24 | variables.put(name, value); 25 | assertEquals(value, new Variable(name).evaluate(variables)); 26 | } 27 | 28 | @Test(expected = MissingValueException.class) 29 | public void missingVariableRaisingException(){ 30 | String name = "myvar"; 31 | double value = 0.0; 32 | assertEquals(value, new Variable(name).evaluate(variables)); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/main/java/com/shawn/leecode/Q83RemoveDuplicatesFromSortedList.java: -------------------------------------------------------------------------------- 1 | package com.shawn.leecode; 2 | 3 | /** 4 | * User: Shawn cao 5 | * Date: 14/12/31 6 | * Time: PM2:29 7 | */ 8 | /* 9 | Given a sorted linked list, delete all duplicates such that each element appear only once. 10 | 11 | For example, 12 | Given 1->1->2, return 1->2. 13 | Given 1->1->2->3->3, return 1->2->3. 14 | */ 15 | public class Q83RemoveDuplicatesFromSortedList { 16 | public ListNode deleteDuplicates(ListNode head) { 17 | for(ListNode p=head; p!=null && p.next!=null; ){ 18 | if (p.val == p.next.val){ 19 | p.next = p.next.next; 20 | continue; 21 | } 22 | p=p.next; 23 | } 24 | return head; 25 | } 26 | 27 | 28 | 29 | public static class ListNode { 30 | int val; 31 | ListNode next; 32 | ListNode(int x) { 33 | val = x; 34 | next = null; 35 | } 36 | } 37 | } 38 | 39 | -------------------------------------------------------------------------------- /src/main/java/com/shawn/GC/AllocationForInstance.java: -------------------------------------------------------------------------------- 1 | package com.shawn.GC; 2 | 3 | /** 4 | * User: Shawn cao 5 | * Date: 14-5-23 6 | * Time: PM5:37 7 | * 8 | * test1 -verbose:gc -Xms20M -Xmx20M -Xmn10M -XX:+PrintGCDetails -XX:SurvivorRatio=8 9 | * test2 -XX:PretenureSizeThreshold=3145728 10 | */ 11 | public class AllocationForInstance { 12 | 13 | private static final int _1MB = 1024 * 1024; 14 | 15 | public static void main(String[] args) throws Exception{ 16 | testAllocation(); 17 | Thread.sleep(500); 18 | testAllocation(); 19 | } 20 | 21 | public static void testAllocation(){ 22 | byte[] allocation1,allocation2,allocation3,allocation4 ; 23 | allocation1 = new byte[2*_1MB]; 24 | allocation2 = new byte[2*_1MB]; 25 | allocation3 = new byte[2*_1MB]; 26 | //in test1: execute a minor GC because the space in Eden region (8M)is not enough for allocation4 27 | //in test2: assign in old generation region. 28 | allocation4 = new byte[4*_1MB]; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/test/java/com/shawn/general/ClassTest.java: -------------------------------------------------------------------------------- 1 | package com.shawn.general; 2 | 3 | import org.junit.Test; 4 | import java.util.Date; 5 | 6 | /** 7 | * @author Shawn Cao 8 | */ 9 | public class ClassTest { 10 | 11 | @Test 12 | public void testSub(){ 13 | Sub sub = new Sub(); 14 | sub.overrideMe(); 15 | } 16 | } 17 | 18 | 19 | class A{ 20 | int a; 21 | int b; 22 | 23 | protected void setA(){ 24 | 25 | } 26 | } 27 | 28 | interface C{ 29 | void c(); 30 | } 31 | class B extends A implements C{ 32 | 33 | @Override 34 | public void setA() { 35 | super.setA(); 36 | } 37 | 38 | @Override 39 | public void c() { 40 | 41 | } 42 | } 43 | 44 | 45 | class Super{ 46 | 47 | public Super(){ 48 | overrideMe(); 49 | } 50 | 51 | public void overrideMe(){ 52 | 53 | } 54 | } 55 | 56 | 57 | final class Sub extends Super{ 58 | 59 | private final Date date; 60 | 61 | Sub(){ 62 | date = new Date(); 63 | } 64 | 65 | @Override 66 | public void overrideMe() { 67 | System.out.println(date); 68 | } 69 | } -------------------------------------------------------------------------------- /src/main/java/com/shawn/nio/FilterStreamTest.java: -------------------------------------------------------------------------------- 1 | package com.shawn.nio; 2 | 3 | import java.io.*; 4 | import java.nio.file.Paths; 5 | import java.util.jar.JarFile; 6 | 7 | /** 8 | * User: Shawn cao 9 | * Date: 13-10-13 10 | * Time: PM10:06 11 | */ 12 | public class FilterStreamTest { 13 | 14 | public static void main(String[] args) throws IOException { 15 | File file = new File("/Users/caocao024/workspace/Test/src/main/java/com/shawn/nio/FilterStreamTest.java"); 16 | copy(new FileInputStream(file),System.out); 17 | } 18 | 19 | public static void copy(InputStream in,OutputStream out) throws IOException { 20 | BufferedInputStream bufferedInputStream = new BufferedInputStream(in); 21 | BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(out); 22 | while(true){ 23 | int datum = bufferedInputStream.read(); 24 | if(datum!=-1){ 25 | bufferedOutputStream.write(datum); 26 | bufferedOutputStream.flush(); 27 | }else { 28 | break; 29 | } 30 | 31 | } 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/test/java/com/shawn/general/ExceptionTest.java: -------------------------------------------------------------------------------- 1 | package com.shawn.general; 2 | 3 | import com.google.common.base.Strings; 4 | import com.google.common.collect.Lists; 5 | import org.junit.Test; 6 | 7 | import java.util.List; 8 | import java.util.Optional; 9 | 10 | import static org.junit.Assert.fail; 11 | 12 | 13 | /** 14 | * @author Shawn Cao 15 | */ 16 | public class ExceptionTest { 17 | 18 | 19 | 20 | @Test 21 | public void testChecked(){ 22 | String str1="aaa",str2="bbb",str3=""; 23 | checkNull(str1); 24 | checkNull(str2); 25 | try{ 26 | checkNull(str3); 27 | fail(); 28 | }catch (IllegalArgumentException e){ 29 | System.out.println(e.getMessage()); 30 | } 31 | } 32 | 33 | private void checkNull(String str){ 34 | if(Strings.isNullOrEmpty(str)){ 35 | throw new IllegalArgumentException("input cannot be null"); 36 | } 37 | } 38 | 39 | @Test 40 | public void testOptional(){ 41 | List l = null; 42 | Optional o =Optional.ofNullable(l); 43 | System.out.println(o); 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /src/main/java/com/shawn/concurrent/basic/InterruptDemo.java: -------------------------------------------------------------------------------- 1 | package com.shawn.concurrent.basic; 2 | 3 | import java.util.concurrent.TimeUnit; 4 | 5 | public class InterruptDemo { 6 | public static void main(String[] args) { 7 | Thread task = new Thread(new PrimeGenerator()); 8 | task.start(); 9 | try { 10 | TimeUnit.MILLISECONDS.sleep(500); 11 | } catch (InterruptedException e) { 12 | e.printStackTrace(); 13 | } 14 | task.interrupt(); 15 | 16 | } 17 | } 18 | 19 | class PrimeGenerator implements Runnable{ 20 | 21 | @Override 22 | public void run() { 23 | long number = 1L; 24 | while(true){ 25 | if(isPrime(number)){ 26 | System.out.printf("Number %d is Prime \n ",number); 27 | } 28 | if(Thread.currentThread().isInterrupted()){ 29 | System.out.println("The prime generator has been interrupted"); 30 | return; 31 | } 32 | number++; 33 | } 34 | } 35 | 36 | private boolean isPrime(long number){ 37 | if(number <= 2){ 38 | return true; 39 | } 40 | for(long i = 2;i= 0 ; i--){ 20 | int tmp = digits[i]; 21 | tmp += carry; 22 | if(tmp >= 10){ 23 | digits[i] = tmp -10 ; 24 | } else{ 25 | digits[i] = tmp; 26 | carry = 0; 27 | } 28 | } 29 | 30 | if(carry == 1){ 31 | int[] result = new int[digits.length+1]; 32 | result[0] = carry; 33 | for(int i=1;i listHelper = new ListHelper(); 10 | public static void main(String[] args) throws InterruptedException { 11 | listHelper.list.add(1); 12 | listHelper.list.add(2); 13 | listHelper.list.add(3); 14 | Thread[] threads = new Thread[10]; 15 | for (int i = 0; i < threads.length; i++) { 16 | threads[i]= new Thread(new Runnable() { 17 | public void run() { 18 | listHelper.putIfAbsent(10); 19 | } 20 | }); 21 | threads[i].start(); 22 | threads[i].join(); 23 | } 24 | for (int i = 0; i < listHelper.list.size(); i++) { 25 | System.out.println(listHelper.list.get(i)); 26 | } 27 | } 28 | } 29 | 30 | 31 | class ListHelper{ 32 | public List list = Collections.synchronizedList(new LinkedList()); 33 | public boolean putIfAbsent(E x){ 34 | synchronized (list) { 35 | boolean absent = !list.contains(x); 36 | if(absent) 37 | list.add(x); 38 | return absent; 39 | } 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /src/main/java/com/shawn/leecode/Q151ReverseWords.java: -------------------------------------------------------------------------------- 1 | package com.shawn.leecode; 2 | 3 | import com.google.common.base.Joiner; 4 | 5 | import java.util.Arrays; 6 | 7 | /** 8 | * User: Shawn cao 9 | * Date: 14/12/31 10 | * Time: AM11:22 11 | */ 12 | /* 13 | Given an input string, reverse the string word by word. 14 | 15 | For example, 16 | Given s = "the sky is blue", 17 | return "blue is sky the". 18 | 19 | 20 | Clarification: 21 | What constitutes a word? 22 | A sequence of non-space characters constitutes a word. 23 | Could the input string contain leading or trailing spaces? 24 | Yes. However, your reversed string should not contain leading or trailing spaces. 25 | How about multiple spaces between two words? 26 | Reduce them to a single space in the reversed string. 27 | */ 28 | public class Q151ReverseWords { 29 | public String reverseWords(String s) { 30 | String[] words = s.trim().split("\\s+"); 31 | 32 | StringBuilder sb = new StringBuilder(s.length()); 33 | for(int i=words.length-1; i>=0; i--){ 34 | sb.append(words[i]); 35 | if(i >0) 36 | sb.append(" "); 37 | } 38 | return sb.toString(); 39 | } 40 | 41 | } 42 | -------------------------------------------------------------------------------- /src/main/java/com/shawn/enumNAnnotation/InstanceFieldTest.java: -------------------------------------------------------------------------------- 1 | package com.shawn.enumNAnnotation; 2 | 3 | /** 4 | * Created with IntelliJ IDEA. 5 | * User: caocao024 6 | * Date: 13-1-30 7 | * Time: PM8:56 8 | * To change this template use File | Settings | File Templates. 9 | */ 10 | public class InstanceFieldTest { 11 | 12 | public static void main(String[] args){ 13 | String m = "SOLO" ; 14 | switch(Ensemble.valueOf(m)){ 15 | case SOLO: 16 | System.out.println("solo..."); 17 | break; 18 | case DECTET: 19 | System.out.println("dectet..."); 20 | break; 21 | default: 22 | throw new AssertionError(); 23 | } 24 | } 25 | } 26 | 27 | enum Ensemble{ 28 | /* 29 | Never derive a value associated with an enum from its ordinal; store it in an instance field instead: 30 | */ 31 | SOLO(1), DUET(2), TRIO(3), QUARTET(4), QUINTET(5), 32 | SEXTET(6), SEPTET(7), OCTET(8), DOUBLE_QUARTET(8), 33 | NONET(9), DECTET(10), TRIPLE_QUARTET(12); 34 | 35 | private final Integer number; 36 | private Ensemble(Integer number){ 37 | this.number = number; 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/main/java/com/shawn/general/PrimitiveVSReferenceType.java: -------------------------------------------------------------------------------- 1 | package com.shawn.general; 2 | 3 | import java.util.Comparator; 4 | 5 | /** 6 | * 7 | * @author shawncao 8 | * when mix primitives and boxed primitives in a single operation, the boxed primitive is autounboxed 9 | * autoboxing reduces the verbosity, but not the danger to using boxed primitives 10 | * Alternatively ,it can throw a NullPointerException 11 | */ 12 | public class PrimitiveVSReferenceType { 13 | 14 | 15 | public static void comparatorTest(){ 16 | Comparator naturalOrder = new Comparator() { 17 | public int compare(Integer first,Integer second){ 18 | //first and second refer to same value but in different mem location where lead to== return false 19 | return first correctNaturalOrder = new Comparator() { 24 | public int compare(Integer first,Integer second){ 25 | int f = first;//auto unboxing 26 | int s = second; 27 | return f { 9 | public void test(final Collection collection){ 10 | for(final E e:collection){ 11 | System.out.println("E: " + e); 12 | } 13 | } 14 | 15 | public void test(final Set sets){ 16 | for(final T t:sets){ 17 | System.out.println("T from set: " + t); 18 | } 19 | } 20 | 21 | public void test(final List intList){ 22 | int result = 0 ; 23 | for(final Integer integer: intList){ 24 | result+=integer.intValue(); 25 | } 26 | System.out.println("result: " + result); 27 | } 28 | 29 | public static void main(String[] args) { 30 | /* final FooType fooType = new FooType<>(); 31 | final List list = Arrays.asList("some","test","value"); 32 | fooType.test(list);*/ 33 | 34 | final FooType ints = new FooType<>(); 35 | final List intList = Arrays.asList(1,2,3,4,5); 36 | ints.test(intList); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /src/test/java/com/shawn/general/MethodTest.java: -------------------------------------------------------------------------------- 1 | package com.shawn.general; 2 | 3 | import java.util.*; 4 | 5 | /** 6 | * @author Shawn Cao 7 | */ 8 | public class MethodTest { 9 | 10 | public static void main(String[] args){ 11 | //new MethodA().m1(-1); 12 | //removeElement(); 13 | List list = new ArrayList<>(); 14 | list.add("aaaa"); 15 | list.remove(new Integer(0)); 16 | System.out.println(list); 17 | 18 | 19 | } 20 | 21 | 22 | public static void removeElement(){ 23 | Set set = new TreeSet<>(); 24 | List list = new ArrayList<>(); 25 | 26 | for(int i = -3; i<3; i++){ 27 | set.add(i); 28 | list.add(i); 29 | } 30 | 31 | for(int i= 0; i< 3; i++){ 32 | set.remove(i); 33 | list.remove((Integer)i); 34 | } 35 | 36 | System.out.println(set + " " + list); 37 | } 38 | } 39 | 40 | 41 | class MethodA{ 42 | 43 | public void m1(int a){ 44 | m2(a, "a"); 45 | } 46 | 47 | private void m2(int a,String b){ 48 | assert a>=0; 49 | assert b!=null; 50 | 51 | System.out.println(10/a + " " + b); 52 | } 53 | } 54 | 55 | 56 | -------------------------------------------------------------------------------- /src/main/java/com/shawn/concurrent/collection/AccessingMap.java: -------------------------------------------------------------------------------- 1 | package com.shawn.concurrent.collection; 2 | 3 | import java.util.Collections; 4 | import java.util.HashMap; 5 | import java.util.Map; 6 | import java.util.concurrent.ConcurrentHashMap; 7 | 8 | public class AccessingMap { 9 | public static void main(String[] args) { 10 | System.out.println("Using plain map:"); 11 | useMap(new HashMap()); 12 | 13 | System.out.println("Using Synchronized map: "); 14 | useMap(Collections.synchronizedMap(new HashMap())); 15 | 16 | System.out.println("Using Concurrent map: "); 17 | useMap(new ConcurrentHashMap()); 18 | } 19 | 20 | private static void useMap(final Map scores){ 21 | scores.put("Fred", 10); 22 | scores.put("Selly", 20); 23 | 24 | try{ 25 | for (final String score: scores.keySet()) { 26 | System.out.println(score+ "score: " + scores.get(score)); 27 | scores.put("Joe", 14); 28 | } 29 | }catch(Exception e){ 30 | System.out.println("Failed: " + e); 31 | } 32 | System.out.println("Number of elements in maps " + scores.keySet().size()); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/test/java/com/shawn/template/RegexLearningTest.java: -------------------------------------------------------------------------------- 1 | package com.shawn.template; 2 | 3 | import java.util.regex.Matcher; 4 | import java.util.regex.Pattern; 5 | 6 | import org.junit.Test; 7 | 8 | import static org.junit.Assert.*; 9 | public class RegexLearningTest { 10 | 11 | @Test 12 | public void testHowGroupCountWorks() { 13 | String haystack = "The needle shop sells needles"; 14 | String regex = "(needle)"; 15 | Matcher matcher = Pattern.compile(regex).matcher(haystack); 16 | assertEquals(2,matcher.groupCount()); 17 | } 18 | 19 | @Test 20 | public void testFindStartAndEnd() { 21 | String haystack = "The needle shop sells needles"; 22 | String regex = "(needle)"; 23 | Matcher matcher = Pattern.compile(regex).matcher(haystack); 24 | assertTrue(matcher.find()); 25 | assertEquals("Wrong start index of 1st match", 4,matcher.start()); 26 | assertEquals("Wrong end index of 1st match", 10,matcher.end()); 27 | 28 | assertTrue(matcher.find()); 29 | assertEquals("Wrong start index of 2nd match", 22,matcher.start()); 30 | assertEquals("Wrong end index of 2nd match", 28,matcher.end()); 31 | 32 | assertFalse("should not have any match",matcher.find()); 33 | } 34 | 35 | 36 | 37 | } 38 | -------------------------------------------------------------------------------- /src/main/java/com/shawn/nio/NetworkServer.java: -------------------------------------------------------------------------------- 1 | package com.shawn.nio; 2 | 3 | import java.io.IOException; 4 | import java.io.OutputStream; 5 | import java.net.ServerSocket; 6 | import java.net.Socket; 7 | import java.nio.charset.Charset; 8 | 9 | /** 10 | * User: Shawn cao 11 | * Date: 13-10-12 12 | * Time: PM6:06 13 | */ 14 | public class NetworkServer { 15 | public static void main(String[] args) throws IOException { 16 | int port = 2345; 17 | ServerSocket socketServer = new ServerSocket(port); 18 | while(true){ 19 | try { 20 | Socket client = socketServer.accept(); 21 | String response = "Hello " + client.getInetAddress() + " on port " + client.getPort() +"\r\n"; 22 | response +="This is " + client.getLocalAddress() + " on port " + client.getLocalPort() + "\r\n"; 23 | OutputStream outputStream = client.getOutputStream(); 24 | outputStream.write(response.getBytes(Charset.defaultCharset())); 25 | outputStream.flush(); 26 | client.close(); 27 | System.out.println("request from: " + client.getInetAddress()); 28 | }catch (IOException e){ 29 | System.err.print(e.getMessage()); 30 | } 31 | } 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/main/java/com/shawn/concurrent/executor/ScheduleExecutor.java: -------------------------------------------------------------------------------- 1 | package com.shawn.concurrent.executor; 2 | 3 | import java.util.concurrent.ExecutionException; 4 | import java.util.concurrent.Executors; 5 | import java.util.concurrent.ScheduledExecutorService; 6 | import java.util.concurrent.TimeUnit; 7 | 8 | public class ScheduleExecutor { 9 | 10 | 11 | public static void main(String[] args) throws InterruptedException, ExecutionException { 12 | int count = 0; 13 | ScheduledExecutorService schedule = Executors.newSingleThreadScheduledExecutor(); 14 | schedule.scheduleAtFixedRate(new ScheduleJob(count,schedule), 0,500, TimeUnit.MILLISECONDS); 15 | /*{ 16 | System.out.println("----------------------------"); 17 | schedule.shutdown(); 18 | }*/ 19 | } 20 | } 21 | 22 | final class ScheduleJob implements Runnable{ 23 | 24 | private int count; 25 | ScheduledExecutorService schedule; 26 | public ScheduleJob(int count,ScheduledExecutorService schedule) { 27 | this.count = count; 28 | this.schedule = schedule; 29 | } 30 | 31 | 32 | @Override 33 | public void run() { 34 | System.out.println("count..." + count); 35 | if(count++ > 10){ 36 | schedule.shutdown(); 37 | } 38 | } 39 | 40 | } -------------------------------------------------------------------------------- /src/main/java/com/shawn/nio/NetworkClientTest.java: -------------------------------------------------------------------------------- 1 | package com.shawn.nio; 2 | 3 | import java.io.IOException; 4 | import java.io.OutputStream; 5 | import java.net.MalformedURLException; 6 | import java.net.URL; 7 | import java.net.URLConnection; 8 | 9 | /** 10 | * User: Shawn cao 11 | * Date: 13-10-12 12 | * Time: PM5:35 13 | */ 14 | public class NetworkClientTest { 15 | public static void main(String[] args){ 16 | if(args.length == 0){ 17 | System.err.println("Usage: java Mail Client username@host.com"); 18 | return; 19 | } 20 | try{ 21 | URL url = new URL("mailto:" + args[0]); 22 | URLConnection uc = url.openConnection(); 23 | uc.setDoOutput(true); 24 | uc.connect(); 25 | OutputStream out = uc.getOutputStream(); 26 | for(int c = System.in.read(); c!=-1;c=System.in.read()){ 27 | out.write(c); 28 | } 29 | out.close(); 30 | } catch (MalformedURLException e) { 31 | e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. 32 | } catch (IOException e) { 33 | e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. 34 | } 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /src/test/java/com/shawn/template/TestTemplateParse.java: -------------------------------------------------------------------------------- 1 | package com.shawn.template; 2 | 3 | 4 | 5 | import junit.framework.TestCase; 6 | import org.junit.Test; 7 | 8 | import java.util.Arrays; 9 | import java.util.List; 10 | public class TestTemplateParse extends TestCase { 11 | 12 | @Test 13 | public void emptyTemplateRendersAsEmptyString(){ 14 | List segments = parse("plain test only"); 15 | assertSegments(segments, "plain test only"); 16 | } 17 | 18 | 19 | @Test 20 | public void parsingMultipleVariables(){ 21 | List segments = parse("${a}:${b}:${c}"); 22 | assertSegments(segments, "${a}", ":", "${b}", ":", "${c}"); 23 | 24 | } 25 | 26 | 27 | private List parse(String template){ 28 | return new TemplateParse().parse(template); 29 | } 30 | 31 | public void parsingTemplateIntoSegmentObjects(){ 32 | TemplateParse p = new TemplateParse(); 33 | List segments = p.parseSegments("a ${b} c ${d}"); 34 | assertSegments(segments,new PlainText("a "),new Variable("b"),new PlainText(" c "),new Variable("d")); 35 | } 36 | private void assertSegments(List actual,Object... expected){ 37 | assertEquals("Number of segments doesn't match. ", expected.length,actual.size()); 38 | assertEquals(Arrays.asList(expected), actual); 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /src/test/java/com/shawn/guava/RateLimiterTest.java: -------------------------------------------------------------------------------- 1 | package com.shawn.guava; 2 | 3 | import com.google.common.collect.Lists; 4 | import com.google.common.util.concurrent.RateLimiter; 5 | import org.junit.internal.runners.statements.RunAfters; 6 | 7 | import java.time.LocalTime; 8 | import java.util.ArrayList; 9 | import java.util.List; 10 | import java.util.concurrent.Executor; 11 | import java.util.concurrent.ExecutorService; 12 | import java.util.concurrent.Executors; 13 | 14 | /** 15 | * Created by Shangfei on 3/3/16. 16 | */ 17 | public class RateLimiterTest { 18 | 19 | static RateLimiter rateLimiter = RateLimiter.create(2.0); 20 | 21 | public static void main(String[] args) { 22 | 23 | List runs = Lists.newArrayListWithCapacity(10); 24 | for (int i = 0; i < 10 ; i++) { 25 | runs.add(new Runnable() { 26 | @Override 27 | public void run() { 28 | System.out.println("print---- time " + LocalTime.now().toString()); 29 | } 30 | }); 31 | } 32 | submitTasks(runs, Executors.newFixedThreadPool(10)); 33 | } 34 | 35 | static void submitTasks(List tasks, ExecutorService executor) { 36 | for (Runnable e: tasks) { 37 | rateLimiter.acquire(); 38 | executor.execute(e); 39 | } 40 | executor.shutdown(); 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/main/java/com/shawn/concurrent/basic/ThreadWithReturnValue.java: -------------------------------------------------------------------------------- 1 | package com.shawn.concurrent.basic; 2 | 3 | import java.util.List; 4 | import java.util.concurrent.Callable; 5 | import java.util.concurrent.ExecutionException; 6 | import java.util.concurrent.ExecutorService; 7 | import java.util.concurrent.Executors; 8 | import java.util.concurrent.Future; 9 | 10 | import com.google.common.collect.Lists; 11 | 12 | public class ThreadWithReturnValue { 13 | public static void main(String[] args) { 14 | taskWithResult(); 15 | } 16 | 17 | static void taskWithResult() { 18 | ExecutorService executor = Executors.newCachedThreadPool(); 19 | List> results = Lists.newArrayList(); 20 | for (int i = 0; i < 10; i++) { 21 | results.add(executor.submit(new TaskWithResult(i))); //submit produce the future 22 | } 23 | for (Future e : results) { 24 | try { 25 | System.out.println(e.get()); 26 | } catch (InterruptedException e1) { 27 | e1.printStackTrace(); 28 | } catch (ExecutionException e1) { 29 | e1.printStackTrace(); 30 | }finally{ 31 | executor.shutdown(); 32 | } 33 | } 34 | } 35 | } 36 | 37 | class TaskWithResult implements Callable { 38 | private int id; 39 | 40 | public TaskWithResult(int id) { 41 | this.id = id; 42 | } 43 | 44 | @Override 45 | public String call() { 46 | return "result of Task with result" + id; 47 | } 48 | 49 | } -------------------------------------------------------------------------------- /src/main/java/com/shawn/nio/BufferCharView.java: -------------------------------------------------------------------------------- 1 | package com.shawn.nio; 2 | 3 | import java.nio.Buffer; 4 | import java.nio.ByteBuffer; 5 | import java.nio.ByteOrder; 6 | import java.nio.CharBuffer; 7 | 8 | public class BufferCharView { 9 | public static void main(String[] args) { 10 | ByteBuffer buffer = ByteBuffer.allocate(13).order(ByteOrder.BIG_ENDIAN); 11 | CharBuffer viewBuffer = buffer.asCharBuffer(); 12 | 13 | buffer.putChar('H'); 14 | buffer.putChar('E'); 15 | buffer.putChar('L'); 16 | buffer.putChar('L'); 17 | buffer.putChar('O'); 18 | buffer.putChar('H'); 19 | /*buffer.put(1, (byte) 'H'); 20 | buffer.put(2, (byte) 0); 21 | buffer.put(3, (byte) 'E'); 22 | buffer.put(4, (byte) 0); 23 | buffer.put(5, (byte) 'L'); 24 | buffer.put(6, (byte) 0); 25 | buffer.put(7, (byte) 'L'); 26 | buffer.put(8, (byte) 0); 27 | buffer.put(9, (byte) 'O'); 28 | buffer.put(10, (byte) 0); 29 | buffer.put(11, (byte) 'M');*/ 30 | println(buffer); 31 | println(viewBuffer); 32 | 33 | } 34 | 35 | public static void println(Buffer buffer){ 36 | System.out.println ("pos=" + buffer.position()+ ", limit=" + buffer.limit( ) 37 | + ", capacity=" + buffer.capacity( ) 38 | + ": '" + buffer.toString( ) + "'"); 39 | } 40 | } 41 | 42 | -------------------------------------------------------------------------------- /src/main/java/com/shawn/concurrent/basic/SimpleTest.java: -------------------------------------------------------------------------------- 1 | package com.shawn.concurrent.basic; 2 | 3 | 4 | public class SimpleTest { 5 | static A a = new A(); 6 | 7 | private static boolean ready; 8 | private static int number; 9 | 10 | public static void main(String[] args) { 11 | noVisibilityTest(); 12 | number = 42; 13 | ready = true; 14 | } 15 | 16 | private static void noVisibilityTest(){ 17 | new Thread(new Runnable() { 18 | public void run() { 19 | System.out.println("run"); 20 | while(!ready){ 21 | Thread.yield(); 22 | } 23 | System.out.println(number); 24 | 25 | } 26 | },"visible thread").start(); 27 | //thread.start(); 28 | } 29 | 30 | static void TestA() throws InterruptedException { 31 | 32 | Thread[] threads = new Thread[10]; 33 | for (int i = 0; i < threads.length; i++) { 34 | threads[i] = new Thread(new Runnable() { 35 | public void run() { 36 | a.addCount(); 37 | } 38 | },i+""); 39 | threads[i].start(); 40 | } 41 | for (int i = 0; i < threads.length; i++) { 42 | threads[i].join(); 43 | } 44 | System.out.println(a.count); 45 | } 46 | } 47 | 48 | class A{ 49 | int count = 0; 50 | 51 | public void addCount(){ 52 | //System.out.println("before:" +count); 53 | synchronized (this) { 54 | count++; 55 | } 56 | 57 | //System.out.println(count + " :" + Thread.currentThread().getName()); 58 | } 59 | } -------------------------------------------------------------------------------- /src/main/java/com/shawn/nio/InputStreamTest.java: -------------------------------------------------------------------------------- 1 | package com.shawn.nio; 2 | 3 | import com.google.common.base.Strings; 4 | 5 | import java.io.*; 6 | import java.nio.charset.Charset; 7 | 8 | /** 9 | * User: Shawn cao 10 | * Date: 13-10-8 11 | * Time: PM6:29 12 | */ 13 | public class InputStreamTest { 14 | 15 | public static void main(String[] args) throws IOException { 16 | File file = new File("/Users/caocao024/workspace/Test/src/main/java/com/shawn/nio/FilePath.java"); 17 | System.out.println("--" + file.length()); 18 | /* RandomAccessFile randomAccessFile = new RandomAccessFile(file,"r"); 19 | String line = ""; 20 | while((line=randomAccessFile.readLine())!=null){ 21 | System.out.println(line); 22 | } */ 23 | 24 | /* 25 | FileInputStream fileInputStream = new FileInputStream(file); 26 | FileOutputStream fileOutputStream = new FileOutputStream("/Users/caocao024/test.java"); 27 | int m = 0; 28 | while((m = fileInputStream.read())!=-1){ 29 | System.out.print((char)m); 30 | fileOutputStream.write(m); 31 | } 32 | fileInputStream.close();; 33 | fileOutputStream.close(); */ 34 | //System.out.println(3&0x000000FF); 35 | System.out.println((int)0xf3ff); 36 | System.out.format("%s %s %s %s",(byte)129,(byte)255, (byte)256,(byte)257); 37 | 38 | 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /src/main/java/com/shawn/nio/DigestTest.java: -------------------------------------------------------------------------------- 1 | package com.shawn.nio; 2 | 3 | 4 | import java.io.FileInputStream; 5 | import java.io.IOException; 6 | import java.io.InputStream; 7 | import java.math.BigInteger; 8 | import java.security.MessageDigest; 9 | import java.security.NoSuchAlgorithmException; 10 | 11 | public class DigestTest { 12 | public static void main(String args[]) throws IOException, NoSuchAlgorithmException { 13 | //digest("http://www.oreilly.com"); 14 | digest("/Users/caocao024/workspace/Test/pom.xml"); 15 | } 16 | 17 | private static String digest(String urlAdd) throws IOException, NoSuchAlgorithmException { 18 | //URL url = new URL(urlAdd); 19 | //InputStream inputStream = url.openStream(); 20 | InputStream inputStream = new FileInputStream(urlAdd); 21 | MessageDigest digest = MessageDigest.getInstance("MD5"); 22 | byte[] data = new byte[128]; 23 | while(true){ 24 | int byteRead = inputStream.read(data); 25 | if(byteRead <0 ) break; 26 | System.out.println("byte reads: " + byteRead); 27 | digest.update(data,0,byteRead); 28 | } 29 | byte[] result = digest.digest(); 30 | for (int i=0; i list; 17 | transient private String str; 18 | private boolean is; 19 | 20 | public SerializeObject(List list, String str, boolean is) { 21 | this.list = list; 22 | this.str = str; 23 | this.is = is; 24 | } 25 | 26 | public List getList() { 27 | return list; 28 | } 29 | 30 | public void setList(List list) { 31 | this.list = list; 32 | } 33 | 34 | public String getStr() { 35 | return str; 36 | } 37 | 38 | public void setStr(String str) { 39 | this.str = str; 40 | } 41 | 42 | public boolean is() { 43 | return is; 44 | } 45 | 46 | public void setIs(boolean is) { 47 | this.is = is; 48 | } 49 | 50 | 51 | @Override 52 | public String toString() { 53 | return Objects.toStringHelper(this) 54 | .add("list", list) 55 | .add("str", str) 56 | .add("is", is) 57 | .toString(); 58 | } 59 | } -------------------------------------------------------------------------------- /src/main/java/com/shawn/nio/ChannelCopy.java: -------------------------------------------------------------------------------- 1 | package com.shawn.nio; 2 | 3 | import java.io.IOException; 4 | import java.nio.ByteBuffer; 5 | import java.nio.channels.Channels; 6 | import java.nio.channels.ReadableByteChannel; 7 | import java.nio.channels.WritableByteChannel; 8 | 9 | public class ChannelCopy { 10 | 11 | public static void main(String[] args) throws IOException{ 12 | ReadableByteChannel src = Channels.newChannel(System.in); 13 | WritableByteChannel dest = Channels.newChannel(System.out); 14 | //channelCopy1(src, dest); 15 | channelCopy2(src, dest); 16 | src.close(); 17 | dest.close(); 18 | } 19 | 20 | private static void channelCopy1(ReadableByteChannel src,WritableByteChannel dest) throws IOException{ 21 | ByteBuffer buffer = ByteBuffer.allocate(16*1024); 22 | while(src.read(buffer)!=-1){ 23 | buffer.flip(); 24 | dest.write(buffer); 25 | buffer.compact(); 26 | } 27 | buffer.flip(); 28 | while(buffer.hasRemaining()){ 29 | dest.write(buffer); 30 | } 31 | } 32 | 33 | private static void channelCopy2(ReadableByteChannel src,WritableByteChannel dest) throws IOException{ 34 | ByteBuffer buffer = ByteBuffer.allocate(16*1024); 35 | while(src.read(buffer)!=-1){ 36 | buffer.flip(); 37 | while(buffer.hasRemaining()){ 38 | dest.write(buffer); 39 | } 40 | buffer.clear(); 41 | } 42 | } 43 | 44 | } 45 | -------------------------------------------------------------------------------- /src/main/java/com/shawn/GC/FinalizeEscapeGC.java: -------------------------------------------------------------------------------- 1 | package com.shawn.GC; 2 | 3 | /** 4 | * User: Shawn cao 5 | * Date: 14-5-23 6 | * Time: PM4:05 7 | */ 8 | public class FinalizeEscapeGC { 9 | 10 | public static FinalizeEscapeGC SAVE_HOOK = null; 11 | 12 | public void isAlive(){ 13 | System.out.println("yes ! I am still alive:"); 14 | } 15 | 16 | @Override 17 | protected void finalize() throws Throwable { 18 | super.finalize(); 19 | System.out.println("Finalize method executed "); 20 | FinalizeEscapeGC.SAVE_HOOK = this; 21 | } 22 | 23 | public static void main(String[] args) throws Throwable{ 24 | 25 | SAVE_HOOK = new FinalizeEscapeGC(); 26 | 27 | //save itself by late execution of finalize() 28 | SAVE_HOOK = null; 29 | System.gc(); 30 | //wait for finalize() to execute ; the priority of finalize() is low 31 | Thread.sleep(500); 32 | 33 | if(SAVE_HOOK != null){ 34 | SAVE_HOOK.isAlive(); 35 | }else { 36 | System.out.println("no, I am dead :( "); 37 | } 38 | 39 | 40 | //second time , unsuccessful. 41 | //cause finalize of a object can only be executed one time . 42 | //in the second time, the finalize() will not execute. 43 | SAVE_HOOK = null; 44 | System.gc(); 45 | Thread.sleep(500); 46 | if(SAVE_HOOK != null){ 47 | SAVE_HOOK.isAlive(); 48 | }else { 49 | System.out.println("no, I am dead :( "); 50 | } 51 | 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /src/main/java/com/shawn/nio/DataSourceTest.java: -------------------------------------------------------------------------------- 1 | package com.shawn.nio; 2 | 3 | import java.io.*; 4 | import java.nio.file.Paths; 5 | 6 | /** 7 | * User: Shawn cao 8 | * Date: 13-10-9 9 | * Time: PM5:36 10 | */ 11 | public class DataSourceTest{ 12 | 13 | public static void main(String[] args) throws IOException { 14 | //printFile(); 15 | writeFile(new FileInputStream(Paths.get("/etc/hosts").toFile())); 16 | } 17 | 18 | private static void printFile() throws IOException { 19 | File[] roots = File.listRoots(); 20 | File dir = new File(roots[0],"etc"); 21 | File hosts = new File(dir,"hosts"); 22 | FileInputStream fis = new FileInputStream(hosts); 23 | byte[] buffer = new byte[(int) hosts.length()]; 24 | int mark = 0; 25 | while((mark = fis.read(buffer))!=-1){ 26 | } 27 | for(int i = 0 ; i < buffer.length;i++){ 28 | System.out.print((char)buffer[i]); 29 | } 30 | } 31 | 32 | private static void writeFile(InputStream inputStream) throws IOException{ 33 | File[] roots = File.listRoots(); 34 | File dir = new File(roots[0],"/Users/caocao024"); 35 | File hosts = new File(dir,"hosts_qa"); 36 | 37 | FileOutputStream outputStream = new FileOutputStream(hosts,true); 38 | byte[] buffer = new byte[1024]; 39 | while(true){ 40 | int bytesRead = inputStream.read(buffer); 41 | if(bytesRead == -1) break; 42 | else outputStream.write(buffer,0,bytesRead); 43 | } 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /src/main/java/com/shawn/nio/ReadFileByChannel.java: -------------------------------------------------------------------------------- 1 | package com.shawn.nio; 2 | 3 | import java.io.File; 4 | import java.nio.ByteBuffer; 5 | import java.nio.channels.FileChannel; 6 | import java.nio.channels.SeekableByteChannel; 7 | import java.nio.file.Files; 8 | import java.nio.file.Paths; 9 | import java.nio.file.StandardOpenOption; 10 | 11 | import com.google.common.primitives.Bytes; 12 | 13 | 14 | public class ReadFileByChannel { 15 | 16 | private int bufferCapacity; 17 | private ByteBuffer byteBuffer; 18 | private FileChannel fileChannel; 19 | private File file; 20 | public ReadFileByChannel(int bufferCapacity, ByteBuffer byteBuffer, FileChannel fileChannel, File file) { 21 | super(); 22 | this.bufferCapacity = bufferCapacity; 23 | this.byteBuffer = byteBuffer; 24 | this.fileChannel = fileChannel; 25 | this.file = file; 26 | } 27 | 28 | 29 | public void readFileByChange(int bufferSize){} 30 | 31 | public static void main(String[] args) throws Exception{ 32 | 33 | 34 | SeekableByteChannel channel =Files.newByteChannel(Paths.get("/home/shawncao/Desktop/xx"), StandardOpenOption.READ); 35 | ByteBuffer byteBuffer = ByteBuffer.allocate(1024*1024); 36 | 37 | byte[] bytes = new byte[0]; 38 | while(channel.read(byteBuffer) > 0){ 39 | byte[] temp = new byte[byteBuffer.position()]; 40 | byteBuffer.get(temp, 0, byteBuffer.position()); 41 | bytes = Bytes.concat(bytes,temp); 42 | } 43 | 44 | System.out.println("..." + bytes.length +" | " + 1024*1024 ); 45 | } 46 | 47 | } 48 | -------------------------------------------------------------------------------- /src/main/java/com/shawn/leecode/Q2AddTwoNumbers.java: -------------------------------------------------------------------------------- 1 | package com.shawn.leecode; 2 | 3 | /** 4 | * User: Shawn cao 5 | * Date: 14/12/25 6 | * Time: PM5:57 7 | */ 8 | 9 | /** 10 | * You are given two linked lists representing two non-negative numbers. 11 | * The digits are stored in reverse order and each of their nodes contain a single digit. 12 | * Add the two numbers and return it as a linked list. 13 | 14 | Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) 15 | Output: 7 -> 0 -> 8 16 | */ 17 | public class Q2AddTwoNumbers { 18 | 19 | 20 | 21 | 22 | public ListNode addTwoNumbers(ListNode l1, ListNode l2) { 23 | int x=0 ,y=0 ,carry=0 , sum=0 ; 24 | ListNode h=null; 25 | while(l1!=null && l2 !=null){ 26 | x = getValueAndMoveNext(l1); 27 | y = getValueAndMoveNext(l2); 28 | sum = x + y + carry; 29 | 30 | ListNode node = new ListNode(sum%10); 31 | h = node; 32 | h = node.next; 33 | carry = sum/10; 34 | } 35 | if(carry > 0){ 36 | ListNode node = new ListNode(carry%10); 37 | h = node; 38 | } 39 | 40 | return h; 41 | } 42 | 43 | 44 | 45 | private int getValueAndMoveNext(ListNode node){ 46 | int x = 0; 47 | if(node != null){ 48 | x= node.val; 49 | node = node.next; 50 | } 51 | return x; 52 | } 53 | public static class ListNode { 54 | int val; 55 | ListNode next; 56 | ListNode(int x) { 57 | val = x; 58 | next = null; 59 | } 60 | } 61 | } 62 | 63 | 64 | 65 | -------------------------------------------------------------------------------- /src/main/java/com/shawn/nio/BufferFillAndDrain.java: -------------------------------------------------------------------------------- 1 | package com.shawn.nio; 2 | 3 | import java.nio.ByteBuffer; 4 | import java.nio.ByteOrder; 5 | 6 | public class BufferFillAndDrain { 7 | 8 | public static void main(String[] args) { 9 | // CharBuffer buffer = CharBuffer.allocate(100); 10 | //System.out.println(buffer.isDirect()); 11 | ByteBuffer buffer = ByteBuffer.allocateDirect(100).order(ByteOrder.BIG_ENDIAN); 12 | System.out.println(buffer.isDirect() + " " + buffer.isReadOnly() + " " + buffer.order().toString()); 13 | while(fillBuffer(buffer)){ 14 | buffer.flip(); 15 | drainBuffer(buffer); 16 | buffer.clear(); 17 | } 18 | } 19 | private static void drainBuffer(ByteBuffer buffer){ 20 | while(buffer.hasRemaining()){ 21 | System.out.print((char)buffer.get()); 22 | } 23 | System.out.println(""); 24 | } 25 | 26 | private static boolean fillBuffer(ByteBuffer buffer){ 27 | if(index>=strings.length) 28 | return false; 29 | String string = strings[index++]; 30 | for (int i = 0; i < string.length(); i++) { 31 | buffer.put((byte)string.charAt(i)); 32 | 33 | } 34 | return true; 35 | } 36 | 37 | private static int index = 0; 38 | private static String [] strings = { 39 | "A random string value", 40 | "The product of an infinite number of monkeys", 41 | "Hey hey we're the Monkees", 42 | "Opening act for the Monkees: Jimi Hendrix", 43 | "'Scuse me while I kiss this fly", 44 | "Help Me! Help Me!" 45 | }; 46 | } 47 | -------------------------------------------------------------------------------- /src/main/java/com/shawn/object/EliminateObsoleteRefTest.java: -------------------------------------------------------------------------------- 1 | package com.shawn.object; 2 | 3 | import java.util.Arrays; 4 | import java.util.EmptyStackException; 5 | import java.util.WeakHashMap; 6 | 7 | public class EliminateObsoleteRefTest { 8 | 9 | /** 10 | * 2.another common source of memory leaks is 11 | * caches(easy to forget leave there after it comes irrelevant) 12 | * a.represent cache as WeakHashMap only if the desired lifetime of cahce 13 | * entries is determined by external refs to the key not value 14 | * b.cleansed of entries by background thread(Timer,ScheduledThreadPoolExecutor) 15 | * LinkedHashMap with its removeEldestEntry method 16 | * 3.third common source of mem leak listeners and other callbacks 17 | */ 18 | 19 | } 20 | 21 | class Stack{ 22 | private Object[] elements; 23 | private int size = 0; 24 | private static final int DEFAULT_CAPACITY=16; 25 | 26 | public Stack(){ 27 | elements = new Object[DEFAULT_CAPACITY]; 28 | } 29 | 30 | public void push(Object e){ 31 | ensureCapacity(); 32 | elements[size++] = e; 33 | } 34 | 35 | public Object pop() { 36 | if(size == 0) 37 | throw new EmptyStackException(); 38 | //memory leak, it will still keep the obsolete reference to this element 39 | //return elements[--size]; 40 | //improve 41 | Object result = elements[--size]; 42 | elements[size] = null; 43 | return result; 44 | } 45 | private void ensureCapacity(){ 46 | if(elements.length == size) 47 | elements = Arrays.copyOf(elements, 2*size + 1); 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /src/main/java/com/shawn/methods/DefensiveCopies.java: -------------------------------------------------------------------------------- 1 | package com.shawn.methods; 2 | 3 | import java.util.Date; 4 | 5 | public class DefensiveCopies { 6 | 7 | public static void main(String[] args) { 8 | Date start = new Date(); 9 | Date end = new Date(); 10 | Period period = new Period(start, end); 11 | start.setYear(78); 12 | } 13 | } 14 | /** 15 | * 16 | * intend to design Period as immutable class ,however,Date is mutable class , 17 | * there will be problem with the constructor 18 | * 19 | * 20 | */ 21 | final class Period{ 22 | private final Date start; 23 | private final Date end; 24 | 25 | //date is mutable, it rebel the purpose of the Period 26 | /*Period(Date start,Date end) { 27 | if(start.compareTo(end) >0){ 28 | throw new IllegalArgumentException(); 29 | } 30 | this.start= start; 31 | this.end = end; 32 | }*/ 33 | 34 | /** 35 | * repaired constructor,return the date object 36 | * note did not use date clone since date is nonfinal, clone is not guaranteed to return an 37 | * object whose class is Date,may return a untrusted subclass 38 | */ 39 | Period(Date start,Date end) { 40 | this.start= new Date(start.getTime()); 41 | this.end = new Date(end.getTime()); 42 | if(start.compareTo(end) >0){ 43 | throw new IllegalArgumentException(start +" after " +end); 44 | } 45 | } 46 | //to prevent period.end().setYear(78)---> 47 | public Date start(){ 48 | //return start; 49 | return new Date(start.getTime()); 50 | } 51 | 52 | public Date end(){ 53 | //return end; 54 | return new Date(end.getTime()); 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /src/main/java/com/shawn/concurrent/basic/ThreadInitExample.java: -------------------------------------------------------------------------------- 1 | package com.shawn.concurrent.basic; 2 | 3 | import java.util.concurrent.ExecutorService; 4 | import java.util.concurrent.Executors; 5 | 6 | public class ThreadInitExample { 7 | public static void main(String[] args) { 8 | //LiftOffRun(); 9 | executorRun(); 10 | } 11 | 12 | static void LiftOffRun(){ 13 | Thread[] threads = new Thread[10]; 14 | for (int i = 0; i < threads.length; i++) { 15 | Thread thread = new Thread(new LiftOff()); 16 | thread.start(); 17 | } 18 | /* 19 | LiftOff off = new LiftOff(10); 20 | Thread thread = new Thread(off); 21 | off.run();*/ 22 | //thread.start(); 23 | } 24 | static void executorRun(){ 25 | //ExecutorService executorService = Executors.newCachedThreadPool();//create as many threads as needed 26 | //ExecutorService executorService = Executors.newSingleThreadExecutor();//each tasks will be queued and run to completion b4 the next is begun 27 | ExecutorService executorService = Executors.newFixedThreadPool(5);//threads are reused when possible 28 | for (int i = 0; i < 5; i++) { 29 | executorService.execute(new LiftOff()); 30 | } 31 | executorService.shutdown(); 32 | } 33 | } 34 | 35 | class LiftOff implements Runnable{ 36 | int countDown = 10; 37 | private static int taskCount =0; 38 | private final int id = taskCount++; 39 | 40 | public LiftOff() { 41 | } 42 | public LiftOff(int countDown){ 43 | this.countDown = countDown; 44 | } 45 | 46 | public String status(){ 47 | return "#" + id + "("+(countDown >0 ?countDown:"liftOff!")+")"; 48 | } 49 | @Override 50 | public void run() { 51 | while (countDown-- > 0) { 52 | System.out.println(status()); 53 | Thread.yield();//moves CPU from one thread to another 54 | } 55 | } 56 | 57 | } 58 | -------------------------------------------------------------------------------- /src/main/java/com/shawn/general/JsonTest.java: -------------------------------------------------------------------------------- 1 | package com.shawn.general; 2 | 3 | 4 | import java.io.File; 5 | import java.io.FileReader; 6 | import java.io.FileWriter; 7 | import java.io.IOException; 8 | import java.util.Map; 9 | 10 | import org.springframework.util.StringUtils; 11 | 12 | import com.google.common.base.Joiner; 13 | import com.google.common.collect.ImmutableMap; 14 | import com.google.common.collect.Maps; 15 | import com.google.gson.Gson; 16 | import com.google.gson.GsonBuilder; 17 | 18 | public class JsonTest { 19 | 20 | private static final Gson gson = new GsonBuilder().enableComplexMapKeySerialization().create(); 21 | 22 | public static void main(String[] args) throws IOException { 23 | Map> map = Maps.newConcurrentMap(); 24 | map.put("/path1", Maps.newHashMap(new ImmutableMap.Builder().put("host","www").put("log_type","error").build())); 25 | map.put("/path2", Maps.newHashMap(new ImmutableMap.Builder().put("host","job").put("log_type","access").build())); 26 | map.put("/path3", Maps.newHashMap(new ImmutableMap.Builder().put("log_type","default").build())); 27 | 28 | FileWriter writer = new FileWriter(new File("/home/shawncao/test.json")); 29 | writer.append(gson.toJson(map)); 30 | writer.close(); 31 | 32 | Map> gsss = gson.fromJson(new FileReader(new File("/home/shawncao/Desktop/logHeader.json")), Map.class); 33 | 34 | System.out.println(StringUtils.collectionToCommaDelimitedString(gsss.keySet())); 35 | for(String e: gsss.keySet()){ 36 | System.out.println( e + ": "+ Joiner.on("&").withKeyValueSeparator("=").join(gsss.get(e))); 37 | } 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/test/java/com/shawn/nio/JacksonTest.java: -------------------------------------------------------------------------------- 1 | package com.shawn.nio; 2 | 3 | import com.google.common.base.Objects; 4 | import com.google.common.base.Strings; 5 | import org.codehaus.jackson.JsonNode; 6 | import org.codehaus.jackson.annotate.JsonIgnoreProperties; 7 | import org.codehaus.jackson.map.ObjectMapper; 8 | import org.codehaus.jackson.type.TypeReference; 9 | import org.junit.Test; 10 | 11 | import java.io.IOException; 12 | import java.net.URL; 13 | 14 | import static org.junit.Assert.assertFalse; 15 | 16 | /** 17 | * @author Shawn Cao 18 | */ 19 | public class JacksonTest { 20 | ObjectMapper objectMapper = new ObjectMapper(); 21 | String link ="http://s.cjol.com/service/joblistjson.aspx?KeywordType=3&Location=2008&SearchType=1&ListType=2&page=2"; 22 | @Test 23 | public void testMapJsonToObject() throws IOException { 24 | CJOLJsonObject object = objectMapper.readValue(new URL(link), new TypeReference(){}); 25 | 26 | System.out.println(object.JobListHtml) ; 27 | assertFalse(Strings.isNullOrEmpty(object.JobListHtml)); 28 | } 29 | 30 | 31 | @Test 32 | public void testReadJsonToGetCertianField() throws IOException{ 33 | JsonNode node = objectMapper.readTree(new URL(link)); 34 | String html = node.get("JobListHtml").asText(); 35 | System.out.println(html); 36 | assertFalse(Strings.isNullOrEmpty(html)); 37 | } 38 | 39 | 40 | @JsonIgnoreProperties(ignoreUnknown = true) 41 | private static class CJOLJsonObject{ 42 | 43 | 44 | public String JobListHtml; 45 | 46 | @Override 47 | public String toString() { 48 | return Objects.toStringHelper(this) 49 | .add("JobListHtml", JobListHtml) 50 | .toString(); 51 | } 52 | 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /src/main/java/com/shawn/concurrent/util/PrintQueueWithSemaphore.java: -------------------------------------------------------------------------------- 1 | package com.shawn.concurrent.util; 2 | 3 | import java.util.concurrent.Semaphore; 4 | 5 | /** 6 | * User: Shawn cao 7 | * Date: 13-4-3 8 | * Time: PM10:18 9 | */ 10 | public class PrintQueueWithSemaphore { 11 | public static void main(String[] args){ 12 | PrintQueueV printQueueV=new PrintQueueV(); 13 | Thread thread[]=new Thread[10]; 14 | for (int i=0; i<10; i++){ 15 | thread[i]=new Thread(new JobV(printQueueV),"Thread"+i); 16 | } 17 | for (int i=0; i<10; i++){ 18 | thread[i].start(); 19 | } 20 | } 21 | 22 | } 23 | 24 | 25 | class JobV implements Runnable{ 26 | private PrintQueueV printQueueV; 27 | 28 | public JobV(PrintQueueV printQueueV){ 29 | this.printQueueV = printQueueV; 30 | } 31 | 32 | public void run() { 33 | System.out.printf("%s: Going to print a job\n",Thread.currentThread().getName()); 34 | printQueueV.printJob(new Object()); 35 | System.out.printf("%s: The document has been printed\n",Thread.currentThread().getName()); 36 | } 37 | } 38 | 39 | class PrintQueueV{ 40 | private final Semaphore semaphore; 41 | 42 | public PrintQueueV(){ 43 | this.semaphore = new Semaphore(1); 44 | } 45 | 46 | public void printJob(Object document){ 47 | try { 48 | semaphore.acquire(); 49 | long duration=(long)(Math.random()*10); 50 | System.out.printf("%s: PrintQueue: Printing a Job during %d seconds\n",Thread.currentThread().getName(),duration); 51 | Thread.sleep(duration); 52 | 53 | }catch (InterruptedException e){ 54 | e.printStackTrace(); 55 | }finally { 56 | semaphore.release(); 57 | } 58 | } 59 | } 60 | 61 | 62 | -------------------------------------------------------------------------------- /src/main/java/com/shawn/IOParadigm/TimeClient.java: -------------------------------------------------------------------------------- 1 | package com.shawn.IOParadigm; 2 | 3 | import java.io.BufferedReader; 4 | import java.io.IOException; 5 | import java.io.InputStreamReader; 6 | import java.io.PrintWriter; 7 | import java.net.Socket; 8 | import java.net.UnknownHostException; 9 | 10 | /** 11 | * User: Shawn cao 12 | * Date: 14-5-16 13 | * Time: PM5:02 14 | */ 15 | public class TimeClient { 16 | 17 | public static void main(String[] args){ 18 | int port = 12345; 19 | Socket socket = null; 20 | BufferedReader in = null; 21 | PrintWriter out = null; 22 | try{ 23 | socket = new Socket("127.0.0.1",port); 24 | in = new BufferedReader(new InputStreamReader(socket.getInputStream())); 25 | out = new PrintWriter(socket.getOutputStream(),true); 26 | out.println("QUERY TIME ORDER"); 27 | System.out.println("Send order 2 server succeed."); 28 | String response = in.readLine(); 29 | System.out.println("Now is " + response); 30 | } catch (UnknownHostException e) { 31 | e.printStackTrace(); 32 | } catch (IOException e) { 33 | e.printStackTrace(); 34 | }finally { 35 | if(out != null){ 36 | out.close(); 37 | out = null; 38 | } 39 | if(in != null){ 40 | try{ 41 | in.close(); 42 | }catch (IOException e){ 43 | e.printStackTrace(); 44 | } 45 | in = null; 46 | } 47 | if(socket != null){ 48 | try{ 49 | socket.close(); 50 | }catch (IOException e){ 51 | e.printStackTrace(); 52 | } 53 | socket = null; 54 | } 55 | } 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /src/main/java/com/shawn/concurrent/basic/InterruptionExceptionDemo.java: -------------------------------------------------------------------------------- 1 | package com.shawn.concurrent.basic; 2 | 3 | import java.io.File; 4 | import java.util.concurrent.TimeUnit; 5 | 6 | public class InterruptionExceptionDemo { 7 | public static void main(String[] args) { 8 | Thread thread =new Thread(new FileSearch("/Users/caocao024/workspace/Test", "InterruptionExceptionDemo.java")); 9 | thread.start(); 10 | try { 11 | TimeUnit.MILLISECONDS.sleep(4000); 12 | } catch (InterruptedException e) { 13 | e.printStackTrace(); 14 | } 15 | thread.interrupt(); 16 | } 17 | } 18 | 19 | class FileSearch implements Runnable { 20 | private String initPath; 21 | private String fileName; 22 | 23 | public FileSearch(String initPath, String fileName) { 24 | this.initPath = initPath; 25 | this.fileName = fileName; 26 | } 27 | 28 | @Override 29 | public void run() { 30 | File file = new File(initPath); 31 | if (file.isDirectory()) { 32 | try { 33 | directoryProcess(file); 34 | } catch (InterruptedException e) { 35 | System.out.printf("%s: The search has been interrupted ", 36 | Thread.currentThread().getName()); 37 | } 38 | } 39 | } 40 | 41 | private void directoryProcess(File file) throws InterruptedException { 42 | File list[] = file.listFiles(); 43 | if (list != null) { 44 | for (int i = 0; i < list.length; i++) { 45 | if (list[i].isDirectory()) { 46 | directoryProcess(list[i]); 47 | } else { 48 | fileProcess(list[i]); 49 | } 50 | } 51 | } 52 | if (Thread.interrupted()) { 53 | throw new InterruptedException(); 54 | } 55 | } 56 | 57 | private void fileProcess(File file) throws InterruptedException { 58 | if (file.getName().equals(fileName)) { 59 | System.out.printf("%s : %s \n", Thread.currentThread().getName(), 60 | file.getAbsoluteFile()); 61 | } 62 | if (Thread.interrupted()) { 63 | throw new InterruptedException(); 64 | } 65 | } 66 | 67 | } 68 | -------------------------------------------------------------------------------- /src/main/java/com/shawn/object/CreateNoUnecessaryObjTest.java: -------------------------------------------------------------------------------- 1 | package com.shawn.object; 2 | 3 | import java.sql.Date; 4 | import java.util.Calendar; 5 | import java.util.TimeZone; 6 | 7 | public class CreateNoUnecessaryObjTest { 8 | 9 | //create new string each time it is executed 10 | String string = new String("stringngngnng"); 11 | //improved 12 | String string2 = "stringaninigaing"; 13 | 14 | //avoid to reuse immutable obj, 15 | } 16 | 17 | class Person{ 18 | private Date birthDate; 19 | 20 | public Date getBirthDate() { 21 | return birthDate; 22 | } 23 | 24 | public void setBirthDate(Date birthDate) { 25 | this.birthDate = birthDate; 26 | } 27 | 28 | //unnecessary to create a new calendar,timezone, each time it is invoked 29 | public boolean isBabyBoomer(){ 30 | 31 | Calendar gmtCal = Calendar.getInstance(TimeZone.getTimeZone("GMT")); 32 | gmtCal.set(1946, Calendar.JANUARY,1,0,0,0); 33 | Date boomStart = (Date) gmtCal.getTime(); 34 | gmtCal.set(1965, Calendar.JANUARY,1,0,0,0); 35 | Date boomEnd = (Date)gmtCal.getTime(); 36 | return birthDate.compareTo(boomStart) >=0 && birthDate.compareTo(boomEnd) <0; 37 | } 38 | //improved 39 | private static Date BOOM_START; 40 | private static Date BOOM_END; 41 | //will be initialized at the beginning, waste resource only if the method never used 42 | //could be lazy initializing these field alternatively 43 | static{ 44 | Calendar gmtCal = Calendar.getInstance(TimeZone.getTimeZone("GMT")); 45 | gmtCal.set(1946, Calendar.JANUARY,1,0,0,0); 46 | BOOM_START = (Date)gmtCal.getTime(); 47 | gmtCal.set(1965, Calendar.JANUARY,1,0,0,0); 48 | BOOM_END = (Date)gmtCal.getTime(); 49 | } 50 | 51 | public boolean betterisBabyBoomer(){ 52 | return birthDate.compareTo(BOOM_START)>=0 && birthDate.compareTo(BOOM_END)<0; 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /src/main/java/com/shawn/generic/UnboundWildcardTest.java: -------------------------------------------------------------------------------- 1 | package com.shawn.generic; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Collection; 5 | import java.util.Collections; 6 | import java.util.HashSet; 7 | import java.util.List; 8 | import java.util.Set; 9 | 10 | import com.google.common.collect.Lists; 11 | import com.google.common.collect.Sets; 12 | /** 13 | * PECS: producer-extends,consumer-super 14 | * e.g:comparable --consumers: Comparable 15 | * Comparator 16 | * 17 | */ 18 | public class UnboundWildcardTest { 19 | 20 | public static void main(String[] args) { 21 | WildcardStack stacks = new WildcardStack(); 22 | Iterable ints = Lists.newArrayList(1,2,3,4); 23 | stacks.pushAllByWildcard(ints); 24 | //not applicable for ints 25 | //stacks.pushAll(ints); 26 | Set intSets = Sets.newHashSet(1,2,3,4); 27 | Set doubleSets = Sets.newHashSet(2.0,4.5,7.11); 28 | //Set mergeSets = union(intSets, doubleSets); 29 | Set mergeSets = WildcardStack.unionbyWildcard(intSets, doubleSets); 30 | } 31 | } 32 | 33 | class WildcardStack extends Stack{ 34 | public void pushAllByWildcard(Iterable src) { 35 | for (T t:src) { 36 | push(t); 37 | } 38 | } 39 | 40 | public void popAllByWildcard(Collection dst){ 41 | while(!isEmpty()){ 42 | dst.add(pop()); 43 | } 44 | } 45 | 46 | public static Set union(Set s1, Set s2) { 47 | Set result = new HashSet(s1); 48 | result.addAll(s2); 49 | return result; 50 | } 51 | 52 | public static Set unionbyWildcard(Set s1, Set s2) { 53 | Set result = new HashSet(s1); 54 | result.addAll(s2); 55 | return result; 56 | } 57 | 58 | //abstract static > T max(List list); 59 | } 60 | -------------------------------------------------------------------------------- /src/main/java/com/shawn/nio/RandomPoll.java: -------------------------------------------------------------------------------- 1 | package com.shawn.nio; 2 | 3 | import com.google.common.base.Joiner; 4 | import com.google.common.base.Strings; 5 | import com.google.common.collect.Lists; 6 | 7 | import java.io.*; 8 | import java.util.List; 9 | import java.util.Random; 10 | 11 | /** 12 | * User: Shawn cao 13 | * Date: 14-2-19 14 | * Time: PM8:12 15 | */ 16 | public class RandomPoll { 17 | 18 | public static void main(String[] args) throws IOException{ 19 | List topics = readFile(); 20 | for(String m: readFile()){ 21 | System.out.println("---" + m); 22 | } 23 | Random random = new Random(); 24 | int i = random.nextInt(topics.size()); 25 | System.out.println(topics.get(i)); 26 | finishedTopic(topics,i); 27 | } 28 | 29 | 30 | public static List readFile() throws IOException { 31 | List topicList = Lists.newArrayList(); 32 | 33 | BufferedReader br = new BufferedReader(new FileReader("/Users/caocao024/Desktop/writing")); 34 | String line =""; 35 | while((line = br.readLine() )!=null){ 36 | String tmp = br.readLine(); 37 | if(tmp == null){ 38 | break; 39 | } 40 | line = line+tmp; 41 | if(!Strings.isNullOrEmpty(line)) 42 | topicList.add(line); 43 | 44 | line = null; 45 | tmp = null; 46 | } 47 | br.close(); 48 | return topicList; 49 | } 50 | 51 | public static void finishedTopic(List finish, int doneIndex) throws IOException{ 52 | BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter("/Users/caocao024/Desktop/writing")); 53 | BufferedWriter bufferedWriterDone = new BufferedWriter(new FileWriter("/Users/caocao024/Desktop/writing_finished")); 54 | bufferedWriterDone.append("\n\n"); 55 | bufferedWriterDone.append(finish.get(doneIndex)); 56 | finish.remove(doneIndex); 57 | bufferedWriterDone.close(); 58 | 59 | bufferedWriter.write(Joiner.on("\n\n").join(finish)); 60 | bufferedWriter.close(); 61 | 62 | } 63 | 64 | } 65 | -------------------------------------------------------------------------------- /src/test/java/com/shawn/general/GeneralTest.java: -------------------------------------------------------------------------------- 1 | package com.shawn.general; 2 | 3 | import com.google.common.collect.Lists; 4 | import org.junit.Test; 5 | 6 | import java.math.BigDecimal; 7 | import java.util.*; 8 | 9 | import static org.junit.Assert.assertEquals; 10 | import static org.junit.Assert.assertTrue; 11 | 12 | /** 13 | * @author Shawn Cao 14 | */ 15 | public class GeneralTest { 16 | 17 | 18 | @Test 19 | public void testRemove(){ 20 | List list = Lists.newArrayList(1,2,3,4,5); 21 | 22 | for(Iterator it = list.iterator();it.hasNext();){ 23 | Integer e = it.next(); 24 | if(e == 3){ 25 | it.remove(); 26 | } 27 | } 28 | assertTrue(!list.contains(3)); 29 | } 30 | 31 | private static final Random rnd = new Random(); 32 | 33 | 34 | @Test 35 | public void testRandomNo(){ 36 | int n = 2 * ((Integer.MAX_VALUE) / 3); 37 | int low = 0; 38 | for (int i = 0; i < 100000; i++) { 39 | if(rnd.nextInt(n) < n/2){ 40 | low ++; 41 | } 42 | } 43 | System.out.println(low); 44 | } 45 | 46 | //do not use double or float for any calculations require exact answers 47 | @Test 48 | public void testFloat(){ 49 | /*double funds = 1.00; 50 | int itemsBought = 0; 51 | for(double price = 0.10; funds >= price; price += .10){ 52 | funds -= price; 53 | itemsBought++; 54 | } 55 | */ 56 | final BigDecimal TEN_CENTS = new BigDecimal(".10"); 57 | int itemsBought = 0; 58 | BigDecimal funds = new BigDecimal("1.0"); 59 | for (BigDecimal price = TEN_CENTS; funds.compareTo(price) >=0 ; price = price.add(TEN_CENTS)) { 60 | funds = funds.subtract(price); 61 | itemsBought++; 62 | 63 | } 64 | assertEquals(4,itemsBought); 65 | assertEquals(new BigDecimal(".00"),funds); 66 | } 67 | 68 | //do not use == for boxed type 69 | 70 | @Test 71 | public void testInterfaceObject(){ 72 | Deque deque = new LinkedList<>(); 73 | 74 | } 75 | } 76 | 77 | -------------------------------------------------------------------------------- /src/main/java/com/shawn/generic/GenericTest.java: -------------------------------------------------------------------------------- 1 | package com.shawn.generic; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Arrays; 5 | import java.util.Collections; 6 | import java.util.EmptyStackException; 7 | import java.util.List; 8 | 9 | 10 | /** 11 | * 12 | * @author shawncao 13 | * parameterized type: List 14 | * Actual type parameter:String 15 | * Generic type: List 16 | * Unbounded wildcard type: List 17 | * Raw type: List 18 | * Bounded type parameter: 19 | * Recursive type bound: > 20 | * Bounded wildcard type : List 21 | * Generic method : static List asList(E[] a) 22 | */ 23 | public class GenericTest { 24 | 25 | public T[] toArray(T[] a) { 26 | 27 | return a; 28 | } 29 | 30 | public void listOverArr() { 31 | // prefer list to array 32 | // fails at runtime 33 | Object[] objects = new Long[1]; 34 | objects[0] = "won't fit in "; 35 | 36 | // fail at compile 37 | // List ol = new ArrayList(); 38 | } 39 | 40 | public static void main(String[] args) { 41 | 42 | } 43 | 44 | } 45 | 46 | class Stack { 47 | private T[] elements; 48 | private int size = 0; 49 | private static final int DEFAULT_INITIAL_CAPACITY = 16; 50 | 51 | @SuppressWarnings("unchecked") 52 | public Stack() { 53 | elements = (T[]) new Object[DEFAULT_INITIAL_CAPACITY]; 54 | } 55 | public void push(T e) { 56 | ensureCapacity(); 57 | elements[size++] = e; 58 | } 59 | public T pop() { 60 | if (size == 0) 61 | throw new EmptyStackException(); 62 | T result = (T)elements[--size]; 63 | elements[size] = null; // Eliminate obsolete reference 64 | return result; 65 | } 66 | public boolean isEmpty() { 67 | return size == 0; 68 | } 69 | private void ensureCapacity() { 70 | if (elements.length == size) 71 | elements = Arrays.copyOf(elements, 2 * size + 1); 72 | } 73 | 74 | public void pushAll(Iterable src){ 75 | for(T t:src){ 76 | push(t); 77 | } 78 | } 79 | } 80 | 81 | 82 | -------------------------------------------------------------------------------- /src/test/java/com/shawn/general/EnumTest.java: -------------------------------------------------------------------------------- 1 | package com.shawn.general; 2 | 3 | import org.junit.Test; 4 | /** 5 | * @author Shawn Cao 6 | */ 7 | public class EnumTest { 8 | 9 | @Test 10 | public void testOp(){ 11 | testOperation(ExtendedOperation.class,1.2, 1.1); 12 | } 13 | 14 | private static & Operation> void testOperation(Class opSet,double x, double y){ 15 | for (Operation o : opSet.getEnumConstants()) { 16 | System.out.printf("%f %s %f = %f %n", x, o, y, o.apply(x, y)); 17 | } 18 | } 19 | 20 | } 21 | 22 | class Herb{ 23 | enum Type{ANNUAL, PERENIAL, BIENNIAL}; 24 | final String name; 25 | final Type type; 26 | 27 | public Herb(String name, Type type) { 28 | this.name = name; 29 | this.type = type; 30 | } 31 | 32 | @Override 33 | public String toString() { 34 | return name; 35 | } 36 | } 37 | 38 | 39 | interface Operation{ 40 | double apply(double x, double y); 41 | } 42 | 43 | 44 | enum BasicOperation implements Operation{ 45 | PLUS("+") { 46 | @Override 47 | public double apply(double x, double y) { 48 | return x+y; 49 | } 50 | }, 51 | MINUS("-") { 52 | @Override 53 | public double apply(double x, double y) { 54 | return x-y; 55 | } 56 | }, 57 | TIMES("*") { 58 | @Override 59 | public double apply(double x, double y) { 60 | return x * y; 61 | } 62 | }, 63 | DIVIDE("/") { 64 | @Override 65 | public double apply(double x, double y) { 66 | return x / y; 67 | } 68 | }; 69 | private String symbol; 70 | BasicOperation(String symbol){ 71 | this.symbol = symbol; 72 | } 73 | } 74 | 75 | enum ExtendedOperation implements Operation{ 76 | EXP("^") { 77 | @Override 78 | public double apply(double x, double y) { 79 | return Math.pow(x,y); 80 | } 81 | }, 82 | REMINDER("%") { 83 | @Override 84 | public double apply(double x, double y) { 85 | return x % y; 86 | } 87 | }; 88 | private String symbol; 89 | ExtendedOperation(String symbol){ 90 | this.symbol = symbol; 91 | } 92 | } -------------------------------------------------------------------------------- /src/main/java/com/shawn/template/TemplateParse.java: -------------------------------------------------------------------------------- 1 | package com.shawn.template; 2 | 3 | 4 | 5 | import java.util.List; 6 | import java.util.regex.Matcher; 7 | import java.util.regex.Pattern; 8 | 9 | import com.google.common.collect.Lists; 10 | 11 | public class TemplateParse { 12 | 13 | private List list; 14 | public TemplateParse() { 15 | list = Lists.newArrayList(); 16 | } 17 | public List parse(String template){ 18 | int index = collectSegments(list, template); 19 | addTail(list, template, index); 20 | addEmptyStringIfTemplateWasEmpty(list); 21 | return list; 22 | } 23 | 24 | public List parseSegments(String template){ 25 | List segments = Lists.newArrayList(); 26 | List strs = parse(template); 27 | for(String s:strs){ 28 | if(Template.isVariable(s)){ 29 | String name = s.substring(2,s.length()-1); 30 | segments.add(new Variable(name)); 31 | }else{ 32 | segments.add(new PlainText(s)); 33 | } 34 | } 35 | return null; 36 | } 37 | private int collectSegments(List segs,String src){ 38 | Pattern pattern = Pattern.compile("\\$\\{[^}]*\\}"); 39 | Matcher matcher = pattern.matcher(src); 40 | int index = 0; 41 | while(matcher.find()){ 42 | addPrecedingPlainText(segs, src, matcher, index); 43 | addVariable(segs, src, matcher); 44 | index = matcher.end(); 45 | } 46 | return index; 47 | } 48 | 49 | private void addTail(List segs,String template,int index){ 50 | if(index < template.length()){ 51 | segs.add(template.substring(index)); 52 | } 53 | } 54 | 55 | private void addVariable(List segs,String src,Matcher m){ 56 | segs.add(src.substring(m.start(),m.end())); 57 | } 58 | private void addPrecedingPlainText(List segs,String src,Matcher m,int index){ 59 | if(index!=m.start()){ 60 | segs.add(src.substring(index,m.start())); 61 | } 62 | } 63 | 64 | private void addEmptyStringIfTemplateWasEmpty(List segs){ 65 | if(segs.isEmpty()){ 66 | segs.add(""); 67 | } 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /src/test/java/com/shawn/general/StringTest.java: -------------------------------------------------------------------------------- 1 | package com.shawn.general; 2 | 3 | import com.google.common.base.Charsets; 4 | import org.junit.Test; 5 | import org.springframework.web.util.UriUtils; 6 | 7 | import java.io.UnsupportedEncodingException; 8 | import java.net.URLDecoder; 9 | import java.net.URLEncoder; 10 | import java.util.Optional; 11 | 12 | /** 13 | * User: Shawn cao 14 | * Date: 14-5-26 15 | * Time: AM10:25 16 | */ 17 | public class StringTest { 18 | 19 | @Test 20 | public void testImmutability(){ 21 | String str1 = "aaa"; 22 | System.out.println(str1.hashCode()); 23 | str1 = "bbb"; 24 | System.out.println(str1.hashCode()); 25 | String str2 = "aaa"; 26 | System.out.println(str2.hashCode()); 27 | 28 | System.out.println(fizzBuzz(15)); 29 | System.out.println(fizzBuzz(10)); 30 | System.out.println(fizzBuzz(77)); 31 | } 32 | 33 | 34 | public static String fizzBuzz(int number){ 35 | String result = Optional.of(number).map(n -> (n%3 == 0 ? "fizz": "") + (n % 5 == 0 ? "Buzz" : "")).get(); 36 | return result.isEmpty() ? Integer.toString(number) : result; 37 | } 38 | 39 | @Test 40 | public void testUrlEncoding() throws UnsupportedEncodingException { 41 | String query = URLEncoder.encode("sourceLink=+http://www.51zhucai.com/zhiwei/job167307.html&applyId=123", Charsets.UTF_8.name()); 42 | System.out.println(query); 43 | String tran = URLDecoder.decode(query,Charsets.UTF_8.name()); 44 | System.out.println(tran); 45 | } 46 | @Test 47 | public void testBitShift(){ 48 | int i = 2118123; 49 | System.out.println((i>>31)&1); 50 | } 51 | 52 | public static String stringReplace(String text){ 53 | text = text.replace("j","l"); 54 | return text; 55 | } 56 | 57 | public static void bufferReplace(StringBuffer text){ 58 | text = text.append("c"); 59 | } 60 | 61 | public static void main(String args[]){ 62 | String textStr = "java"; 63 | StringBuffer textBuffer = new StringBuffer("java"); 64 | System.out.println("b---" + textBuffer.hashCode()); 65 | bufferReplace(textBuffer); 66 | 67 | System.out.println(stringReplace(textStr) + " | " + textStr.hashCode()); 68 | System.out.println(textBuffer +" "+ textBuffer.hashCode()); 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /src/test/java/com/shawn/general/AnnotationTest.java: -------------------------------------------------------------------------------- 1 | package com.shawn.general; 2 | 3 | import java.lang.annotation.ElementType; 4 | import java.lang.annotation.Retention; 5 | import java.lang.annotation.RetentionPolicy; 6 | import java.lang.annotation.Target; 7 | import java.lang.reflect.InvocationTargetException; 8 | import java.lang.reflect.Method; 9 | 10 | import org.junit.Test; 11 | /** 12 | * @author Shawn Cao 13 | */ 14 | public class AnnotationTest { 15 | 16 | public static void main(String[] args){ 17 | int tests = 0; 18 | int passed = 0; 19 | Class testClass = AnnotationTest.class; 20 | for (Method m : testClass.getMethods()) { 21 | if (m.isAnnotationPresent(Anno.class)) { 22 | tests++; 23 | try { 24 | m.invoke(null); 25 | System.out.printf("Test %s failed: no exception%n" ,m); 26 | } catch (InvocationTargetException e) { 27 | Throwable t = e.getCause(); 28 | Class[] excTypes = m.getAnnotation(Anno.class).value(); 29 | int oldPassed = passed; 30 | for(Class ex:excTypes){ 31 | if(ex.isInstance(t)){ 32 | passed++; 33 | break; 34 | } 35 | } 36 | if(passed==oldPassed){ 37 | System.out.printf("Test %s failed: %s %n",m,t); 38 | } 39 | 40 | }catch (Exception e) { 41 | System.out.println("Invalid @Test: " + m); 42 | } 43 | } 44 | } 45 | 46 | System.out.printf("Passed:%d, failed:%d%n", passed, tests - passed); 47 | } 48 | 49 | @Anno({ArithmeticException.class,NullPointerException.class}) 50 | public void m1(){ 51 | int i=0; 52 | i = i/1; 53 | } 54 | 55 | @Anno({ArrayIndexOutOfBoundsException.class}) 56 | public void m2(){ 57 | int[] arr = new int[0]; 58 | arr[1]=1; 59 | } 60 | } 61 | 62 | 63 | @Retention(RetentionPolicy.RUNTIME) 64 | @Target(ElementType.METHOD) 65 | @interface Anno{ 66 | Class[] value(); 67 | } -------------------------------------------------------------------------------- /src/main/java/com/shawn/concurrent/executor/SimpleExecutor.java: -------------------------------------------------------------------------------- 1 | package com.shawn.concurrent.executor; 2 | 3 | import java.util.Date; 4 | import java.util.concurrent.Executors; 5 | import java.util.concurrent.ThreadPoolExecutor; 6 | import java.util.concurrent.TimeUnit; 7 | 8 | public class SimpleExecutor { 9 | public static void main(String[] args) { 10 | ExecutorServer server = new ExecutorServer(); 11 | for (int i = 0; i < 100; i++) { 12 | Task task = new Task("Task " + i); 13 | server.executeTask(task); 14 | } 15 | server.endServer(); 16 | } 17 | } 18 | 19 | class Task implements Runnable{ 20 | private Date initDate; 21 | private String name; 22 | 23 | public Task(String name){ 24 | initDate = new Date(); 25 | this.name = name; 26 | } 27 | 28 | public void run() { 29 | System.out.printf("%s: Task %s: Created on: %s \n",Thread.currentThread().getName(),name,initDate); 30 | System.out.printf("%s: Task %s: Started on: %s \n",Thread.currentThread().getName(),name,new Date()); 31 | try { 32 | Long duration = (long)(Math.random()*10); 33 | System.out.printf("%s: Task %s: Doing a task during %d seconds \n",Thread.currentThread().getName(),name,duration); 34 | TimeUnit.SECONDS.sleep(duration); 35 | } catch (Exception e) { 36 | e.printStackTrace(); 37 | } 38 | System.out.printf("%s: Task %s:Finished on: %s \n",Thread.currentThread().getName(),name,new Date()); 39 | } 40 | } 41 | 42 | class ExecutorServer { 43 | private ThreadPoolExecutor executor; 44 | public ExecutorServer() { 45 | //executor = (ThreadPoolExecutor)Executors.newCachedThreadPool(); 46 | executor = (ThreadPoolExecutor)Executors.newFixedThreadPool(50); 47 | } 48 | 49 | public void executeTask(Task task){ 50 | System.out.printf("Server: A new task has arrived \n"); 51 | executor.execute(task); 52 | System.out.printf("Server: largest number pool size: %d \n",executor.getLargestPoolSize()); 53 | System.out.printf("Server: pool Size: %d \n",executor.getPoolSize()); 54 | System.out.printf("Server: Active count; %d\n",executor.getActiveCount()); 55 | System.out.printf("Server: Completed Tasks: %d\n",executor.getCompletedTaskCount()); 56 | } 57 | 58 | public void endServer(){ 59 | executor.shutdown(); 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /src/main/java/com/shawn/object/ObjectBuilder.java: -------------------------------------------------------------------------------- 1 | package com.shawn.object; 2 | 3 | import org.apache.commons.lang3.builder.ToStringBuilder; 4 | import org.apache.commons.lang3.builder.ToStringStyle; 5 | 6 | import com.google.common.base.Objects.ToStringHelper; 7 | 8 | public class ObjectBuilder { 9 | 10 | public static void main(String[] args) { 11 | 12 | } 13 | } 14 | 15 | class NutritionFacts { 16 | private int servingSize; 17 | private int servings; 18 | private int calories; 19 | private int fat; 20 | private int sodium; 21 | private int carbohydrate; 22 | 23 | 24 | public void setServingSize(int servingSize) { 25 | this.servingSize = servingSize; 26 | } 27 | 28 | 29 | public void setServings(int servings) { 30 | this.servings = servings; 31 | } 32 | 33 | 34 | public void setCalories(int calories) { 35 | this.calories = calories; 36 | } 37 | 38 | 39 | public void setFat(int fat) { 40 | this.fat = fat; 41 | } 42 | 43 | 44 | public void setSodium(int sodium) { 45 | this.sodium = sodium; 46 | } 47 | 48 | 49 | public void setCarbohydrate(int carbohydrate) { 50 | this.carbohydrate = carbohydrate; 51 | } 52 | 53 | 54 | public int getServingSize() { 55 | return servingSize; 56 | } 57 | 58 | 59 | public int getServings() { 60 | return servings; 61 | } 62 | 63 | 64 | public int getCalories() { 65 | return calories; 66 | } 67 | 68 | 69 | public int getFat() { 70 | return fat; 71 | } 72 | 73 | 74 | public int getSodium() { 75 | return sodium; 76 | } 77 | 78 | 79 | public int getCarbohydrate() { 80 | return carbohydrate; 81 | } 82 | 83 | 84 | public static class NutritionFactBuilder { 85 | NutritionFacts nutritionFacts; 86 | public NutritionFactBuilder(NutritionFacts nutritionFacts) { 87 | this.nutritionFacts = nutritionFacts; 88 | } 89 | 90 | public NutritionFacts servingSize(int servingSize){ 91 | nutritionFacts.setServingSize(servingSize); 92 | return nutritionFacts; 93 | } 94 | 95 | public NutritionFacts servings(int servings){ 96 | nutritionFacts.setServings(servings); 97 | return nutritionFacts; 98 | } 99 | 100 | } 101 | } 102 | -------------------------------------------------------------------------------- /src/main/java/com/shawn/guru/StoreCredit.java: -------------------------------------------------------------------------------- 1 | package com.shawn.guru; 2 | 3 | import java.io.BufferedReader; 4 | import java.io.File; 5 | import java.io.FileReader; 6 | import java.io.PrintWriter; 7 | import java.util.List; 8 | 9 | import com.google.common.base.Strings; 10 | import com.google.common.collect.Lists; 11 | 12 | public class StoreCredit { 13 | private static final String FILE_PATH = "~/"; 14 | private int total = 0; 15 | 16 | public static void main(String[] args) { 17 | System.out.printf("1212123 \r"); 18 | } 19 | 20 | private void printOutput(List ints) throws Exception { 21 | PrintWriter pw = new PrintWriter(new File(FILE_PATH + "A-small-out.in")); 22 | for (int i = 0; i < ints.size(); i++) { 23 | pw.write("Case #"+(i+1) + ": "); 24 | for(int j = 0 ; j readList() throws Exception { 33 | List credits = Lists.newArrayList(); 34 | File file = new File(FILE_PATH + "A-small-practice.in"); 35 | BufferedReader br = new BufferedReader(new FileReader(file)); 36 | total = br.read(); 37 | while (Strings.isNullOrEmpty(br.readLine())) { 38 | CreditConsumer cc = new CreditConsumer(); 39 | cc.setCredits(Integer.parseInt(br.readLine())); 40 | String[] items = br.readLine().split(" "); 41 | List itemPrice = Lists.newArrayListWithCapacity(items.length); 42 | for (int i = 0; i < items.length; i++) { 43 | itemPrice.add(Integer.parseInt(items[i])); 44 | } 45 | cc.setAvailibleItems(itemPrice); 46 | credits.add(cc); 47 | } 48 | br.close(); 49 | return credits; 50 | } 51 | } 52 | 53 | class CreditConsumer { 54 | private int credits; 55 | private List availibleItems; 56 | 57 | public int getCredits() { 58 | return credits; 59 | } 60 | 61 | public void setCredits(int credits) { 62 | this.credits = credits; 63 | } 64 | 65 | public List getAvailibleItems() { 66 | return availibleItems; 67 | } 68 | 69 | public void setAvailibleItems(List availibleItems) { 70 | this.availibleItems = availibleItems; 71 | } 72 | 73 | } 74 | -------------------------------------------------------------------------------- /src/test/java/com/shawn/template/TestTemplate.java: -------------------------------------------------------------------------------- 1 | package com.shawn.template; 2 | 3 | import org.junit.Before; 4 | import org.junit.Test; 5 | 6 | import static org.junit.Assert.*; 7 | public class TestTemplate { 8 | 9 | private Template template; 10 | 11 | @Before 12 | public void setUp(){ 13 | template = new Template("${one},${two},${three}"); 14 | template.set("one", "1"); 15 | template.set("two", "2"); 16 | template.set("three", "3"); 17 | } 18 | /* @Test 19 | public void oneVariable(){ 20 | Template template = new Template("Hello, ${name}"); 21 | template.set("name","Reader"); 22 | assertEquals("Hello, Reader", template.evaluate()); 23 | } 24 | 25 | @Test 26 | public void diffTemplate(){ 27 | Template template = new Template("Hello, ${name}"); 28 | template.set("name","someone else"); 29 | assertEquals("Hello, someone else",template.evaluate()); 30 | } 31 | */ 32 | @Test 33 | public void multipleVariables(){ 34 | /*Template template = new Template("${one},${two},${three}"); 35 | template.set("one", "1"); 36 | template.set("two", "2"); 37 | template.set("three", "3"); 38 | assertEquals("1,2,3", template.evaluate());*/ 39 | assertTemplateEvaluatesTo("1,2,3"); 40 | } 41 | 42 | @Test 43 | public void unkownVariableIgnored(){ 44 | /*Template template = new Template("Hello, ${name}"); 45 | template.set("name", "Reader");*/ 46 | template.set("doesnotexist", "Hi"); 47 | //assertEquals("Hello, Reader", template.evaluate()); 48 | assertTemplateEvaluatesTo("1,2,3"); 49 | } 50 | 51 | 52 | @Test(expected=MissingValueException.class) 53 | public void missingValueRaiseException(){ 54 | //try { 55 | new Template("${foo}").evaluate(); 56 | /* fail("evaluate() should throw an exception if a variable was left w/o a value"); 57 | } catch (MissingValueException e) { 58 | // TODO: handle exception 59 | }*/ 60 | } 61 | 62 | 63 | @Test 64 | public void variablesGetProcessedJustOnce(){ 65 | template.set("one", "${one}"); 66 | template.set("two", "${three}"); 67 | template.set("three", "${two}"); 68 | assertTemplateEvaluatesTo("${one},${three},${two}"); 69 | } 70 | private void assertTemplateEvaluatesTo(String expected){ 71 | assertEquals(expected, template.evaluate()); 72 | } 73 | 74 | 75 | 76 | 77 | 78 | } 79 | -------------------------------------------------------------------------------- /src/main/java/com/shawn/general/enumTest.java: -------------------------------------------------------------------------------- 1 | package com.shawn.general; 2 | 3 | import jdk.nashorn.internal.runtime.regexp.joni.constants.OPCode; 4 | 5 | import java.util.HashMap; 6 | import java.util.Map; 7 | 8 | /** 9 | * Created by Shangfei on 2/25/16. 10 | */ 11 | public class enumTest { 12 | public static void main(String[] args){ 13 | for (Planet p: Planet.values()) { 14 | System.out.printf("Weight on %s is %f%n",p, p.surfaceWeight()); 15 | } 16 | } 17 | 18 | private static & Operation> void test(Class opSet, double x, double y) { 19 | for (Operation op : opSet.getEnumConstants()) { 20 | System.out.printf("%f %s %f = %f %n",x ,op, y, op.apply(x, y)); 21 | } 22 | } 23 | 24 | enum Planet { 25 | Mecrury(3.302e+23, 2.439e6), 26 | Earth(5.975e+24, 6.053e6); 27 | 28 | private final double mass; 29 | private final double radius; 30 | private final double surfaceGravity; 31 | 32 | private static final double G = 6.67300E-11; 33 | 34 | Planet(double mass, double radius){ 35 | this.mass = mass; 36 | this.radius = radius; 37 | surfaceGravity = G * mass/ (radius * radius); 38 | } 39 | 40 | public double surfaceWeight() { 41 | return mass * surfaceGravity; 42 | } 43 | } 44 | public interface Operation{ 45 | public double apply(double x, double y); 46 | } 47 | 48 | public enum BasicOperation implements Operation{ 49 | PLUS("+"){ 50 | @Override 51 | public double apply(double x, double y){ 52 | return x + y; 53 | } 54 | }, 55 | MINUS("-"){ 56 | @Override 57 | public double apply(double x, double y) { 58 | return x - y; 59 | } 60 | }; 61 | 62 | private final String symbol; 63 | public static final Map stringToEnum = new HashMap<>(); 64 | static{ 65 | for(BasicOperation op: BasicOperation.values()) 66 | stringToEnum.put(op.toString(), op); 67 | } 68 | BasicOperation(String symbol){ 69 | this.symbol = symbol; 70 | } 71 | @Override 72 | public String toString() { 73 | return symbol; 74 | } 75 | 76 | public static BasicOperation fromString(String symbol) { 77 | return stringToEnum.get(symbol); 78 | } 79 | } 80 | } 81 | -------------------------------------------------------------------------------- /src/main/java/com/shawn/concurrent/util/SyncBankAccount.java: -------------------------------------------------------------------------------- 1 | package com.shawn.concurrent.util; 2 | 3 | public class SyncBankAccount { 4 | public static void main(String[] args) { 5 | Accounts account = new Accounts(); 6 | account.setBalance(1000); 7 | Company company = new Company(account); 8 | Thread companyThread = new Thread(company); 9 | 10 | Bank bank = new Bank(account); 11 | Thread bankThread = new Thread(bank); 12 | System.out.printf("Account : Initial Balance: %f\n", account.getBalance()); 13 | companyThread.start(); 14 | bankThread.start(); 15 | 16 | try { 17 | companyThread.join(); 18 | bankThread.join(); 19 | System.out.printf("Account : Final Balance: %f\n", account.getBalance()); 20 | } catch (InterruptedException e) { 21 | e.printStackTrace(); 22 | } 23 | } 24 | 25 | } 26 | 27 | class Company implements Runnable { 28 | private Accounts account; 29 | 30 | public Company(Accounts account) { 31 | this.account = account; 32 | } 33 | 34 | public void run() { 35 | for (int i = 0; i < 100; i++) { 36 | account.addAmount(1000); 37 | } 38 | } 39 | 40 | } 41 | 42 | class Bank implements Runnable { 43 | 44 | private Accounts account; 45 | 46 | public Bank(Accounts account) { 47 | this.account = account; 48 | } 49 | 50 | public void run() { 51 | for (int i = 0; i < 100; i++) { 52 | account.subtractAmount(1000); 53 | } 54 | } 55 | 56 | } 57 | 58 | class Accounts { 59 | private double balance; 60 | 61 | public double getBalance() { 62 | return balance; 63 | } 64 | 65 | public void setBalance(double balance) { 66 | this.balance = balance; 67 | } 68 | 69 | public synchronized void addAmount(double amount) { 70 | double tmp = this.balance; 71 | /*try { 72 | Thread.sleep(10); 73 | } catch (Exception e) { 74 | e.printStackTrace(); 75 | }*/ 76 | tmp += amount; 77 | balance = tmp; 78 | System.out.println("balance " + balance); 79 | } 80 | 81 | public synchronized void subtractAmount(double amount) { 82 | double tmp = balance; 83 | /*try { 84 | Thread.sleep(10); 85 | } catch (Exception e) { 86 | e.printStackTrace(); 87 | }*/ 88 | 89 | tmp -= amount; 90 | balance = tmp; 91 | System.out.println("balance " + balance); 92 | } 93 | 94 | } 95 | -------------------------------------------------------------------------------- /src/main/java/com/shawn/nio/AsyncIO.java: -------------------------------------------------------------------------------- 1 | package com.shawn.nio; 2 | 3 | import java.io.IOException; 4 | import java.nio.ByteBuffer; 5 | import java.nio.channels.AsynchronousFileChannel; 6 | import java.nio.channels.CompletionHandler; 7 | import java.nio.file.Path; 8 | import java.nio.file.Paths; 9 | import java.util.concurrent.ExecutionException; 10 | import java.util.concurrent.Future; 11 | 12 | /** 13 | * User: Shawn cao 14 | * Date: 13-9-13 15 | * Time: PM8:54 16 | */ 17 | public class AsyncIO { 18 | 19 | static final Path file = Paths.get("/var/log/daily.out"); 20 | public static void main(String[] args){ 21 | //asyncFile(); 22 | callbackFile(); 23 | } 24 | public static void asyncFile(){ 25 | 26 | 27 | try { 28 | AsynchronousFileChannel channel = AsynchronousFileChannel.open(file); 29 | ByteBuffer buffer = ByteBuffer.allocate(100_0000); 30 | Future result = channel.read(buffer,0); 31 | while (!result.isDone()){ 32 | System.out.println("*********"); 33 | } 34 | Integer bytesRead = result.get(); 35 | System.out.println("Byte read[" + bytesRead + "]"); 36 | } catch (IOException e) { 37 | e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. 38 | } catch (InterruptedException e) { 39 | e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. 40 | } catch (ExecutionException e) { 41 | e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. 42 | } 43 | } 44 | 45 | public static void callbackFile(){ 46 | try { 47 | AsynchronousFileChannel channel = AsynchronousFileChannel.open(file); 48 | ByteBuffer buffer = ByteBuffer.allocate(1000_0000); 49 | channel.read(buffer,0,buffer,new CompletionHandler() { 50 | @Override 51 | public void completed(Integer result, ByteBuffer attachment) { 52 | System.out.println("Bytes read[" + result+"]"); 53 | } 54 | 55 | @Override 56 | public void failed(Throwable exc, ByteBuffer attachment) { 57 | System.out.println(exc.getMessage()); 58 | } 59 | }); 60 | } catch (IOException e) { 61 | e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. 62 | } 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /src/main/java/com/shawn/concurrent/util/CountDownLatchDemo.java: -------------------------------------------------------------------------------- 1 | package com.shawn.concurrent.util; 2 | 3 | import java.util.concurrent.CountDownLatch; 4 | import java.util.concurrent.TimeUnit; 5 | 6 | public class CountDownLatchDemo { 7 | 8 | public static void main(String[] args) throws InterruptedException { 9 | CountDownLatch startLatch = new CountDownLatch(1); 10 | VideoConference conference = new VideoConference(10,startLatch); 11 | Thread threadConference = new Thread(conference); 12 | threadConference.start(); 13 | 14 | for (int i = 0; i < 10; i++) { 15 | Participant participant = new Participant(conference, "participant " + i); 16 | Thread thread = new Thread(participant); 17 | thread.start(); 18 | } 19 | startLatch.await(); 20 | System.out.println("Video conference started "); 21 | } 22 | } 23 | 24 | 25 | 26 | class VideoConference implements Runnable{ 27 | 28 | private final CountDownLatch controller; 29 | private CountDownLatch startLatch; 30 | public VideoConference(int number,CountDownLatch startLatch) { 31 | controller = new CountDownLatch(number); 32 | this.startLatch = startLatch; 33 | } 34 | 35 | public void arrive(String name){ 36 | System.out.printf("%s has arrived. ",name); 37 | controller.countDown(); 38 | System.out.printf("Video conference: waiting for %d participants. \n",controller.getCount()); 39 | } 40 | public void run() { 41 | System.out.printf("Video conference: Initialization: %d participants.\n",controller.getCount()); 42 | try { 43 | controller.await(); 44 | System.out.printf("Video conference: All the participants have come \n "); 45 | System.out.printf("Video conference: It's ready...\n"); 46 | startLatch.countDown(); 47 | } catch (Exception e) { 48 | e.printStackTrace(); 49 | } 50 | } 51 | 52 | } 53 | 54 | class Participant implements Runnable{ 55 | private VideoConference videoConference; 56 | private String name; 57 | 58 | public Participant(VideoConference videoConference,String name) { 59 | this.videoConference = videoConference; 60 | this.name = name; 61 | } 62 | 63 | public void run() { 64 | long duration = (long)(Math.random()*10); 65 | try { 66 | TimeUnit.SECONDS.sleep(duration); 67 | } catch (Exception e) { 68 | e.printStackTrace(); 69 | } 70 | videoConference.arrive(name); 71 | } 72 | 73 | 74 | } 75 | -------------------------------------------------------------------------------- /src/main/java/com/shawn/nio/FileManipulation.java: -------------------------------------------------------------------------------- 1 | package com.shawn.nio; 2 | 3 | import java.io.File; 4 | import java.io.FileInputStream; 5 | import java.io.FileOutputStream; 6 | import java.io.IOException; 7 | import java.nio.channels.FileChannel; 8 | import java.nio.file.Files; 9 | import java.nio.file.Path; 10 | import java.nio.file.Paths; 11 | import java.nio.file.StandardCopyOption; 12 | import java.nio.file.attribute.FileAttribute; 13 | import java.nio.file.attribute.PosixFilePermission; 14 | import java.nio.file.attribute.PosixFilePermissions; 15 | import java.util.Set; 16 | 17 | /** 18 | * User: Shawn cao 19 | * Date: 13-9-12 20 | * Time: PM11:26 21 | */ 22 | public class FileManipulation { 23 | 24 | public static void main(String[] args) throws IOException { 25 | filePermission(); 26 | //deleteFile(); 27 | fileCopy(); 28 | } 29 | 30 | private static void filePermission() throws IOException { 31 | Path target = Paths.get("/Users/caocao024/tmp"); 32 | if(!target.toFile().exists()){ 33 | Set perms = PosixFilePermissions.fromString("rw-rw-rw-"); 34 | FileAttribute> attribute = PosixFilePermissions.asFileAttribute(perms); 35 | Files.createFile(target,attribute); 36 | } 37 | 38 | } 39 | 40 | private static void deleteFile() throws IOException{ 41 | Path target = Paths.get("/Users/caocao024/tmp"); 42 | Files.delete(target); 43 | } 44 | 45 | private static void fileCopy() throws IOException{ 46 | Path source = Paths.get("/Users/caocao024/tmp"); 47 | Path target = Paths.get("/Users/caocao024/temp/tmp"); 48 | Files.move(source,target, StandardCopyOption.ATOMIC_MOVE); 49 | } 50 | 51 | public static void copyFile(File sourceFile,String toPath) throws IOException{ 52 | 53 | File desFile = new File(toPath+"/"+sourceFile.getName()); 54 | 55 | FileChannel source = null; 56 | FileChannel destination = null; 57 | try { 58 | source = new FileInputStream(sourceFile).getChannel(); 59 | destination = new FileOutputStream(desFile).getChannel(); 60 | long count = 0; 61 | long size = source.size(); 62 | System.out.println("11: " + size); 63 | while((count+=destination.transferFrom(source, count, size -count)) posixFilePermission = attributes.permissions(); 30 | posixFilePermission.clear(); 31 | String owner = attributes.owner().getName(); 32 | String perms = PosixFilePermissions.toString(posixFilePermission); 33 | System.out.format("%s %s %n",owner,perms); 34 | 35 | posixFilePermission.add(PosixFilePermission.OWNER_READ); 36 | posixFilePermission.add(PosixFilePermission.GROUP_READ); 37 | posixFilePermission.add(PosixFilePermission.OTHERS_READ); 38 | posixFilePermission.add(PosixFilePermission.OWNER_WRITE); 39 | Files.setPosixFilePermissions(target,posixFilePermission); 40 | 41 | } 42 | private static void readAttribute(){ 43 | try{ 44 | Path zip = Paths.get("/usr/bin/zip"); 45 | System.out.println(Files.getLastModifiedTime(zip)); 46 | System.out.println(Files.size(zip)); 47 | System.out.println(Files.isSymbolicLink(zip)); 48 | System.out.println(Files.isDirectory(zip)); 49 | System.out.println(Files.readAttributes(zip,"*")); 50 | }catch(IOException e){ 51 | 52 | } 53 | } 54 | 55 | private static void readSymbolic(){ 56 | Path file=Paths.get("/usr/bin/scala"); 57 | try{ 58 | if(Files.isSymbolicLink(file)){ 59 | file = Files.readSymbolicLink(file); 60 | } 61 | BasicFileAttributes attributes = Files.readAttributes(file, BasicFileAttributes.class); 62 | System.out.println("---"+attributes.creationTime()); 63 | }catch (IOException e){ 64 | e.printStackTrace(); 65 | } 66 | 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /src/main/java/com/shawn/concurrent/util/Account.java: -------------------------------------------------------------------------------- 1 | package com.shawn.concurrent.util; 2 | 3 | import java.util.concurrent.TimeUnit; 4 | import java.util.concurrent.locks.Lock; 5 | import java.util.concurrent.locks.ReentrantLock; 6 | 7 | public class Account implements Comparable { 8 | private int balance; 9 | public final Lock monitor = new ReentrantLock(); 10 | 11 | public Account(final int initialBalance) { 12 | balance = initialBalance; 13 | } 14 | 15 | public void deposit(final int amount) { 16 | 17 | try { 18 | monitor.lock(); 19 | if (amount > 0) { 20 | balance += amount; 21 | } 22 | } finally { 23 | monitor.unlock(); 24 | } 25 | } 26 | 27 | 28 | public boolean withdraw(final int amount){ 29 | try { 30 | monitor.lock(); 31 | if(amount >0 && balance >= amount){ 32 | balance-= amount; 33 | return true; 34 | } 35 | return false; 36 | }finally{ 37 | monitor.unlock(); 38 | } 39 | } 40 | @Override 41 | public int compareTo(Account other) { 42 | return new Integer(hashCode()).compareTo(other.hashCode()); 43 | } 44 | 45 | @Override 46 | public String toString() { 47 | return String.valueOf(this.balance); 48 | } 49 | } 50 | 51 | class AccountService{ 52 | public boolean transfer(final Account from, final Account to,final int amount) throws Exception{ 53 | /* final Account[] accounts = new Account[]{from,to}; 54 | Arrays.sort(accounts);*/ 55 | if(from.monitor.tryLock(1,TimeUnit.MILLISECONDS)){ 56 | try{ 57 | if(to.monitor.tryLock(1,TimeUnit.MILLISECONDS)){ 58 | try{ 59 | if(from.withdraw(amount)){ 60 | to.deposit(amount); 61 | return true; 62 | }else { 63 | return false; 64 | } 65 | }finally{ 66 | from.monitor.lock(); 67 | } 68 | } 69 | }finally{ 70 | to.monitor.unlock(); 71 | } 72 | } 73 | throw new Exception("unable to acquire a lock"); 74 | } 75 | 76 | public static void main(String[] args) throws Exception { 77 | Account from = new Account(500); 78 | Account to = new Account(1000); 79 | new AccountService().transfer(from,to, 300); 80 | System.out.format("from :%s to:%s", from.toString(), to.toString()); 81 | } 82 | } 83 | -------------------------------------------------------------------------------- /src/main/java/com/shawn/concurrent/util/QueueLock.java: -------------------------------------------------------------------------------- 1 | package com.shawn.concurrent.util; 2 | 3 | import java.util.concurrent.locks.Lock; 4 | import java.util.concurrent.locks.ReentrantLock; 5 | 6 | 7 | public class QueueLock { 8 | public static void main(String[] args) { 9 | PrintQueue printQueue = new PrintQueue(); 10 | Thread[] threads = new Thread[10]; 11 | for (int i = 0; i < threads.length; i++) { 12 | threads[i] = new Thread(new Job(printQueue), "Thread " + i); 13 | } 14 | 15 | for (int i = 0; i < threads.length; i++) { 16 | threads[i].start(); 17 | } 18 | } 19 | } 20 | 21 | class Job implements Runnable { 22 | private PrintQueue printQueue; 23 | 24 | public Job(PrintQueue printQueue) { 25 | this.printQueue = printQueue; 26 | } 27 | 28 | public void run() { 29 | System.out.printf("%s: Going to print a document\n", Thread.currentThread().getName()); 30 | printQueue.printJob(new Object()); 31 | // printQueue.printJobWithTimeDuration(new Object()); 32 | System.out.printf("%s: The document has been printed\n", Thread.currentThread().getName()); 33 | } 34 | 35 | } 36 | 37 | class PrintQueue { 38 | // private final Lock queueLock = new ReentrantLock(); 39 | private final Lock queueLock = new ReentrantLock(true); 40 | 41 | public void printJob(Object document) { 42 | if (queueLock.tryLock()) { 43 | /** 44 | * alternatively:queueLock.lock(); 45 | * 46 | */ 47 | 48 | try { 49 | Long duration = (long) (Math.random() * 100); 50 | System.out.println(Thread.currentThread().getName() + ":PrintQueue: Printing a Job during " + (duration / 1000) + " seconds"); 51 | Thread.sleep(duration); 52 | } catch (InterruptedException e) { 53 | e.printStackTrace(); 54 | } 55 | } 56 | /* 57 | * alternative: finally { queueLock.unlock(); } } 58 | */ 59 | } 60 | 61 | public void printJobWithTimeDuration(Object document) { 62 | for (int i = 0; i < 2; i++) { 63 | queueLock.lock(); 64 | try { 65 | Long duration = (long) (Math.random() * 5000); 66 | System.out.println(Thread.currentThread().getName() + ":PrintQueue: Printing a Job during " + (duration / 1000) + " seconds"); 67 | Thread.sleep(duration); 68 | } catch (InterruptedException e) { 69 | e.printStackTrace(); 70 | } finally { 71 | queueLock.unlock(); 72 | } 73 | } 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /src/main/java/com/shawn/concurrent/executor/FactorialCallable.java: -------------------------------------------------------------------------------- 1 | package com.shawn.concurrent.executor; 2 | 3 | import java.util.List; 4 | import java.util.Random; 5 | import java.util.concurrent.Callable; 6 | import java.util.concurrent.Executors; 7 | import java.util.concurrent.Future; 8 | import java.util.concurrent.ThreadPoolExecutor; 9 | import java.util.concurrent.TimeUnit; 10 | 11 | import com.google.common.collect.Lists; 12 | 13 | public class FactorialCallable { 14 | public static void main(String[] args) { 15 | ThreadPoolExecutor executor = (ThreadPoolExecutor)Executors.newFixedThreadPool(2); 16 | List> resultList = Lists.newArrayList(); 17 | 18 | Random random = new Random(); 19 | for (int i = 0; i < 10; i++) { 20 | Integer number = random.nextInt(10); 21 | FactorialCalculator calculator = new FactorialCalculator(number); 22 | Future result = executor.submit(calculator); 23 | resultList.add(result); 24 | } 25 | do { 26 | System.out.printf("Main: Number of completed tasks: %d \n",executor.getCompletedTaskCount()); 27 | for (int i = 0; i < resultList.size(); i++) { 28 | Future result = resultList.get(i); 29 | System.out.printf("Main : Task %d: %s\n",i,result.isDone()); 30 | } 31 | try { 32 | TimeUnit.MILLISECONDS.sleep(50); 33 | } catch (Exception e) { 34 | e.printStackTrace(); 35 | } 36 | } while (executor.getCompletedTaskCount() < resultList.size()); 37 | System.out.printf("Main: Result. \n"); 38 | for (int i = 0; i < resultList.size(); i++) { 39 | Future result = resultList.get(i); 40 | Integer number = null; 41 | try { 42 | number = result.get(); 43 | } catch (Exception e) { 44 | e.printStackTrace(); 45 | } 46 | System.out.printf("Main: Task %d: %d \n",i,number); 47 | } 48 | executor.shutdown(); 49 | } 50 | } 51 | 52 | class FactorialCalculator implements Callable{ 53 | 54 | private Integer number; 55 | 56 | public FactorialCalculator(Integer number){ 57 | this.number = number; 58 | } 59 | public Integer call() throws Exception { 60 | int result = 1; 61 | if((number ==0) || (number==1)){ 62 | result = 1; 63 | }else { 64 | for (int i = 2; i < number; i++) { 65 | result*=i; 66 | TimeUnit.MILLISECONDS.sleep(20); 67 | } 68 | } 69 | System.out.printf("%s: %d \n",Thread.currentThread().getName(),result); 70 | return result; 71 | } 72 | 73 | } -------------------------------------------------------------------------------- /src/main/java/com/shawn/nio/FilePath.java: -------------------------------------------------------------------------------- 1 | package com.shawn.nio; 2 | 3 | import java.io.IOException; 4 | import java.nio.file.FileVisitResult; 5 | import java.nio.file.Files; 6 | import java.nio.file.Path; 7 | import java.nio.file.Paths; 8 | import java.nio.file.SimpleFileVisitor; 9 | import java.nio.file.StandardCopyOption; 10 | import java.nio.file.attribute.BasicFileAttributes; 11 | 12 | /** 13 | * Created with IntelliJ IDEA. 14 | * User: caocao024 15 | * Date: 13-9-12 16 | * Time: PM10:03 17 | * To change this template use File | Settings | File Templates. 18 | */ 19 | public class FilePath { 20 | 21 | public static void main(String[] args) throws IOException { 22 | /* Path listing = Paths.get("/usr/bin/zip"); 23 | System.out.println(listing.getRoot()+" | " + listing.getParent() + " | "+listing.getNameCount()); 24 | Path normalizedPath = Paths.get("./FilePath.java").normalize(); 25 | System.out.println(normalizedPath.toString()); 26 | Path dir = Paths.get("/Users/caocao024/workspace/tianji-job"); 27 | try (DirectoryStream stream = Files.newDirectoryStream(dir,"*.xml")){ 28 | for(Path entry:stream) 29 | System.out.println(entry.getFileName()); 30 | }catch (IOException e){ 31 | System.out.println(e.getMessage()); 32 | } */ 33 | 34 | //Path startingDir = Paths.get("/Users/caocao024/workspace/tianji-job"); 35 | //Files.walkFileTree(startingDir,new FindPomVisitor()); 36 | Path dir = Paths.get("/Users/caocao024/Downloads"); 37 | Files.walkFileTree(dir,new FindVedioMove("/Users/caocao024/Downloads/.r")); 38 | } 39 | 40 | private static class FindPomVisitor extends SimpleFileVisitor{ 41 | 42 | @Override 43 | public FileVisitResult visitFile(Path file,BasicFileAttributes attributes){ 44 | 45 | if(file.toString().endsWith(".xml")){ 46 | System.out.println(file.getFileName()); 47 | } 48 | return FileVisitResult.CONTINUE; 49 | } 50 | } 51 | 52 | private static class FindVedioMove extends SimpleFileVisitor{ 53 | String movePath; 54 | FindVedioMove(String movePath){ 55 | this.movePath = movePath; 56 | } 57 | @Override 58 | public FileVisitResult visitFile(Path file,BasicFileAttributes attributes) throws IOException { 59 | 60 | if(file.toString().endsWith(".mp4")||file.toString().endsWith(".wmv")){ 61 | Files.createFile(Paths.get(movePath + "/" + file.getFileName())); 62 | Files.move(file,Paths.get(movePath + "/" + file.getFileName()),StandardCopyOption.REPLACE_EXISTING); 63 | //Files.delete(file); 64 | } 65 | return FileVisitResult.CONTINUE; 66 | } 67 | } 68 | 69 | 70 | } 71 | 72 | 73 | 74 | -------------------------------------------------------------------------------- /src/main/java/com/shawn/template/Template.java: -------------------------------------------------------------------------------- 1 | package com.shawn.template; 2 | 3 | import java.util.List; 4 | import java.util.Map; 5 | 6 | import com.google.common.collect.Maps; 7 | 8 | 9 | public class Template { 10 | //private String variableValue; 11 | private Map variables; 12 | private String templateText; 13 | public Template(String templateText){ 14 | variables = Maps.newLinkedHashMap(); 15 | this.templateText = templateText; 16 | } 17 | 18 | public void set(String name,String value){ 19 | //this.variableValue = value; 20 | variables.put(name, value); 21 | } 22 | 23 | public String evaluate(){ 24 | /*String result = replaceVariable(); 25 | checkForMissingValue(result);*/ 26 | TemplateParse parser = new TemplateParse(); 27 | List segments = parser.parseSegments(templateText); 28 | return concatenate(segments); 29 | /*List segments = parser.parse(templateText); 30 | StringBuilder result = new StringBuilder(); 31 | for(String segment:segments){ 32 | append(segment, result); 33 | }*/ 34 | // return result.toString(); 35 | } 36 | 37 | private String concatenate(List segments){ 38 | StringBuilder result = new StringBuilder(); 39 | for(Segment segment:segments){ 40 | //segment.appendTo(result,variables); 41 | result.append(segment.evaluate(variables)); 42 | } 43 | return result.toString(); 44 | } 45 | 46 | private void append(String segment,StringBuilder result){ 47 | if(isVariable(segment)){ 48 | evaluateVariable(segment, result); 49 | }else{ 50 | result.append(segment); 51 | } 52 | } 53 | 54 | 55 | public static boolean isVariable(String segment){ 56 | return segment.startsWith("${") && segment.endsWith("}"); 57 | } 58 | 59 | private void evaluateVariable(String segment,StringBuilder result){ 60 | String var = segment.substring(2,segment.length()-1); 61 | if(!variables.containsKey(var)){ 62 | throw new MissingValueException("No value for: " + segment); 63 | } 64 | result.append(variables.get(var)); 65 | } 66 | /* private String replaceVariable(){ 67 | String result = templateText; 68 | for(Entry entry:variables.entrySet()){ 69 | String regex = "\\$\\{"+entry.getKey() + "\\}"; 70 | result = result.replaceAll(regex, entry.getValue()); 71 | } 72 | return result; 73 | } 74 | private void checkForMissingValue(String result){ 75 | Matcher m = Pattern.compile(".*\\$\\{.+\\}.*").matcher(result); 76 | if(m.find()){ 77 | throw new MissingValueException("No value for " + m.group()); 78 | } 79 | }*/ 80 | } 81 | -------------------------------------------------------------------------------- /src/main/java/com/shawn/nio/GatheringChannelTest.java: -------------------------------------------------------------------------------- 1 | package com.shawn.nio; 2 | 3 | import java.io.FileOutputStream; 4 | import java.nio.ByteBuffer; 5 | import java.nio.channels.GatheringByteChannel; 6 | import java.nio.charset.Charset; 7 | import java.util.List; 8 | import java.util.Random; 9 | 10 | import com.google.common.collect.Lists; 11 | 12 | public class GatheringChannelTest { 13 | 14 | private static final String DEMOGRAPHIC = "com/shawn/nio/blahblah.txt"; 15 | 16 | private static String[] col1 = { "Aggregate", "Enable", "Leverage", "Facilitate", "Synergize", "Repurpose", "Strategize", "Reinvent", "Harness" }; 17 | private static String[] col2 = { "cross-platform", "best-of-breed", "frictionless", "ubiquitous", "extensible", "compelling", "mission-critical", "collaborative", 18 | "integrated" }; 19 | private static String[] col3 = { "methodologies", "infomediaries", "platforms", "schemas", "mindshare", "paradigms", "functionalities", "web services", 20 | "infrastructures" }; 21 | 22 | private static String newline = System.getProperty("line.separator"); 23 | private static Random random = new Random(); 24 | 25 | private static ByteBuffer[] utterBS(int howmany) throws Exception { 26 | List list = Lists.newLinkedList(); 27 | for (int i = 0; i < howmany; i++) { 28 | list.add(pickRandom(col1, " ")); 29 | list.add(pickRandom(col2, " ")); 30 | list.add(pickRandom(col3, newline)); 31 | } 32 | ByteBuffer[] buffers = new ByteBuffer[list.size()]; 33 | list.toArray(buffers); 34 | return buffers; 35 | } 36 | 37 | private static ByteBuffer pickRandom(String[] strings, String suffix) throws Exception { 38 | String string = strings[random.nextInt(strings.length)]; 39 | int total = string.length() + suffix.length(); 40 | ByteBuffer buffer = ByteBuffer.allocate(total); 41 | buffer.put(string.getBytes(Charset.forName("UTF-8"))); 42 | buffer.put(suffix.getBytes(Charset.forName("UTF-8"))); 43 | buffer.flip(); 44 | return buffer; 45 | } 46 | 47 | public static void main(String[] args) throws Exception { 48 | int reps = 10; 49 | if (args.length > 0) { 50 | reps = Integer.parseInt(args[0]); 51 | } 52 | FileOutputStream fos = new FileOutputStream(DEMOGRAPHIC); 53 | GatheringByteChannel gatherChannel = fos.getChannel(); 54 | // Generate some brilliant marcom, er, repurposed content 55 | ByteBuffer[] bs = utterBS(reps); 56 | // Deliver the message to the waiting market 57 | while (gatherChannel.write(bs) > 0) { 58 | // Empty body 59 | // Loop until write( ) returns zero 60 | } 61 | System.out.println("Mindshare paradigms synergized to " + DEMOGRAPHIC); 62 | fos.close(); 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /src/main/java/com/shawn/general/RegexTest.java: -------------------------------------------------------------------------------- 1 | package com.shawn.general; import java.util.regex.Matcher; import java.util.regex.Pattern; import sun.security.krb5.internal.PAData; public class RegexTest { //static final String PATTERN = "^http://job.dajie.com/([\\s\\S]*.html)"; static String PATTERN = "^http://search.51job.com/jobsearch/search_result.php?(.*)"; static String LINK_PATTERN="^http://sou.zhaopin.com/jobs/searchresult.ashx((\\?p=[0-9]*){0,}$)"; public static void main(String[] args) { System.out.println(IsMatch("12345", "^[1]\\d{10}$")); System.out.println(IsMatch("12345678901", "^[1]\\d{10}$")); System.out.println(IsMatch("22345678901", "^[1]\\d{10}$")); /*System.out.println(IsMatch("m", "^m((\\?p=[0-9]*)*$)")); //System.out.println(IsMatch("http://job.dajie.com/0ade3c61-d141-4593-9136-3e5385cdad7e.html", PATTERN)); //System.out.println(IsMatch("http://job.dajie.com/search/result?page=10", "http://job.dajie.com/([\\s\\S]*.html)|(search/result?page=10)")); System.out.println(IsMatch("http://search.51job.com/list/000000%252C00,000000,0000,00,9,99,java,2,2.html?lang=c&stype=1&postchannel=0000&workyear=99&cotype=99°reefrom=99&jobterm=01&lonlat=0%2C0&radius=-1&ord_field=0&list_type=0&confirmdate=9", "^http://search.51job.com/list/(.*).html?(.*)")); System.out.println(IsMatch("http://http://search.51job.com/job/828123721,c.html", "^http://http://search.51job.com/job/([0-9]*),c.html")); System.out.println(IsMatch("http://sou.zhaopin.com/jobs/searchresult.ashx?sg=6a841f4660d24206919a96a95ae84740&p=2", "^http://sou.zhaopin.com/jobs/searchresult.ashx(.*)")); System.out.println(IsMatch("http://jobs.zhaopin.com/132621423250061.htm","http://jobs.zhaopin.com/(.*).htm")); //[p=[0-9]]|[^jl=[0-9]*&kw=[.*]&gc=[.*]&ga=[.*]&gr=[0-9]*] System.out.println(IsMatch("http://sou.zhaopin.com/jobs/searchresult.ashx?jl=530&kw=&gc=%e5%9c%b0%e9%93%816%e5%8f%b7%e7%ba%bf&ga=%e8%bd%a6%e5%85%ac%e5%ba%84%e8%a5%bf%e7%ab%99&gr=3", LINK_PATTERN)); System.out.println(IsMatch("http://sou.zhaopin.com/jobs/searchresult.ashx?p=23", LINK_PATTERN));*/ } public static boolean IsMatch(String string, String pattern) { try { Pattern patt = Pattern.compile(pattern); Matcher matcher = patt.matcher(string); return matcher.matches(); } catch (RuntimeException e) { return false; } } public static void pic() { // String string = null; // System.out.println((!Strings.isNullOrEmpty(string) || // !Strings.isNullOrEmpty(string.trim()))); String logo = "/upload/corps/logo/000/010/008/job_868551f460cc52c66723945a4e5cd879.png"; String fileName = "large_" + "3cf64ac0188d98fd1c34b593de2e9893.jpg"; String logoPath = logo.substring(0, logo.lastIndexOf("/")); logoPath = logoPath.replace("/logo/", "/cp_square_logo/"); System.out.println("http://www.tianji.com".concat(logoPath + "/" + fileName)); } } -------------------------------------------------------------------------------- /src/main/java/com/shawn/concurrent/basic/PriceInfoWithReadWriteLockDemo.java: -------------------------------------------------------------------------------- 1 | package com.shawn.concurrent.basic; 2 | 3 | import java.util.List; 4 | import java.util.concurrent.TimeUnit; 5 | import java.util.concurrent.locks.ReentrantReadWriteLock; 6 | import java.util.concurrent.locks.ReentrantReadWriteLock.ReadLock; 7 | import java.util.concurrent.locks.ReentrantReadWriteLock.WriteLock; 8 | import com.google.common.collect.Lists; 9 | 10 | public class PriceInfoWithReadWriteLockDemo { 11 | public static void main(String[] args) { 12 | PricesInfo pricesInfo = new PricesInfo(); 13 | List list = Lists.newArrayList(); 14 | 15 | for (int i=0; i<5; i++){ 16 | list.add(new Thread(new Reader(pricesInfo),"reader"+i)); 17 | } 18 | list.add(new Thread(new Writer(pricesInfo),"writer ")); 19 | 20 | for (Thread thread:list) { 21 | thread.start(); 22 | } 23 | 24 | } 25 | } 26 | 27 | 28 | class Reader implements Runnable{ 29 | private PricesInfo pricesInfo; 30 | public Reader(PricesInfo pricesInfo) { 31 | this.pricesInfo = pricesInfo; 32 | } 33 | @Override 34 | public void run() { 35 | for (int i=0; i<10; i++){ 36 | System.out.printf("%s: Price 1: %f\n", Thread.currentThread().getName(),pricesInfo.getPrice1()); 37 | System.out.printf("%s: Price 2: %f\n", Thread.currentThread().getName(),pricesInfo.getPrice2()); 38 | } 39 | } 40 | 41 | } 42 | class Writer implements Runnable{ 43 | private PricesInfo pricesInfo; 44 | public Writer(PricesInfo pricesInfo) { 45 | this.pricesInfo = pricesInfo; 46 | } 47 | @Override 48 | public void run() { 49 | double price1 = Math.random()*10; 50 | double price2 = Math.random()*8; 51 | try { 52 | TimeUnit.MILLISECONDS.sleep(20); 53 | } catch (InterruptedException e) { 54 | e.printStackTrace(); 55 | } 56 | pricesInfo.setPrices(price1, price2); 57 | } 58 | } 59 | 60 | class PricesInfo{ 61 | private double price1; 62 | private double price2; 63 | 64 | final private ReadLock readLock; 65 | final private WriteLock writeLock; 66 | public PricesInfo(){ 67 | price1=1.0; 68 | price2=2.0; 69 | ReentrantReadWriteLock readWriteLock = new ReentrantReadWriteLock(); 70 | readLock = readWriteLock.readLock(); 71 | writeLock = readWriteLock.writeLock(); 72 | } 73 | 74 | public double getPrice1() { 75 | readLock.lock(); 76 | double value = price1; 77 | readLock.unlock(); 78 | return value; 79 | } 80 | 81 | public double getPrice2() { 82 | readLock.lock(); 83 | double value = price2; 84 | readLock.unlock(); 85 | return value; 86 | } 87 | 88 | public void setPrices(double price1,double price2) { 89 | writeLock.lock(); 90 | System.out.printf("%s: Attempt to modify the prices with price1 %f, price2 %f.\n",Thread.currentThread().getName(),price1,price2); 91 | this.price1 = price1; 92 | this.price2 = price2; 93 | System.out.printf("%s: Prices have been modified.\n",Thread.currentThread().getName()); 94 | writeLock.unlock(); 95 | } 96 | } -------------------------------------------------------------------------------- /src/main/java/com/shawn/concurrent/util/ExchangeDataInConTask.java: -------------------------------------------------------------------------------- 1 | package com.shawn.concurrent.util; 2 | 3 | import java.util.List; 4 | import java.util.concurrent.Exchanger; 5 | 6 | import com.google.common.collect.Lists; 7 | 8 | public class ExchangeDataInConTask { 9 | public static void main(String[] args) { 10 | List buffer1 =Lists.newArrayList(); 11 | List buffer2 = Lists.newArrayList(); 12 | 13 | Exchanger> exchanger = new Exchanger>(); 14 | 15 | ExchangeProducer producer = new ExchangeProducer(buffer1,exchanger); 16 | ExchangeConsumer consumer = new ExchangeConsumer(buffer2, exchanger); 17 | 18 | Thread threadProducer = new Thread(producer); 19 | Thread threadConsumer = new Thread(consumer); 20 | 21 | threadConsumer.start(); 22 | threadProducer.start(); 23 | } 24 | } 25 | 26 | class ExchangeProducer implements Runnable{ 27 | private List buffer; 28 | 29 | private final Exchanger> exchanger; 30 | 31 | public ExchangeProducer(List buffer, Exchanger> exhcanger){ 32 | this.buffer = buffer; 33 | this.exchanger = exhcanger; 34 | } 35 | 36 | public void run() { 37 | int cycle = 1; 38 | for (int i = 0; i < 10; i++) { 39 | System.out.printf("Producer: cycle %d \n",cycle); 40 | for (int j = 0; j < 10; j++) { 41 | String message = "Event " + ((i*10) + j); 42 | System.out.printf("Producer: %s\n",message); 43 | buffer.add(message); 44 | } 45 | try { 46 | buffer = exchanger.exchange(buffer); 47 | } catch (Exception e) { 48 | e.printStackTrace(); 49 | } 50 | System.out.println("Producer: " + buffer.size()); 51 | cycle++; 52 | } 53 | } 54 | } 55 | 56 | class ExchangeConsumer implements Runnable{ 57 | private List buffer; 58 | 59 | private final Exchanger> exchanger; 60 | 61 | public ExchangeConsumer(List buffer, Exchanger> exchanger){ 62 | this.buffer = buffer; 63 | this.exchanger = exchanger; 64 | } 65 | 66 | public void run() { 67 | int cycle = 1; 68 | for (int i = 0; i < 10; i++) { 69 | System.out.printf("Consumer: Cycle %d \n",cycle); 70 | try { 71 | buffer = exchanger.exchange(buffer); 72 | } catch (Exception e) { 73 | e.printStackTrace(); 74 | } 75 | System.out.println("Consumer: " + buffer.size()); 76 | for (int j = 0; j < 10; j++) { 77 | String message = buffer.get(0); 78 | System.out.println("Consumer: " + message); 79 | buffer.remove(0); 80 | } 81 | cycle++; 82 | } 83 | } 84 | } 85 | 86 | 87 | -------------------------------------------------------------------------------- /src/main/java/com/shawn/concurrent/util/PrintQueueWithMultiRecSemaphore.java: -------------------------------------------------------------------------------- 1 | package com.shawn.concurrent.util; 2 | 3 | import java.util.concurrent.Semaphore; 4 | import java.util.concurrent.TimeUnit; 5 | import java.util.concurrent.locks.Lock; 6 | import java.util.concurrent.locks.ReentrantLock; 7 | 8 | public class PrintQueueWithMultiRecSemaphore { 9 | public static void main(String[] args){ 10 | PrintQueueWithMultiRec printQueueWithMultiRec=new PrintQueueWithMultiRec(); 11 | Thread thread[]=new Thread[10]; 12 | for (int i=0; i<10; i++){ 13 | thread[i]=new Thread(new JobWithMultiRec(printQueueWithMultiRec),"Thread"+i); 14 | } 15 | for (int i=0; i<10; i++){ 16 | thread[i].start(); 17 | } 18 | } 19 | } 20 | 21 | 22 | class JobWithMultiRec implements Runnable{ 23 | private PrintQueueWithMultiRec printQueueWithMultiRec; 24 | 25 | public JobWithMultiRec(PrintQueueWithMultiRec printQueueWithMultiRec){ 26 | this.printQueueWithMultiRec = printQueueWithMultiRec; 27 | } 28 | 29 | public void run() { 30 | System.out.printf("%s: Going to print a job\n",Thread.currentThread().getName()); 31 | printQueueWithMultiRec.printJob(new Object()); 32 | System.out.printf("%s: The document has been printed\n",Thread.currentThread().getName()); 33 | } 34 | } 35 | 36 | class PrintQueueWithMultiRec{ 37 | private boolean freePrinters[]; 38 | private Lock lockPrinters; 39 | private Semaphore semaphore; 40 | public PrintQueueWithMultiRec() { 41 | semaphore = new Semaphore(3); 42 | freePrinters = new boolean[3]; 43 | for (int i = 0; i < freePrinters.length; i++) { 44 | freePrinters[i] = true; 45 | } 46 | lockPrinters = new ReentrantLock(); 47 | } 48 | 49 | public void printJob(Object document){ 50 | try { 51 | semaphore.acquire(); 52 | int assignedPrinter = getPrinter(); 53 | long duration = (long) (Math.random()*10); 54 | System.out.printf("%s: printQueue: Printing a job in Printer %d during %d seconds \n", Thread.currentThread().getName(),assignedPrinter,duration); 55 | TimeUnit.SECONDS.sleep(duration); 56 | freePrinters[assignedPrinter] = true; 57 | } catch (Exception e) { 58 | e.printStackTrace(); 59 | }finally{ 60 | semaphore.release(); 61 | } 62 | } 63 | 64 | private int getPrinter(){ 65 | int ret = -1; 66 | try { 67 | lockPrinters.lock(); 68 | for (int i = 0; i < freePrinters.length; i++) { 69 | if (freePrinters[i]) { 70 | ret =i; 71 | freePrinters[i] = false; 72 | break; 73 | } 74 | } 75 | } catch (Exception e) { 76 | e.printStackTrace(); 77 | }finally{ 78 | lockPrinters.unlock(); 79 | } 80 | return ret; 81 | } 82 | } 83 | -------------------------------------------------------------------------------- /src/main/java/com/shawn/object/StaticFactory.java: -------------------------------------------------------------------------------- 1 | package com.shawn.object; 2 | 3 | import java.util.HashMap; 4 | 5 | import com.google.common.collect.ImmutableList; 6 | 7 | /** 8 | * Created with IntelliJ IDEA. User: caocao024 Date: 13-1-15 Time: PM10:03 To 9 | * change this template use File | Settings | File Templates. 10 | */ 11 | public class StaticFactory { 12 | public static void main(String[] args) { 13 | 14 | /** 15 | * static factory 1.initialize object with name "new StaticConsObj()"---->"StaticConsObj.getNameInstance()" 16 | * 2.not required to create a new object each time they're invoked-->instance controlled 17 | */ 18 | StaticConsObj staticConsObj = StaticConsObj.getNameInstance("Tom"); 19 | StaticConsObj staticConsObj1 = StaticConsObj.getNameInstance("Jack"); 20 | System.out.println(staticConsObj.hashCode() == staticConsObj1.hashCode()); 21 | System.out.println(staticConsObj.getName() + staticConsObj1.getName()); 22 | /** 23 | * 3.return an object of any subtype their return type (also con.),see: 24 | * ImmutableList: a.doesn't expose any public or protected cons, it can be 25 | * subclassed within the package while not allowing user to subclass it 26 | * b.return specialized subclass without exposing their types 27 | * c.of() return the singlton instance of EmptyImmutableList , of(E) return RegularImmutableList 28 | */ 29 | ImmutableList immutableList = ImmutableList.of(1, 2, 3, 4); 30 | 31 | /** 32 | * create new object with specifying the parameterized type ,con: 33 | * HashMap maps = new HashMap(); 34 | */ 35 | 36 | HashMap maps = StaticConsObj.newInstance(); 37 | /** 38 | * valueOf---type-conversion e.g. Boolean.valueOf(); 39 | * of---concise alternative to valueOf 40 | * getInstance--returns an instance described by parameters cannot be said to have same value(sole instance) 41 | * newInstance---like getInstance but returned instance is distinct 42 | * getType---like getInstance when factory method is in a different class 43 | * newType---like newInstance 44 | */ 45 | } 46 | } 47 | 48 | class StaticConsObj { 49 | 50 | private String name; 51 | private static final StaticConsObj CONS_OBJ = new StaticConsObj(); 52 | 53 | public static HashMap newInstance() { 54 | return new HashMap(); 55 | } 56 | 57 | public static StaticConsObj getInstance() { 58 | return CONS_OBJ; 59 | } 60 | 61 | public static StaticConsObj getNameInstance(final String name) { 62 | CONS_OBJ.setName(name); 63 | return CONS_OBJ; 64 | } 65 | 66 | public String getName() { 67 | return name; 68 | } 69 | 70 | public void setName(String name) { 71 | this.name = name; 72 | } 73 | 74 | @Override 75 | public String toString() { 76 | return "StaticConsObj{" + "name='" + name + '\'' + '}'; 77 | } 78 | } -------------------------------------------------------------------------------- /src/main/java/com/shawn/guru/ListTest.java: -------------------------------------------------------------------------------- 1 | package com.shawn.guru; 2 | 3 | import java.util.Arrays; 4 | import java.util.List; 5 | import java.util.Map; 6 | 7 | import org.apache.commons.lang.builder.ToStringBuilder; 8 | 9 | import com.google.common.base.CharMatcher; 10 | import com.google.common.collect.ArrayListMultimap; 11 | import com.google.common.collect.Lists; 12 | import com.google.common.collect.Multiset; 13 | import com.google.common.collect.Multisets; 14 | import com.google.common.collect.Sets; 15 | 16 | public class ListTest { 17 | 18 | public static void main(String[] args) { 19 | 20 | 21 | Person p1 = new Person("aaa", "1", "tianji"); 22 | Person p2 = new Person("b", "2", "haha"); 23 | Person p3 = new Person("c", "3", "tianji"); 24 | Person p4 = new Person("d", "4", "dia"); 25 | Person p5 = new Person("e", "5", "haha"); 26 | Person p6 = new Person("f", "6", "dia"); 27 | Person p7 = new Person("g", "7", "tianji"); 28 | Person p8 = new Person("h", "8", "haha"); 29 | List list = Arrays.asList(p1,p2,p3,p4,p5,p6,p7,p8); 30 | List others = Lists.newArrayList(); 31 | List tianjis = Lists.newArrayList(); 32 | for(Person p:list){ 33 | if(p.getFrom().equals("tianji")){ 34 | tianjis.add(p); 35 | }else{ 36 | others.add(p); 37 | } 38 | } 39 | 40 | //List tianjis= map.get("tianji"); 41 | for (Person p: tianjis) { 42 | p.setOthers("tianji"); 43 | } 44 | //List diasList = map.get("dia"); 45 | for (Person p:others) { 46 | p.setOthers("other"); 47 | } 48 | 49 | //List result = Lists.newArrayList(map.values()); 50 | for (Person p: list) { 51 | System.out.println(p.toString()); 52 | } 53 | 54 | System.out.println(CharMatcher.inRange('a', 'z').or(CharMatcher.inRange('A', 'Z')).matchesAllOf("asdasdasd")); 55 | } 56 | 57 | 58 | } 59 | 60 | class Person{ 61 | String name; 62 | String id; 63 | String from; 64 | String others; 65 | public Person(String name, String id, String from) { 66 | this.name = name; 67 | this.id = id; 68 | this.from = from; 69 | } 70 | public String getName() { 71 | return name; 72 | } 73 | public void setName(String name) { 74 | this.name = name; 75 | } 76 | public String getId() { 77 | return id; 78 | } 79 | public void setId(String id) { 80 | this.id = id; 81 | } 82 | public String getFrom() { 83 | return from; 84 | } 85 | public void setFrom(String from) { 86 | this.from = from; 87 | } 88 | public String getOthers() { 89 | return others; 90 | } 91 | public void setOthers(String others) { 92 | this.others = others; 93 | } 94 | 95 | @Override 96 | public String toString() { 97 | return ToStringBuilder.reflectionToString(this); 98 | } 99 | } 100 | -------------------------------------------------------------------------------- /src/main/java/com/shawn/classNInterface/RegexMatchTest.java: -------------------------------------------------------------------------------- 1 | package com.shawn.classNInterface; 2 | 3 | import java.util.HashSet; 4 | import java.util.Iterator; 5 | import java.util.Random; 6 | import java.util.regex.Matcher; 7 | import java.util.regex.Pattern; 8 | 9 | import com.google.common.base.Strings; 10 | import com.google.common.collect.Sets; 11 | 12 | public class RegexMatchTest { 13 | 14 | private static final String EMAILREGEX = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$"; 15 | private static final String NAMEREGEX="[\u4e00-\u9fa5]{2,5}"; 16 | private static final String PSDREGEX="^[\\@A-Za-z0-9\\!\\#\\$\\%\\^\\&\\*\\.\\~]{6,16}$"; 17 | private static final String PSDREGEX2 = "^[_A-Za-z0-9\\!\\#\\$\\%\\^\\&\\*\\.\\~]{6,16}$"; 18 | private static final String GENDERREGEX=""; 19 | //"[1XLn] 9+K>C{3F2;D\6`SZ508v::WV#(R;8vasciiWV7{Kc0.58v::WV#)"; 20 | 21 | public static void main(String[] args) { 22 | /*JobSearchServiceImpl search = new JobSearchServiceImpl(); 23 | SearchCriterionVO searchCriterionVO = new SearchCriterionVO(); 24 | searchCriterionVO.setKeyword("tianji"); 25 | search.search(searchCriterionVO);*/ 26 | /* String s= "PM /n Account Manager"; 27 | 28 | 29 | String LUCENE_ESCAPE_CHARS ="[\\\\+\\-\\!\\(\\)\\:\\^\\]\\{\\}\\~\\*\\?]"; 30 | Pattern LUCENE_PATTERN = Pattern.compile(LUCENE_ESCAPE_CHARS); 31 | String REPLACEMENT_STRING = "\\\\$0"; 32 | LUCENE_PATTERN.matcher(s); 33 | System.out.println(s);*/ 34 | //ids(); 35 | //System.out.println(IsMatch("c.shangfei@gmail.com", EMAILREGEX)); 36 | //System.out.println(IsMatch("928_ooo@gmail.com.cn", EMAILREGEX)); 37 | //System.out.println(IsMatch("!@#$%^", PSDREGEX)); 38 | System.out.println(IsMatch(Strings.nullToEmpty("!@#$%^&*"), PSDREGEX)); 39 | String str = "内蒙古"; 40 | String[] locality = str.split("\\s"); 41 | System.out.println(locality[0]); 42 | } 43 | 44 | private static boolean IsMatch(String string,String pattern) { 45 | try { 46 | Pattern patt = Pattern.compile(pattern); 47 | Matcher matcher = patt.matcher(string); 48 | return matcher.matches(); 49 | } catch (RuntimeException e) { 50 | System.out.println("run error "+ e.toString()); 51 | return false; 52 | } 53 | } 54 | 55 | public static void ids(){ 56 | Integer[] intIds={2519,4221,4230,2902,3757,2470,3070,3301,3155,3114,3300,3232}; 57 | HashSet ids = Sets.newHashSet(); 58 | Random random = new Random(); 59 | while(true){ 60 | ids.add(Math.abs(random.nextInt()%(intIds.length-1))); 61 | if(ids.size()==4){ 62 | break; 63 | } 64 | } 65 | Iterator its = ids.iterator(); 66 | while(its.hasNext()){ 67 | System.out.println(its.next()); 68 | } 69 | Integer[] res = (Integer[])ids.toArray(); 70 | } 71 | } 72 | 73 | 74 | -------------------------------------------------------------------------------- /src/main/java/com/shawn/concurrent/util/ExecutorServer.java: -------------------------------------------------------------------------------- 1 | package com.shawn.concurrent.util; 2 | 3 | 4 | import java.util.Date; 5 | import java.util.Iterator; 6 | import java.util.List; 7 | import java.util.Set; 8 | import java.util.concurrent.ExecutionException; 9 | import java.util.concurrent.Executors; 10 | import java.util.concurrent.Future; 11 | import java.util.concurrent.ThreadPoolExecutor; 12 | import java.util.concurrent.TimeUnit; 13 | import java.util.concurrent.locks.ReentrantLock; 14 | 15 | import com.google.common.collect.Lists; 16 | import com.google.common.collect.Sets; 17 | 18 | 19 | 20 | public class ExecutorServer { 21 | static ReentrantLock lock = new ReentrantLock(); 22 | 23 | public static void main(String[] args) throws InterruptedException, ExecutionException { 24 | Server server = new Server(); 25 | Set sets = Sets.newCopyOnWriteArraySet(); 26 | List futures = Lists.newArrayList(); 27 | for (int i = 0; i < 10; i++) { 28 | Task task = new Task("Task " + i, sets); 29 | futures.add(server.executeTask(task)); 30 | //server.executeTask(task); 31 | } 32 | for (Future future:futures) { 33 | future.get(); 34 | } 35 | server.endServer(); 36 | Iterator iterator = sets.iterator(); 37 | while(iterator.hasNext()){ 38 | System.out.println("set ..." + iterator.next()); 39 | } 40 | 41 | 42 | 43 | } 44 | } 45 | 46 | 47 | 48 | class Server { 49 | private ThreadPoolExecutor executor; 50 | 51 | Server(){ 52 | executor = (ThreadPoolExecutor)Executors.newCachedThreadPool(); 53 | } 54 | 55 | public ThreadPoolExecutor getExecutorInstance(){ 56 | return executor; 57 | } 58 | 59 | public Future executeTask(Task task){ 60 | System.out.println("Server: new task has arrived \n"); 61 | Future future = (Future) executor.submit(task); 62 | System.out.printf("Server:%s Pool Size \n",executor.getPoolSize()); 63 | System.out.printf("Server:%s Active thread \n",executor.getActiveCount()); 64 | System.out.printf("Server:%s Completed Tasks \n",executor.getCompletedTaskCount()); 65 | return future; 66 | } 67 | 68 | 69 | public void endServer(){ 70 | executor.shutdown(); 71 | } 72 | 73 | } 74 | class Task implements Runnable{ 75 | 76 | private Date iniDate; 77 | private String name; 78 | private Set set; 79 | public Task(String name,Set sets) { 80 | iniDate = new Date(); 81 | this.name = name; 82 | this.set = sets; 83 | } 84 | public void runFun(){ 85 | System.out.printf("%s Task %s \n",Thread.currentThread().getName(),iniDate); 86 | } 87 | public void run() { 88 | runFun(); 89 | try { 90 | long duration = (long)(Math.random()*10); 91 | TimeUnit.SECONDS.sleep(duration); 92 | } catch (Exception e) { 93 | e.printStackTrace(); 94 | } 95 | set.add(name); 96 | System.out.printf("%s : Task %s:finish on : %s \n", Thread.currentThread().getName(),name,new Date()); 97 | } 98 | 99 | } -------------------------------------------------------------------------------- /src/main/java/com/shawn/methods/OverloadingTricks.java: -------------------------------------------------------------------------------- 1 | package com.shawn.methods; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Collection; 5 | import java.util.HashSet; 6 | import java.util.List; 7 | import java.util.Map; 8 | import java.util.Set; 9 | import java.util.TreeSet; 10 | /** 11 | * 12 | * @author shawncao 13 | *never to export two overloadings with the same number of parameters 14 | */ 15 | public class OverloadingTricks { 16 | public static void main(String[] args) { 17 | //wineTest(); 18 | classifyTest(); 19 | primitiveAutoBox(); 20 | } 21 | 22 | public static void wineTest(){ 23 | Wine[] wines = {new Wine(),new SparklingWine(),new Champagne()}; 24 | for (int i = 0; i < wines.length; i++) { 25 | System.out.println(wines[i].name()); 26 | } 27 | } 28 | public static void classifyTest() { 29 | Collection[] collections = { new HashSet(), new ArrayList() }; 30 | for (Collection c : collections) { 31 | //System.out.println(CollectionClassifier.classify(c)); 32 | System.out.println(CollectionClassifier.classifyRight(c)); 33 | } 34 | } 35 | 36 | public static void primitiveAutoBox(){ 37 | Set set = new TreeSet(); 38 | List list = new ArrayList(); 39 | 40 | for(int i=-3; i<3;i++){ 41 | set.add(i); 42 | list.add(i); 43 | } 44 | for(int i=-3; i<3;i++){ 45 | set.remove(i); 46 | /** 47 | * list has two remove methods,remove(Object),remove(int index) 48 | */ 49 | //list.remove(i); 50 | list.remove(Integer.valueOf(i)); 51 | } 52 | System.out.println(set+ " " + list); 53 | } 54 | 55 | } 56 | 57 | /** 58 | * classify method is overloaded,choice of which overloading to invoke is made 59 | * at compile time cuz the classify is static,while selection among overridden 60 | * is dynamic.main test ,all these types are the same Collection at compile 61 | * time correct version of overridden method is chosen at runtime 62 | */ 63 | 64 | class CollectionClassifier { 65 | public static String classify(Set set) { 66 | return "Set"; 67 | } 68 | 69 | public static String classify(List list) { 70 | return "List"; 71 | } 72 | 73 | public static String classify(Map map) { 74 | return "Map"; 75 | } 76 | 77 | public static String classify(Collection collection) { 78 | return "Collection"; 79 | } 80 | 81 | public static String classifyRight(Collection collection){ 82 | return collection instanceof Set ? "Set":collection instanceof List?"List" : "Unknown Collection"; 83 | } 84 | } 85 | 86 | class Wine { 87 | String name() { 88 | return "wine"; 89 | } 90 | } 91 | 92 | class SparklingWine extends Wine { 93 | @Override 94 | String name() { 95 | return "Sparkling wine"; 96 | } 97 | } 98 | 99 | class Champagne extends SparklingWine { 100 | @Override 101 | String name() { 102 | return "champagne"; 103 | } 104 | } 105 | -------------------------------------------------------------------------------- /src/main/java/com/shawn/concurrent/divideAndConquer/ComputePrimeNumber.java: -------------------------------------------------------------------------------- 1 | package com.shawn.concurrent.divideAndConquer; 2 | 3 | import java.util.List; 4 | import java.util.concurrent.Callable; 5 | import java.util.concurrent.ExecutionException; 6 | import java.util.concurrent.ExecutorService; 7 | import java.util.concurrent.Executors; 8 | import java.util.concurrent.Future; 9 | import java.util.concurrent.TimeUnit; 10 | 11 | import com.google.common.collect.Lists; 12 | 13 | 14 | public class ComputePrimeNumber { 15 | public static void main(String[] args) { 16 | //new SequentialPrimeFinder().timeAndCompute(10000000); 17 | new ConcurrentPrimeFinder(5, 5).timeAndCompute(10000000); 18 | } 19 | } 20 | 21 | 22 | class ConcurrentPrimeFinder extends AbstractPrimeFinder{ 23 | 24 | private final int poolSize; 25 | private final int numberOfPart; 26 | public ConcurrentPrimeFinder(final int poolSize,final int numberOfPart) { 27 | this.poolSize = poolSize; 28 | this.numberOfPart = numberOfPart; 29 | } 30 | @Override 31 | public int countPrimes(int number) { 32 | int count = 0; 33 | final List> partritons = Lists.newArrayList(); 34 | final int chunksPerPartrition = number / numberOfPart; 35 | for (int i = 0; i < numberOfPart; i++) { 36 | final int lower = (i*chunksPerPartrition) + 1; 37 | final int upper = (i==numberOfPart-1)?number:lower + chunksPerPartrition-1; 38 | partritons.add(new Callable() { 39 | public Integer call(){ 40 | return countPrimeInRange(lower, upper); 41 | } 42 | }); 43 | } 44 | final ExecutorService executor = Executors.newFixedThreadPool(poolSize); 45 | try { 46 | final List> resultsFromPartritions = executor.invokeAll(partritons,1000,TimeUnit.SECONDS); 47 | executor.shutdown(); 48 | for (final Future result: resultsFromPartritions) { 49 | count+=result.get(); 50 | } 51 | } catch (InterruptedException e) { 52 | e.printStackTrace(); 53 | } catch (ExecutionException e) { 54 | e.printStackTrace(); 55 | } 56 | return count; 57 | } 58 | 59 | } 60 | 61 | class SequentialPrimeFinder extends AbstractPrimeFinder{ 62 | 63 | @Override 64 | public int countPrimes(int number) { 65 | return countPrimeInRange(1, number); 66 | } 67 | 68 | } 69 | abstract class AbstractPrimeFinder{ 70 | 71 | public boolean isPrime(final int number){ 72 | if(number <= 1) 73 | return false; 74 | for(int i=2;i lines = Files.readAllLines(path,StandardCharsets.UTF_8); 54 | System.out.println(Joiner.on(";").join(lines)); 55 | 56 | } catch (IOException e) { 57 | e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. 58 | } 59 | } 60 | 61 | public static void watchService(){ 62 | try { 63 | WatchService watcher = FileSystems.getDefault().newWatchService(); 64 | WatchKey watchKey= Paths.get("/Users/caocao024/Desktop").register(watcher,StandardWatchEventKinds.ENTRY_MODIFY); 65 | while(true) { 66 | //watchKey = watcher.take(); 67 | for(WatchEvent event:watcher.poll(10, TimeUnit.MILLISECONDS).pollEvents()){ 68 | if(event.kind() == StandardWatchEventKinds.ENTRY_MODIFY){ 69 | System.out.println("====" + event.context() + " | " + event.count() ); 70 | } 71 | } 72 | watchKey.reset(); 73 | } 74 | } catch (IOException | InterruptedException e) { 75 | e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. 76 | } 77 | } 78 | 79 | public static void seekByChannel(){ 80 | ByteBuffer buffer = ByteBuffer.allocate(1024); 81 | try { 82 | FileChannel channel = FileChannel.open(Paths.get("/var/log/daily.out"),StandardOpenOption.READ); 83 | channel.read(buffer,channel.size()-1024); 84 | System.out.println("---"+(char)buffer.get()); 85 | } catch (IOException e) { 86 | e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. 87 | } 88 | } 89 | } 90 | -------------------------------------------------------------------------------- /src/test/java/com/shawn/guava/CacheTest.java: -------------------------------------------------------------------------------- 1 | package com.shawn.guava; 2 | 3 | import com.google.common.cache.*; 4 | import com.google.common.collect.ImmutableMap; 5 | import org.junit.Before; 6 | import org.junit.Test; 7 | 8 | import java.util.concurrent.Callable; 9 | import java.util.concurrent.ExecutionException; 10 | import java.util.concurrent.TimeUnit; 11 | 12 | import static org.junit.Assert.assertTrue; 13 | 14 | /** 15 | * User: Shawn cao 16 | * Date: 14-6-9 17 | * Time: AM10:05 18 | */ 19 | public class CacheTest { 20 | 21 | 22 | 23 | @Test 24 | public void testCacheByCacheLoader() throws Exception{ 25 | LoadingCache cache = CacheBuilder.newBuilder().maximumSize(10).build(new CacheLoader() { 26 | @Override 27 | public String load(String s) throws Exception { 28 | return maps.get(s); 29 | } 30 | }); 31 | assertTrue(cache.get("a").equals("aaa")); 32 | assertTrue(cache.size() == 1); 33 | assertTrue(cache.get("b").equals("bbb")); 34 | assertTrue(cache.size() == 2); 35 | } 36 | 37 | @Test 38 | public void testCacheByCallable() throws Exception{ 39 | Cache cache = CacheBuilder.newBuilder().build(); 40 | String result = cache.get("Herry",new Callable() { 41 | @Override 42 | public String call() throws Exception { 43 | return "Hello Herry !"; 44 | } 45 | }); 46 | assertTrue(result.equals("Hello Herry !")); 47 | 48 | result = cache.get("Jerry",new Callable() { 49 | @Override 50 | public String call() throws Exception { 51 | return "Goodbye Herry, welcome Jerry !"; 52 | } 53 | }); 54 | assertTrue(result.equals("Goodbye Herry, welcome Jerry !")); 55 | } 56 | 57 | 58 | static ImmutableMap maps = ImmutableMap.of("a","aaa","b","bbb"); 59 | 60 | 61 | private LoadingCache cached(CacheLoader cacheLoader) { 62 | LoadingCache cache = CacheBuilder 63 | .newBuilder() 64 | .maximumSize(2) 65 | .weakKeys() 66 | .softValues() 67 | .refreshAfterWrite(120, TimeUnit.SECONDS) 68 | .expireAfterWrite(10, TimeUnit.MINUTES) 69 | .removalListener(new RemovalListener(){ 70 | @Override 71 | public void onRemoval(RemovalNotification rn) { 72 | System.out.println(rn.getKey()+" is removed"); 73 | 74 | }}) 75 | .build(cacheLoader); 76 | return cache; 77 | } 78 | 79 | private LoadingCache commonCache(final String key) { 80 | return cached(new CacheLoader() { 81 | @Override 82 | public String load(String s) throws Exception { 83 | return "Hello "+s; 84 | } 85 | }); 86 | } 87 | 88 | @Test 89 | public void testLoadingCache() throws ExecutionException { 90 | LoadingCache commonCache = commonCache("herry"); 91 | assertTrue("Hello herry".equals(commonCache.get("herry"))); 92 | assertTrue("Hello Toby".equals(commonCache.get("Toby"))); 93 | assertTrue("Hello Howie".equals(commonCache.get("Howie"))); 94 | commonCache.invalidate("herry"); 95 | commonCache.invalidateAll(); 96 | } 97 | } 98 | -------------------------------------------------------------------------------- /src/main/java/com/shawn/nio/EcryptionTest.java: -------------------------------------------------------------------------------- 1 | package com.shawn.nio; 2 | 3 | import java.security.spec.AlgorithmParameterSpec; 4 | import java.security.spec.KeySpec; 5 | 6 | import javax.crypto.Cipher; 7 | import javax.crypto.SecretKey; 8 | import javax.crypto.SecretKeyFactory; 9 | import javax.crypto.spec.PBEKeySpec; 10 | import javax.crypto.spec.PBEParameterSpec; 11 | 12 | import org.apache.commons.codec.binary.Base64; 13 | 14 | public class EcryptionTest { 15 | 16 | public static void main(String[] args) { 17 | //String url = "311:100"; 18 | System.out.println(encode("705:8659122")); 19 | /*long start = System.currentTimeMillis(); 20 | for(int i=80000;i<200000;i++){ 21 | String url = "311:"+i; 22 | //String encoded = encode(url); 23 | String encoded = Base64.encodeBase64URLSafeString(url.getBytes()); 24 | System.out.println("encode: " +url+" | "+ encoded); 25 | } 26 | System.out.println("--------------------------------"); 27 | System.out.println("total: " + (System.currentTimeMillis() - start));*/ 28 | 29 | /*String decoded = decode(encoded); 30 | System.out.println("decoded: " + decoded);*/ 31 | } 32 | 33 | // define random salt 34 | private static final byte[] SALT = { (byte) 0x21, (byte) 0x21, (byte) 0xF0, (byte) 0x55, (byte) 0xC3, (byte) 0x9F, (byte) 0x5A, (byte) 0x75 }; 35 | 36 | private final static int ITERATION_COUNT = 31; 37 | 38 | public static String encode(String input) { 39 | if (input == null) { 40 | throw new IllegalArgumentException(); 41 | } 42 | try { 43 | 44 | KeySpec keySpec = new PBEKeySpec(null, SALT, ITERATION_COUNT); 45 | AlgorithmParameterSpec paramSpec = new PBEParameterSpec(SALT, ITERATION_COUNT); 46 | 47 | SecretKey key = SecretKeyFactory.getInstance("PBEWithMD5AndDES").generateSecret(keySpec); 48 | 49 | Cipher ecipher = Cipher.getInstance(key.getAlgorithm()); 50 | ecipher.init(Cipher.ENCRYPT_MODE, key, paramSpec); 51 | 52 | byte[] enc = ecipher.doFinal(input.getBytes()); 53 | 54 | String res = new String(Base64.encodeBase64(enc)); 55 | // escapes for url 56 | res = res.replace('+', '-').replace('/', '_').replace("%", "%25").replace("\n", "%0A"); 57 | 58 | return res; 59 | 60 | } catch (Exception e) { 61 | } 62 | 63 | return ""; 64 | 65 | } 66 | 67 | public static String decode(String token) { 68 | if (token == null) { 69 | return null; 70 | } 71 | try { 72 | 73 | String input = token.replace("%0A", "\n").replace("%25", "%").replace('_', '/').replace('-', '+'); 74 | 75 | byte[] dec = Base64.decodeBase64(input.getBytes()); 76 | 77 | KeySpec keySpec = new PBEKeySpec(null, SALT, ITERATION_COUNT); 78 | AlgorithmParameterSpec paramSpec = new PBEParameterSpec(SALT, ITERATION_COUNT); 79 | 80 | SecretKey key = SecretKeyFactory.getInstance("PBEWithMD5AndDES").generateSecret(keySpec); 81 | 82 | Cipher dcipher = Cipher.getInstance(key.getAlgorithm()); 83 | dcipher.init(Cipher.DECRYPT_MODE, key, paramSpec); 84 | 85 | byte[] decoded = dcipher.doFinal(dec); 86 | 87 | String result = new String(decoded); 88 | return result; 89 | 90 | } catch (Exception e) { 91 | //e.printStackTrace(); 92 | } 93 | 94 | return null; 95 | } 96 | 97 | } 98 | -------------------------------------------------------------------------------- /src/main/java/com/shawn/concurrent/basic/BasicThreadTest.java: -------------------------------------------------------------------------------- 1 | package com.shawn.concurrent.basic; 2 | 3 | import java.io.FileWriter; 4 | import java.io.IOException; 5 | import java.io.PrintStream; 6 | import java.io.PrintWriter; 7 | import java.lang.Thread.State; 8 | 9 | 10 | 11 | public class BasicThreadTest { 12 | 13 | public static void main(String[] args) { 14 | //RunSimpleThread(); 15 | RunWithStateMonitoring(); 16 | 17 | } 18 | 19 | public static void RunSimpleThread(){ 20 | for (int i = 0; i < 10; i++) { 21 | Thread d= new Thread(new Calculator(i)); 22 | d.start(); 23 | } 24 | } 25 | 26 | public static void RunWithStateMonitoring() { 27 | Thread threads[] = new Thread[10]; 28 | Thread.State status[] = new Thread.State[10]; 29 | for (int i = 0; i < threads.length; i++) { 30 | threads[i] = new Thread(new Calculator(i)); 31 | if((i%2) == 0){ 32 | threads[i].setPriority(Thread.MAX_PRIORITY); 33 | }else { 34 | threads[i].setPriority(Thread.MIN_PRIORITY); 35 | } 36 | threads[i].setName("T " + i); 37 | } 38 | printThreadInfo(threads,status); 39 | } 40 | 41 | private static void printThreadInfo(Thread[] threads,Thread.State[] status){ 42 | //FileWriter fileWriter; 43 | //PrintWriter pw; 44 | 45 | try (FileWriter fileWriter = new FileWriter("/Users/caocao024/log.txt");PrintWriter pw= new PrintWriter(fileWriter);){ 46 | for (int i = 0; i < 10; i++) { 47 | pw.println("Main: Status of Thread" + i + ":"+threads[i].getState()); 48 | status[i] = threads[i].getState(); 49 | } 50 | for (int i = 0; i < 10; i++) { 51 | threads[i].start(); 52 | } 53 | //record thread state until all threads terminates 54 | boolean finish = false; 55 | while (!finish) { 56 | for(int i=0; i<10;i++){ 57 | if(threads[i].getState()!=status[i]){ 58 | writeThreadInfo(pw,threads[i],status[i]); 59 | status[i] = threads[i].getState(); 60 | } 61 | } 62 | finish = true; 63 | for (int i = 0; i < 10; i++) { 64 | finish = finish&&(threads[i].getState() == State.TERMINATED); 65 | } 66 | } 67 | pw.close(); 68 | } catch (IOException e) { 69 | e.printStackTrace(); 70 | } 71 | } 72 | 73 | private static void writeThreadInfo(PrintWriter pw,Thread t , State state){ 74 | //pw.printf("Main: Id %d - %s\n",t.getId(),t.getName()); 75 | pw.printf("Main: ------- %s\n",t.getName()); 76 | pw.printf("Main:Priority: %d \n",t.getPriority()); 77 | pw.printf("Main: Old State: %s\n",state); 78 | pw.printf("Main:New State: %s \n",t.getState()); 79 | pw.printf("Main:**************************************************\n"); 80 | } 81 | } 82 | 83 | 84 | //class Calculator implements Runnable{ 85 | class Calculator extends Thread{ 86 | private int number; 87 | public Calculator(int number) { 88 | this.number = number; 89 | } 90 | 91 | public void run() { 92 | for (int i = 0; i < 10; i++) { 93 | System.out.printf("%s: %d*%d = %d \n",Thread.currentThread().getName(),number,i,i*number); 94 | } 95 | } 96 | 97 | } -------------------------------------------------------------------------------- /src/main/java/com/shawn/concurrent/basic/ReentrantLockTest.java: -------------------------------------------------------------------------------- 1 | package com.shawn.concurrent.basic; 2 | 3 | public class ReentrantLockTest { 4 | 5 | static ShareObject so; 6 | 7 | public static void main(String[] args) { 8 | //final Lock lock = new SimpleLock(); 9 | 10 | final Lock lock= new ReentrantLock(); 11 | Thread[] threads = new Thread[5]; 12 | so = new ShareObject(lock); 13 | for (int i = 0; i < threads.length; i++) { 14 | threads[i] = new Thread(new Runnable() { 15 | public void run() { 16 | try { 17 | System.out.printf("%s require the lock A \n", Thread.currentThread().getName()); 18 | lock.lock(); 19 | System.out.printf("%s got the lock A \n", Thread.currentThread().getName()); 20 | so.a(); 21 | } catch (Exception e) { 22 | e.printStackTrace(); 23 | } finally { 24 | System.out.printf("%s release the lock A \n", Thread.currentThread().getName()); 25 | lock.unlock(); 26 | } 27 | } 28 | }, i + ""); 29 | } 30 | for (int i = 0; i < threads.length; i++) { 31 | threads[i].start(); 32 | } 33 | } 34 | } 35 | 36 | class ShareObject { 37 | private Lock lock; 38 | 39 | public ShareObject(Lock lock) { 40 | this.lock = lock; 41 | } 42 | 43 | public void a() { 44 | try { 45 | System.out.printf("%s require the lock B \n", Thread.currentThread().getName()); 46 | lock.lock(); 47 | System.out.printf("%s got the lock b \n", Thread.currentThread().getName()); 48 | b(); 49 | 50 | } catch (InterruptedException e) { 51 | e.printStackTrace(); 52 | } finally { 53 | System.out.printf("%s release the lock B \n", Thread.currentThread().getName()); 54 | lock.unlock(); 55 | } 56 | 57 | } 58 | 59 | public void b() { 60 | 61 | } 62 | } 63 | 64 | class ReentrantLock implements Lock { 65 | Thread lockedBy = null; 66 | boolean isLocked = false; 67 | int count = 0; 68 | 69 | public synchronized void lock() throws InterruptedException { 70 | while (count != 0 && lockedBy != Thread.currentThread()) { 71 | wait(); 72 | } 73 | isLocked = true; 74 | lockedBy = Thread.currentThread(); 75 | count++; 76 | } 77 | 78 | public synchronized void unlock() { 79 | if (lockedBy == Thread.currentThread()) { 80 | count--; 81 | if (count == 0) { 82 | isLocked = false; 83 | notify(); 84 | } 85 | } 86 | } 87 | 88 | } 89 | 90 | class SimpleLock implements Lock { 91 | Thread currentThread = null; 92 | boolean isLock = false; 93 | 94 | public synchronized void lock() throws InterruptedException { 95 | while (isLock) { 96 | wait(); 97 | } 98 | currentThread = Thread.currentThread(); 99 | isLock = true; 100 | } 101 | 102 | public synchronized void unlock() { 103 | if (currentThread == Thread.currentThread()) { 104 | isLock = false; 105 | notifyAll(); 106 | } 107 | } 108 | 109 | } 110 | 111 | interface Lock { 112 | public void lock() throws InterruptedException; 113 | 114 | public void unlock(); 115 | } -------------------------------------------------------------------------------- /src/main/java/com/shawn/enumNAnnotation/ReplaceConstantTest.java: -------------------------------------------------------------------------------- 1 | package com.shawn.enumNAnnotation; 2 | 3 | import java.util.HashMap; 4 | import java.util.Map; 5 | 6 | 7 | /** 8 | * enum: classes export one instance for each enumeration constant via static final 9 | * instance-controlled,singletons 10 | * 11 | */ 12 | public class ReplaceConstantTest { 13 | 14 | public static void main(String[] args) { 15 | opSymbol(); 16 | } 17 | 18 | static void opSymbol(){ 19 | for(Operation op:Operation.values()){ 20 | //System.out.printf("op on %s is %s%n",op,op.show()); 21 | } 22 | } 23 | static void opTest(){ 24 | //System.out.println(Operation.PLUS.apply(1.0, 2.0)); 25 | for(Operation op: Operation.values()){ 26 | System.out.printf("op on %s is %f%n",op,op.apply(1.0, 2.0)); 27 | } 28 | } 29 | 30 | static void conTest(){ 31 | double marsWeight=2091923; 32 | double mass = marsWeight/Plant.MARS.surfaceGravity(); 33 | for(Plant p: Plant.values()){ 34 | System.out.printf("Weight on %s is %f%n",p,p.surfaceWeight(mass)); 35 | } 36 | } 37 | } 38 | /* 39 | * 1.to associate data with enum constants , declare instance fields and write a constructor 40 | * that takes the data and stores it in the fields 41 | * 2. immutable,all fields should be final 42 | * 43 | */ 44 | enum Plant{ 45 | VENUS(4.869e+24,6.052e6), 46 | MARS(6.419e+23,3.393e6), 47 | NEPTUNE(1.024e+26,2.477e7); 48 | 49 | private final double mass; 50 | private final double radius; 51 | private final double surfaceGravity; 52 | 53 | private static final double G = 6.67300E-11; 54 | private Plant(double mass,double radius){ 55 | this.mass = mass; 56 | this.radius = radius; 57 | surfaceGravity = G*mass/(radius*radius); 58 | } 59 | 60 | public double mass(){ 61 | return mass; 62 | } 63 | 64 | public double radius(){ 65 | return radius; 66 | } 67 | public double surfaceGravity(){ 68 | return surfaceGravity; 69 | } 70 | 71 | public double surfaceWeight(double mass){ 72 | return mass*surfaceGravity; 73 | } 74 | } 75 | 76 | 77 | interface Show{ 78 | public String show(); 79 | } 80 | 81 | enum Operation implements Show{ 82 | PLUS("+"){ 83 | @Override 84 | double apply(double x, double y) { 85 | return x+y; 86 | } 87 | public String show() { 88 | return this.getSymbol(); 89 | } 90 | }, 91 | MINUS("-"){ 92 | @Override 93 | double apply(double x, double y) { 94 | return x-y; 95 | } 96 | 97 | public String show() { 98 | return this.getSymbol(); 99 | } 100 | }; 101 | 102 | private final String symbol; 103 | private Operation(String symbol) { 104 | this.symbol = symbol; 105 | } 106 | 107 | public String getSymbol(){ 108 | return this.symbol; 109 | } 110 | //abstract method to implement in each Operation 111 | abstract double apply(double x, double y); 112 | 113 | //using string to get Label 114 | public static final Map StringToEnum = new HashMap(); 115 | static{ 116 | for (Operation op:values()) { 117 | StringToEnum.put(op.toString(), op); 118 | } 119 | } 120 | public static Operation getOperation(String symbol){ 121 | return StringToEnum.get(symbol); 122 | } 123 | } 124 | 125 | -------------------------------------------------------------------------------- /src/main/java/com/shawn/nio/JarFileTest.java: -------------------------------------------------------------------------------- 1 | package com.shawn.nio; 2 | 3 | import java.io.FileNotFoundException; 4 | import java.io.FileOutputStream; 5 | import java.io.IOException; 6 | import java.util.Enumeration; 7 | import java.util.jar.Attributes; 8 | import java.util.jar.JarEntry; 9 | import java.util.jar.JarFile; 10 | import java.util.jar.Pack200; 11 | import java.util.jar.Pack200.Packer; 12 | import java.util.zip.ZipEntry; 13 | 14 | import org.joda.time.DateTime; 15 | 16 | import com.google.common.base.Strings; 17 | 18 | public class JarFileTest { 19 | 20 | public static void main(String[] args) throws IOException { 21 | //jarLister("/home/shawncao/.m2/repository/joda-time/joda-time/2.3/joda-time-2.3-sources.jar"); 22 | packClass("/home/shawncao/workspace/Test/src"); 23 | } 24 | 25 | 26 | public static void jarLister(String filename) throws IOException{ 27 | JarFile jarFile = new JarFile(filename); 28 | Enumeration enumeration = jarFile.entries(); 29 | while (enumeration.hasMoreElements()) { 30 | JarEntry jarEntry = (JarEntry) enumeration.nextElement(); 31 | String name = jarEntry.getName(); 32 | DateTime dateTime = new DateTime(jarEntry.getTime()); 33 | long size = jarEntry.getSize(); 34 | long compressSize = jarEntry.getCompressedSize(); 35 | long crc = jarEntry.getCrc(); 36 | int method = jarEntry.getMethod(); 37 | String comment = jarEntry.getComment(); 38 | switch (method) { 39 | case ZipEntry.STORED: 40 | System.out.println(name + " was stored at " + dateTime.toString("yyyy-MM-dd HH:mm:ss") + " with a size of " + size+ " bytes"); 41 | break; 42 | case ZipEntry.DEFLATED: 43 | System.out.println(name + " was deflated at " + dateTime.toString("yyyy-MM-dd HH:mm:ss") +"from " + size + " bytes to " 44 | + compressSize + " bytes, a savings of " 45 | + (100.0 - 100.0*compressSize/size) + "%"); 46 | break; 47 | default: 48 | System.out.println(name + " was compressed using an unrecognized method at " + dateTime.toString("yyyy-MM-dd HH:mm:ss") 49 | +"from " + size + " bytes to " 50 | + compressSize + " bytes, a savings of " 51 | + (100.0 - 100.0*compressSize/size) + "%"); 52 | break; 53 | } 54 | System.out.println("Its CRC is " + crc); 55 | if (!Strings.isNullOrEmpty(comment)) { 56 | System.out.println(comment); 57 | } 58 | if (jarEntry.isDirectory( )) { 59 | System.out.println(name + " is a directory"); 60 | } 61 | Attributes a = jarEntry.getAttributes( ); 62 | if (a != null) { 63 | Object[] nameValuePairs = a.entrySet().toArray( ); 64 | for (int j = 0; j < nameValuePairs.length; j++) { 65 | System.out.println(nameValuePairs[j]); 66 | } 67 | } 68 | } 69 | jarFile.close(); 70 | } 71 | 72 | public static void packClass(String filename) throws FileNotFoundException, IOException{ 73 | Packer packer = Pack200.newPacker(); 74 | FileOutputStream fos = null; 75 | try { 76 | 77 | packer.pack(new JarFile(filename), fos =new FileOutputStream(filename+".jar")); 78 | }finally{ 79 | if(fos!=null) fos.close(); 80 | } 81 | 82 | 83 | } 84 | } 85 | -------------------------------------------------------------------------------- /src/main/java/com/shawn/concurrent/basic/BackwardThread.java: -------------------------------------------------------------------------------- 1 | package com.shawn.concurrent.basic; 2 | 3 | import java.util.concurrent.TimeUnit; 4 | import java.util.concurrent.locks.Condition; 5 | import java.util.concurrent.locks.ReentrantLock; 6 | 7 | public class BackwardThread { 8 | 9 | public static void main(String[] args) throws InterruptedException { 10 | //runBySync(); 11 | runByReentrantLock(); 12 | } 13 | 14 | static SharedObject so = new SharedObject(); 15 | static void runBySync(){ 16 | Thread[] threads = new Thread[10]; 17 | for (int i = 0; i < threads.length; i++) { 18 | threads[i] = new ThreadSync(i,so); 19 | threads[i].start(); 20 | } 21 | 22 | } 23 | static void runByReentrantLock(){ 24 | Thread[] threads = new Thread[10]; 25 | Doc doc = new Doc(); 26 | for( int i=0; i< threads.length; i++){ 27 | threads[i] = new Thread(new DocPrint(i, doc),i+""); 28 | threads[i].start(); 29 | //threads[i]. 30 | } 31 | } 32 | } 33 | 34 | class ThreadSync extends Thread{ 35 | SharedObject sharedObject; 36 | int num; 37 | public ThreadSync(int i,SharedObject sharedObject) { 38 | this.sharedObject =sharedObject; 39 | num = i; 40 | } 41 | 42 | @Override 43 | public void run() { 44 | sharedObject.printSelf(num); 45 | } 46 | } 47 | 48 | class SharedObject { 49 | 50 | private Integer numberOfThreads = 10; 51 | //private final Object mutex = new Object(); 52 | public void printSelf(int num){ 53 | /*try { 54 | TimeUnit.SECONDS.sleep(1); 55 | System.out.println("in sleep"); 56 | } catch (InterruptedException e) { 57 | e.printStackTrace(); 58 | }*/ 59 | //System.out.println(this.toString()); 60 | try { 61 | TimeUnit.MILLISECONDS.sleep(500); 62 | System.out.println("sleep:" +Thread.currentThread().getName()); 63 | } catch (InterruptedException e1) { 64 | e1.printStackTrace(); 65 | } 66 | synchronized (this) { 67 | while((num+1) != numberOfThreads){ 68 | try { 69 | //System.out.println("before wait: " + Thread.currentThread().getName()); 70 | wait(); 71 | //System.out.println("after wait: " + Thread.currentThread().getName()); 72 | } catch (InterruptedException e) { 73 | e.printStackTrace(); 74 | } 75 | } 76 | System.out.println( num + " "+Thread.currentThread().getName()); 77 | numberOfThreads--; 78 | notifyAll(); 79 | } 80 | } 81 | } 82 | 83 | 84 | class DocPrint implements Runnable{ 85 | private Doc doc; 86 | private int id; 87 | public DocPrint(int id,Doc doc) { 88 | this.id = id; 89 | this.doc = doc; 90 | } 91 | public void run() { 92 | doc.printSelf(id); 93 | } 94 | 95 | } 96 | class Doc { 97 | private Condition number; 98 | private ReentrantLock lock; 99 | private int numOfThread = 10; 100 | 101 | public Doc() { 102 | lock = new ReentrantLock(); 103 | number = lock.newCondition(); 104 | } 105 | 106 | public void printSelf(int id) { 107 | lock.lock(); 108 | try { 109 | while(id+1 != numOfThread) { 110 | //System.out.printf("%s is waiting...\n",Thread.currentThread().getName()); 111 | number.await(); 112 | } 113 | System.out.println( id + " "+Thread.currentThread().getName()); 114 | numOfThread--; 115 | number.signalAll(); 116 | } catch (InterruptedException e) { 117 | Thread.interrupted(); 118 | }finally{ 119 | lock.unlock(); 120 | } 121 | } 122 | } 123 | --------------------------------------------------------------------------------