diff --git a/akka/src/main/java/actors/props/DemoActor.java b/akka/src/main/java/actors/props/DemoActor.java index 1fea425..8a015ef 100644 --- a/akka/src/main/java/actors/props/DemoActor.java +++ b/akka/src/main/java/actors/props/DemoActor.java @@ -14,7 +14,6 @@ public class DemoActor extends UntypedActor { public static Props props(final int magicNumber) { return Props.create(new Creator() { private static final long serialVersionUID = 1L; - @Override public DemoActor create() { return new DemoActor(magicNumber); diff --git a/commons-io/pom.xml b/commons-io/pom.xml new file mode 100644 index 0000000..cec9192 --- /dev/null +++ b/commons-io/pom.xml @@ -0,0 +1,22 @@ + + + + tutorial + me.zzw.app + 1.0-SNAPSHOT + + 4.0.0 + + commons-io + + + commons-io + commons-io + 2.5 + + + + + \ No newline at end of file diff --git a/concurrent/concurrent.iml b/concurrent/concurrent.iml index d734bf0..c40574c 100644 --- a/concurrent/concurrent.iml +++ b/concurrent/concurrent.iml @@ -4,6 +4,8 @@ + + diff --git a/concurrent/src/main/me.zzw.app.concurrent/IAtomicInteger.java b/concurrent/src/main/me.zzw.app.concurrent/IAtomicInteger.java new file mode 100644 index 0000000..b296e94 --- /dev/null +++ b/concurrent/src/main/me.zzw.app.concurrent/IAtomicInteger.java @@ -0,0 +1,25 @@ +package me.zzw.app.concurrent; + +import java.util.concurrent.*; +import java.util.concurrent.atomic.AtomicInteger; + +/** + * Created by infosea on 2016-09-12. + */ +public class IAtomicInteger { + public static void main(String[] args) { + AtomicInteger i = new AtomicInteger(); + + Executor executor = new ThreadPoolExecutor(3, 5, 100, TimeUnit.SECONDS, new LinkedBlockingDeque()); + for (int j = 0; j < 100; j++) { + executor.execute(new Runnable() { + @Override + public void run() { +// System.out.println(i.getAndIncrement()); + System.out.println(i.getAndIncrement()); + } + }); + } + + } +} diff --git a/concurrent/src/main/me.zzw.app.concurrent/TAbstractExecutorService.java b/concurrent/src/main/me.zzw.app.concurrent/TAbstractExecutorService.java new file mode 100644 index 0000000..897bd89 --- /dev/null +++ b/concurrent/src/main/me.zzw.app.concurrent/TAbstractExecutorService.java @@ -0,0 +1,63 @@ +package me.zzw.app.concurrent; + +import jdk.nashorn.internal.codegen.CompilerConstants; + +import java.util.concurrent.*; + +/** + * Created by infosea on 2016-09-12. + */ + + class CustomThreadPoolExecutor extends ThreadPoolExecutor { +// private Callable c; + private Runnable r; + + public CustomThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue workQueue) { + super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue); + } + + static class CustomTask implements RunnableFuture { + + @Override + public void run() { + + } + + @Override + public boolean cancel(boolean mayInterruptIfRunning) { + return false; + } + + @Override + public boolean isCancelled() { + return false; + } + + @Override + public boolean isDone() { + return false; + } + + @Override + public V get() throws InterruptedException, ExecutionException { + return null; + } + + @Override + public V get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { + return null; + } + } + +// protected RunnableFuture newTaskFor(Callable c) { +// return new CustomTask(c); +// } +// protected RunnableFuture newTaskFor(Runnable r, V v) { +// return new CustomTask(r, v); +// } + // ... add constructors, etc. + + +} +public class TAbstractExecutorService { +} diff --git a/concurrent/src/main/me.zzw.app.concurrent/TCallable.java b/concurrent/src/main/me.zzw.app.concurrent/TCallable.java new file mode 100644 index 0000000..ed004f3 --- /dev/null +++ b/concurrent/src/main/me.zzw.app.concurrent/TCallable.java @@ -0,0 +1,25 @@ +package me.zzw.app.concurrent; + +import java.util.concurrent.Callable; + +/** + * Created by infosea on 2016-09-12. + */ +public class TCallable implements Callable { + private int i, j = 0; + + public TCallable(int i, int j) { + this.i = i; + this.j = j; + } + + @Override + public Integer call() throws Exception { + return i + j; + } + + public static void main(String[] args) throws Exception { + TCallable callable = new TCallable(2,3); + System.out.println( callable.call()); + } +} diff --git a/concurrent/src/main/me.zzw.app.concurrent/TCountedCompleter.java b/concurrent/src/main/me.zzw.app.concurrent/TCountedCompleter.java new file mode 100644 index 0000000..c933bed --- /dev/null +++ b/concurrent/src/main/me.zzw.app.concurrent/TCountedCompleter.java @@ -0,0 +1,204 @@ +package me.zzw.app.concurrent; + +import java.util.concurrent.CountedCompleter; +import java.util.concurrent.atomic.AtomicReference; + +/** + * Created by infosea on 2016-09-09. + */ +class MyOperation { + void apply(E e) { + System.out.println(e); + } +} + +class ForEach extends CountedCompleter { + + public static void forEach(E[] array, MyOperation op) { + new ForEach(null, array, op, 0, array.length).invoke(); + } + + final E[] array; final MyOperation op; final int lo, hi; + ForEach(CountedCompleter p, E[] array, MyOperation op, int lo, int hi){ + super(p); + this.array = array; + this.op = op; + this.lo = lo; + this.hi = hi; + } + + @Override + public void compute() { + if(hi -lo >=2 ){ + int mid = (lo + hi) >>> 1; + setPendingCount(2); // must set pending count before fork + new ForEach(this, array, op, mid, hi).fork(); // right child; + new ForEach(this, array, op, lo, mid).fork(); // left child + }else if (hi > lo) + op.apply(array[lo]); + tryComplete(); + } +} + +class ForEach2 extends CountedCompleter{ + + public static void forEach(E[] array, MyOperation op) { + new ForEach(null, array, op, 0, array.length).invoke(); + } + + final E[] array; final MyOperation op; final int lo, hi; + ForEach2(CountedCompleter p, E[] array, MyOperation op, int lo, int hi){ + super(p); + this.array = array; + this.op = op; + this.lo = lo; + this.hi = hi; + } + + public void compute() { // version 2 + if (hi - lo >= 2) { + int mid = (lo + hi) >>> 1; + setPendingCount(1); // only one pending + new ForEach2(this, array, op, mid, hi).fork(); // right child + new ForEach2(this, array, op, lo, mid).compute(); // direct invoke + } else { + if (hi > lo) + op.apply(array[lo]); + tryComplete(); + } + } +} + +class ForEach3 extends CountedCompleter { + + public static void forEach(E[] array, MyOperation op) { + new ForEach3(null, array, op, 0, array.length).invoke(); + } + + final E[] array; + final MyOperation op; + final int lo, hi; + + ForEach3(CountedCompleter p, E[] array, MyOperation op, int lo, int hi) { + super(p); + this.array = array; + this.op = op; + this.lo = lo; + this.hi = hi; + } + + public void compute() { // version 3 + int l = lo, h = hi; + while (h - l >= 2) { + int mid = (l + h) >>> 1; + addToPendingCount(1); + new ForEach3(this, array, op, mid, h).fork(); // right child + h = mid; + } + if (h > l) + op.apply(array[l]); + propagateCompletion(); + } +} + +class Searcher extends CountedCompleter { + + final E[] array; final AtomicReference result; final int lo, hi; + + Searcher(CountedCompleter p, E[] array, AtomicReference result, int lo, int hi) { + super(p); + this.array = array; this.result = result; this.lo = lo; this.hi = hi; + } + + public E getRawResult() { return result.get(); } + + public void compute() { // similar to ForEach version 3 + int l = lo, h = hi; + while (result.get() == null && h >= l) { + if (h - l >= 2) { + int mid = (l + h) >>> 1; + addToPendingCount(1); + new Searcher(this, array, result, mid, h).fork(); + h = mid; + } + else { + E x = array[l]; + if (matches(x) && result.compareAndSet(null, x)) + quietlyCompleteRoot(); // root task is now joinable + break; + } + } + tryComplete(); // normally complete whether or not found + } + + boolean matches(E e) { + return true; + } // return true if found + + + public static E search(E[] array) { + return new Searcher(null, array, new AtomicReference(), 0, array.length).invoke(); + } + +} + +class MyMapper { E apply(E v) { return v; } } +class MyReducer { E apply(E x, E y) { return x; } } +class MapReducer extends CountedCompleter { + final E[] array; final MyMapper mapper; + final MyReducer reducer; final int lo, hi; + MapReducer sibling; + E result; + MapReducer(CountedCompleter p, E[] array, MyMapper mapper, + MyReducer reducer, int lo, int hi) { + super(p); + this.array = array; this.mapper = mapper; + this.reducer = reducer; this.lo = lo; this.hi = hi; + } + public void compute() { + if (hi - lo >= 2) { + int mid = (lo + hi) >>> 1; + MapReducer left = new MapReducer(this, array, mapper, reducer, lo, mid); + MapReducer right = new MapReducer(this, array, mapper, reducer, mid, hi); + left.sibling = right; + right.sibling = left; + setPendingCount(1); // only right is pending + right.fork(); + left.compute(); // directly execute left + } + else { + if (hi > lo) + result = mapper.apply(array[lo]); + tryComplete(); + } + } + public void onCompletion(CountedCompleter caller) { + if (caller != this) { + MapReducer child = (MapReducer)caller; + MapReducer sib = child.sibling; + if (sib == null || sib.result == null) + result = child.result; + else + result = reducer.apply(child.result, sib.result); + } + } + public E getRawResult() { return result; } + + public static E mapReduce(E[] array, MyMapper mapper, MyReducer reducer) { + return new MapReducer(null, array, mapper, reducer, + 0, array.length).invoke(); + } +} + + + +public class TCountedCompleter { + public static void main(String[] args) { + ForEach.forEach(new Integer[]{2,6,4,3,6,7,8,4,3,6,8,9,0,5,4,3,2}, new MyOperation()); + System.out.println("-----------"); + ForEach2.forEach(new Integer[]{2,6,4,3,6,7,8,4,3,6,8,9,0,5,4,3,2}, new MyOperation()); + System.out.println("-----------"); + ForEach3.forEach(new Integer[]{2,6,4,3,6,7,8,4,3,6,8,9,0,5,4,3,2}, new MyOperation()); + + } +} diff --git a/concurrent/src/main/me.zzw.app.concurrent/TCyclicBarrier.java b/concurrent/src/main/me.zzw.app.concurrent/TCyclicBarrier.java new file mode 100644 index 0000000..523c003 --- /dev/null +++ b/concurrent/src/main/me.zzw.app.concurrent/TCyclicBarrier.java @@ -0,0 +1,78 @@ +package me.zzw.app.concurrent; + +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.BrokenBarrierException; +import java.util.concurrent.CyclicBarrier; + +/** + * Created by infosea on 2016-09-09. + */ +class Solver { + final int N; + final float[][] data; + final CyclicBarrier barrier; + + class Worker implements Runnable { + int myRow; + + public Worker(int myRow) { + this.myRow = myRow; + } + + @Override + public void run() { + // while( !done()){ + processRow(myRow); + + try{ + barrier.await(); + }catch (InterruptedException e){ + return; + }catch (BrokenBarrierException e){ + return; + } + // } + } + + private boolean done() { + return true; + } + + private void processRow(int myRow) { + System.out.println("is processing row " + myRow); + } + } + + public Solver(float[][] matrix) { + this.data = matrix; + this.N = matrix.length; + Runnable barrierAction = () ->mergeRows(data); + barrier = new CyclicBarrier(N, barrierAction); + + List threads = new ArrayList<>(N); + for (int i =0; i< N ;i++){ + Thread thread = new Thread(new Worker(i)); + threads.add(thread); + thread.start(); + } + + // wait until done + for ( Thread thread : threads) + try { + thread.join(); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + + private void mergeRows(float[][] data) { + System.out.println( "has finished " + data); + } +} +public class TCyclicBarrier { + public static void main(String[] args){ + float[][] matrix = new float[][]{{1.2f,1,3f},{2.2f,2.3f}}; + Solver solver = new Solver(matrix); + } +} diff --git a/concurrent/src/main/me.zzw.app.concurrent/TExecutorService.java b/concurrent/src/main/me.zzw.app.concurrent/TExecutorService.java new file mode 100644 index 0000000..4e7ed49 --- /dev/null +++ b/concurrent/src/main/me.zzw.app.concurrent/TExecutorService.java @@ -0,0 +1,61 @@ +package me.zzw.app.concurrent; + +import java.io.*; +import java.net.ServerSocket; +import java.net.Socket; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; + +/** + * Created by infosea on 2016-09-12. + */ +class NetworkService implements Runnable { + private final ServerSocket serverSocket; + private final ExecutorService pool; + + public NetworkService(int port, int poolSize) throws IOException{ + serverSocket = new ServerSocket(port); + pool = Executors.newFixedThreadPool(poolSize); + } + + @Override + public void run() { + try{ + for(;;){ + pool.execute(new Handler(serverSocket.accept())); + } + }catch (IOException ex){ + pool.shutdown();; + } + } +} +class Handler implements Runnable { + private final Socket socket; + private final BufferedReader in; + private String line = ""; + public Handler(Socket socket) throws IOException { + this.socket = socket; + this.in = new BufferedReader(new InputStreamReader(socket.getInputStream())); + + } + + @Override + public void run() { + try { + while ((line = in.readLine()) != null) + System.out.println(line); + }catch (IOException ex){ + ex.printStackTrace(); + } + } +} +public class TExecutorService { + public static void main(String[] args){ + try { + NetworkService service = new NetworkService(9999, 20); + new Thread(service).start(); + } catch (IOException e) { + e.printStackTrace(); + } + } +} diff --git a/concurrent/src/main/me.zzw.app.concurrent/TForkJoinPool.java b/concurrent/src/main/me.zzw.app.concurrent/TForkJoinPool.java new file mode 100644 index 0000000..8afa0ca --- /dev/null +++ b/concurrent/src/main/me.zzw.app.concurrent/TForkJoinPool.java @@ -0,0 +1,76 @@ +package me.zzw.app.concurrent; + +import java.io.File; +import java.util.concurrent.ForkJoinPool; +import java.util.concurrent.ForkJoinTask; +import java.util.concurrent.TimeUnit; + +/** + * Created by infosea on 2016-09-12. + */ +class DocumentTask extends ForkJoinTask { + File file; + + public DocumentTask(File file) { + this.file = file; + } + + @Override + public File getRawResult() { + return file; + } + + @Override + protected void setRawResult(File value) { + file = file; + } + + @Override + protected boolean exec() { + if (file.isDirectory()) { + File[] files = file.listFiles(); + for (File f : files) + new DocumentTask(f).fork(); + return true; + } else { + System.out.println(file.getName()); + return true; + } + + } +} +class ListFile { + public void listFile(File file) { + if(file.isDirectory()){ + File[] files = file.listFiles(); + for(File f : files){ + listFile(f); + } + }else { + System.out.println(file.getName()); + } + } +} +public class TForkJoinPool { + + public static void main(String[] args){ +// long begin =System.currentTimeMillis(); +// ForkJoinPool pool = new ForkJoinPool(4); +// pool.submit( new DocumentTask(new File("F:\\ilasLogRead"))); +// try { +// pool.awaitTermination(2, TimeUnit.SECONDS); +// } catch (InterruptedException e) { +// e.printStackTrace(); +// } +// long end = System.currentTimeMillis(); +// System.out.println(end - begin); + + + + long begin2 = System.currentTimeMillis(); + ListFile listFile = new ListFile(); + listFile.listFile(new File("F:\\ilasLogRead")); + long end2 = System.currentTimeMillis(); + System.out.println(end2 - begin2); + } +} diff --git a/concurrent/src/main/me.zzw.app.concurrent/TForkJoinTask.java b/concurrent/src/main/me.zzw.app.concurrent/TForkJoinTask.java new file mode 100644 index 0000000..90ad691 --- /dev/null +++ b/concurrent/src/main/me.zzw.app.concurrent/TForkJoinTask.java @@ -0,0 +1,29 @@ +package me.zzw.app.concurrent; + +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ForkJoinTask; +import java.util.concurrent.RecursiveTask; + +/** + * Created by infosea on 2016-09-09. + */ +public class TForkJoinTask { + public static String splie(String s){ + return s; + } + public static void main(String[] args) throws ExecutionException, InterruptedException { + String s = "abcdefg"; + ForkJoinTask task = new RecursiveTask() { + @Override + protected String compute() { + if(s.length()>6){ + //split(s); + } + return s; + } + }; + task.invoke(); + String ss = task.get(); + System.out.println(ss); + } +} diff --git a/concurrent/src/main/me.zzw.app.concurrent/TFurture.java b/concurrent/src/main/me.zzw.app.concurrent/TFurture.java new file mode 100644 index 0000000..b5d52c2 --- /dev/null +++ b/concurrent/src/main/me.zzw.app.concurrent/TFurture.java @@ -0,0 +1,78 @@ +package me.zzw.app.concurrent; + +import jdk.nashorn.internal.codegen.CompilerConstants; + +import java.io.File; +import java.util.concurrent.*; + +/** + * Created by infosea on 2016-09-09. + */ +interface ArchiveSearcher { + String search(String target); +} + +class App { + ExecutorService executor = Executors.newFixedThreadPool(5); + ArchiveSearcher searcher = new ArchiveSearcher() { + private String[] strings ={ "a","b","c", "a", "e", "f", "g"}; + @Override + public String search(String target) { + String strs = ""; + for(String s : strings){ + if(s.equals(target)){ + strs +=s; + } + } + return strs; + } + }; + void showSearch(final String target) throws InterruptedException { + Future future = executor.submit(() -> searcher.search(target)); + displayOtherThings(); + try { + displayText(future.get()); + }catch (ExecutionException ex) {cleanup(); return;} + } + + void showSearch2(final String target) throws InterruptedException { + FutureTask future = + new FutureTask( () -> searcher.search(target)); + executor.execute(future); + displayOtherThings(); + try { + displayText(future.get()); + }catch (ExecutionException ex) {cleanup(); return;} + } + + void shutdown(){ + executor.shutdownNow(); + } + + private void displayOtherThings() { + System.out.println(" display other things"); + } + + private void displayText(String text){ + System.out.println(text); + } + + private void cleanup(){ + executor.shutdown(); + } + +} +public class TFurture { + public static void main(String[] args){ + App app = new App(); + try { + app.showSearch2("a"); + app.showSearch2("b"); + app.showSearch2("c"); + app.showSearch2("e"); + } catch (InterruptedException e) { + e.printStackTrace(); + } + app.shutdown(); + } +} diff --git a/concurrent/src/main/me.zzw.app.concurrent/TSemaphore.java b/concurrent/src/main/me.zzw.app.concurrent/TSemaphore.java new file mode 100644 index 0000000..8e502aa --- /dev/null +++ b/concurrent/src/main/me.zzw.app.concurrent/TSemaphore.java @@ -0,0 +1,71 @@ +package me.zzw.app.concurrent; + +import java.util.Objects; +import java.util.concurrent.Semaphore; + +/** + * Created by infosea on 2016-09-09. + */ +class Pool{ + private static final int MAX_VAILABLE = 100; + private final Semaphore available = new Semaphore(MAX_VAILABLE, true); + + public Object getItem() throws InterruptedException { + available.acquire(); + return getNextAvailableItem(); + } + + public void putItem(Object x) { + if (markAsUnused(x)) + available.release(); + } + + // Not a particularly efficient data structure; just for demo + + protected Object[] items = new Integer[MAX_VAILABLE]; + + public Pool(){ + for (int i=0;i tasks){ + final Phaser phaser = new Phaser(1); // "1" to register self + // create and start threads + for (final Runnable task : tasks){ + phaser.register(); + new Thread() { + @Override + public void run() { + phaser.arriveAndAwaitAdvance(); // await all creation + task.run(); + } + }.start(); + } + + // allow thread to start and deregister self + phaser.arriveAndDeregister(); + } + public static void main(String[] args){ + final int tasksSize = 5; + List tasks = new ArrayList<>(tasksSize); + for(int i= 0; i< tasksSize; i++){ + tasks.add(() -> System.out.println("task is running")); + } + Tphaser tphaser = new Tphaser(); + tphaser.runTasks(tasks); + } + +} diff --git a/concurrent/src/main/me.zzw.app.concurrent/TrecursiveAction.java b/concurrent/src/main/me.zzw.app.concurrent/TrecursiveAction.java new file mode 100644 index 0000000..d61395f --- /dev/null +++ b/concurrent/src/main/me.zzw.app.concurrent/TrecursiveAction.java @@ -0,0 +1,59 @@ +package me.zzw.app.concurrent; + +import java.util.Arrays; +import java.util.concurrent.RecursiveAction; + +/** + * Created by infosea on 2016-09-09. + */ + +public class TrecursiveAction { + static class SortTask extends RecursiveAction{ + final long[] array; final int lo, hi; + + public SortTask(long[] array, int lo, int hi) { + this.array = array; + this.lo = lo; + this.hi = hi; + } + + public SortTask(long[] array) { + this(array,0,array.length); + } + + @Override + protected void compute() { + if (hi - lo < THRESHOLD) + sortSquentially(lo, hi); + else{ + int mid = (lo + hi) >>> 1; + invokeAll(new SortTask(array, lo, mid), + new SortTask(array, mid, hi)); + merge(lo, mid, hi); + } + } + // implementation details follow; + static final int THRESHOLD = 1000; + void sortSquentially(int lo, int hi) { + Arrays.sort(array, lo, hi); + } + void merge(int lo, int mid, int hi) { + long[] buf = Arrays.copyOfRange(array, lo, mid); + for(int i = 0, j = lo, k = mid; i < buf.length; j++) + array[j] = (k == hi || buf[i] < array[k]) ? + buf[i++] : array[k++]; + } + } + + public static void main(String[] args){ + long[] sortingLongs = new long[100000] ; + for(int i = 0; i< 100000; i++){ + sortingLongs[i] = Long.valueOf(i).longValue(); + } + TrecursiveAction.SortTask sortTask = new TrecursiveAction.SortTask(sortingLongs); + sortTask.compute(); + for(int i = 0; i < sortTask.array.length; i++){ + System.out.println(sortTask.array[i]); + } + } +} diff --git a/concurrent/src/main/me.zzw.app.concurrent/TthreadFactory.java b/concurrent/src/main/me.zzw.app.concurrent/TthreadFactory.java new file mode 100644 index 0000000..79bd5d8 --- /dev/null +++ b/concurrent/src/main/me.zzw.app.concurrent/TthreadFactory.java @@ -0,0 +1,13 @@ +package me.zzw.app.concurrent; + +import java.util.concurrent.Executors; +import java.util.concurrent.ThreadFactory; + +/** + * Created by infosea on 2016-09-09. + */ +public class TthreadFactory { + public static void main(String[] args){ + ThreadFactory factory = Executors.defaultThreadFactory(); + } +} diff --git a/concurrent/src/main/me.zzw.app.concurrent/consumerAndProductor/Main.java b/concurrent/src/main/me.zzw.app.concurrent/consumerAndProductor/Main.java new file mode 100644 index 0000000..5d8f138 --- /dev/null +++ b/concurrent/src/main/me.zzw.app.concurrent/consumerAndProductor/Main.java @@ -0,0 +1,128 @@ +package me.zzw.app.concurrent.consumerAndProductor; + +import java.util.Stack; + +/** + * Created by infosea on 2016-09-09. + */ +class Consumer extends Thread{ + Base base; + + public Consumer(Base base) { + this.base = base; + } + + public void consume(){ + base.pop(); + + } + + @Override + public void run() { + while (true) { + consume(); + } + } +} + +class Producer extends Thread{ + public static int item = 0; + Base base; + + public Producer(Base base) { + this.base = base; + } + + public void product(){ + while(true) { + base.push(new Item("item" + ++item)); + } + } + + @Override + public void run() { + product(); + } +} + +class Item { + private String name; + + public Item(String name) { + this.name = name; + } + + public String getName() { + return name; + } + +} + +class Base { + private Stack items; + + public Base(Stack items) { + this.items = items; + } + + public Stack getItems() { + return items; + } + + public void pop() { + synchronized (items) { + if (items.size() !=0) { + Item item = items.pop(); + System.out.println("consume item : " + item.getName()); + items.notifyAll(); + + } else { + try { + System.out.println(items.size()); + items.wait(); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + } + + } + + public void push(Item item){ + synchronized (items) { + if(items.size() ==0) { + items.push(item); + System.out.println("product item : item" + item); + try { + Thread.sleep(1000); + } catch (InterruptedException e) { + e.printStackTrace(); + } + items.notifyAll(); + }else{ + try { + System.out.println(items.size()); + items.wait(); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + } + } +} + +public class Main { + public static void main(String[] args){ + + Base base = new Base(new Stack()); + Consumer consumer1 = new Consumer(base); + Producer producer1 = new Producer(base); + consumer1.start(); + producer1.start(); + Consumer consumer2 = new Consumer(base); + Producer producer2 = new Producer(base); + consumer2.start(); + producer2.start(); + } + +} diff --git a/concurrent/src/main/me.zzw.app.concurrent/consumerAndProductor/Test.java b/concurrent/src/main/me.zzw.app.concurrent/consumerAndProductor/Test.java new file mode 100644 index 0000000..a504695 --- /dev/null +++ b/concurrent/src/main/me.zzw.app.concurrent/consumerAndProductor/Test.java @@ -0,0 +1,273 @@ +package me.zzw.app.concurrent.consumerAndProductor; + +/** + * Created by infosea on 2016-09-09. + */ +import java.util.LinkedList; + +/** + * 仓库类Storage实现缓冲区 + * + * Email:530025983@qq.com + * + * @author MONKEY.D.MENG 2011-03-15 + * + */ + class Storage +{ + // 仓库最大存储量 + private final int MAX_SIZE = 100; + + // 仓库存储的载体 + private LinkedList list = new LinkedList(); + + // 生产num个产品 + public void produce(int num) + { + // 同步代码段 + synchronized (list) + { + // 如果仓库剩余容量不足 + while (list.size() + num > MAX_SIZE) + { + System.out.println("【要生产的产品数量】:" + num + "/t【库存量】:" + + list.size() + "/t暂时不能执行生产任务!"); + try + { + // 由于条件不满足,生产阻塞 + list.wait(); + } + catch (InterruptedException e) + { + e.printStackTrace(); + } + } + + // 生产条件满足情况下,生产num个产品 + for (int i = 1; i <= num; ++i) + { + list.add(new Object()); + } + + System.out.println("【已经生产产品数】:" + num + "/t【现仓储量为】:" + list.size()); + + list.notifyAll(); + } + } + + // 消费num个产品 + public void consume(int num) + { + // 同步代码段 + synchronized (list) + { + // 如果仓库存储量不足 + while (list.size() < num) + { + System.out.println("【要消费的产品数量】:" + num + "/t【库存量】:" + + list.size() + "/t暂时不能执行生产任务!"); + try + { + // 由于条件不满足,消费阻塞 + list.wait(); + } + catch (InterruptedException e) + { + e.printStackTrace(); + } + } + + // 消费条件满足情况下,消费num个产品 + for (int i = 1; i <= num; ++i) + { + list.remove(); + } + + System.out.println("【已经消费产品数】:" + num + "/t【现仓储量为】:" + list.size()); + + list.notifyAll(); + } + } + + // get/set方法 + public LinkedList getList() + { + return list; + } + + public void setList(LinkedList list) + { + this.list = list; + } + + public int getMAX_SIZE() + { + return MAX_SIZE; + } +} +/** + * 生产者类Producer继承线程类Thread + * + * Email:530025983@qq.com + * + * @author MONKEY.D.MENG 2011-03-15 + * + */ + class Producer1 extends Thread +{ + // 每次生产的产品数量 + private int num; + + // 所在放置的仓库 + private Storage storage; + + // 构造函数,设置仓库 + public Producer1(Storage storage) + { + this.storage = storage; + } + + // 线程run函数 + public void run() + { + produce(num); + } + + // 调用仓库Storage的生产函数 + public void produce(int num) + { + storage.produce(num); + } + + // get/set方法 + public int getNum() + { + return num; + } + + public void setNum(int num) + { + this.num = num; + } + + public Storage getStorage() + { + return storage; + } + + public void setStorage(Storage storage) + { + this.storage = storage; + } +} +/** + * 消费者类Consumer继承线程类Thread + * + * Email:530025983@qq.com + * + * @author MONKEY.D.MENG 2011-03-15 + * + */ + class Consumer1 extends Thread +{ + // 每次消费的产品数量 + private int num; + + // 所在放置的仓库 + private Storage storage; + + // 构造函数,设置仓库 + public Consumer1(Storage storage) + { + this.storage = storage; + } + + // 线程run函数 + public void run() + { + consume(num); + } + + // 调用仓库Storage的生产函数 + public void consume(int num) + { + storage.consume(num); + } + + // get/set方法 + public int getNum() + { + return num; + } + + public void setNum(int num) + { + this.num = num; + } + + public Storage getStorage() + { + return storage; + } + + public void setStorage(Storage storage) + { + this.storage = storage; + } +} +/** + * 测试类Test + * + * Email:530025983@qq.com + * + * @author MONKEY.D.MENG 2011-03-15 + * + */ +public class Test +{ + public static void main(String[] args) + { + // 仓库对象 + Storage storage = new Storage(); + + // 生产者对象 + Producer1 p1 = new Producer1(storage); + Producer1 p2 = new Producer1(storage); + Producer1 p3 = new Producer1(storage); + Producer1 p4 = new Producer1(storage); + Producer1 p5 = new Producer1(storage); + Producer1 p6 = new Producer1(storage); + Producer1 p7 = new Producer1(storage); + + // 消费者对象 + Consumer1 c1 = new Consumer1(storage); + Consumer1 c2 = new Consumer1(storage); + Consumer1 c3 = new Consumer1(storage); + + // 设置生产者产品生产数量 + p1.setNum(10); + p2.setNum(10); + p3.setNum(10); + p4.setNum(10); + p5.setNum(10); + p6.setNum(10); + p7.setNum(80); + + // 设置消费者产品消费数量 + c1.setNum(50); + c2.setNum(20); + c3.setNum(30); + + // 线程开始执行 + c1.start(); + c2.start(); + c3.start(); + p1.start(); + p2.start(); + p3.start(); + p4.start(); + p5.start(); + p6.start(); + p7.start(); + } +} diff --git a/concurrent/src/main/me/zzw/app/io/TPipedInputStream.java b/concurrent/src/main/me/zzw/app/io/TPipedInputStream.java new file mode 100644 index 0000000..18d019f --- /dev/null +++ b/concurrent/src/main/me/zzw/app/io/TPipedInputStream.java @@ -0,0 +1,41 @@ +package me.zzw.app.io; + +import java.io.*; + +/** + * Created by infosea on 2016-09-12. + */ +public class TPipedInputStream { + PipedInputStream pis ; + BufferedReader br; + PipedOutputStream pos; + + public TPipedInputStream(PipedOutputStream pos, BufferedReader br) { + try { + this.pis = new PipedInputStream(pos); + + this.br = br; + this.pos = pos; + } catch (IOException e) { + e.printStackTrace(); + } + } + + public static void main(String[] args) { + try { + TPipedInputStream pis = new TPipedInputStream(new PipedOutputStream(), new BufferedReader(new FileReader(new File("c:/csb.log")))); + byte[] bytes ; + String line =""; + while((line = pis.br.readLine())!= null) { + bytes = line.getBytes(); + pis.pos.write(bytes); + pis.pos.flush(); + int len = pis.pis.read(bytes); + System.out.println(new String(bytes, 0, len)); + + } + } catch (IOException e) { + e.printStackTrace(); + } + } +} diff --git a/concurrent/src/main/me/zzw/app/lang/TCompiler.java b/concurrent/src/main/me/zzw/app/lang/TCompiler.java new file mode 100644 index 0000000..c58143c --- /dev/null +++ b/concurrent/src/main/me/zzw/app/lang/TCompiler.java @@ -0,0 +1,18 @@ +package me.zzw.app.lang; + +/** + * Created by infosea on 2016-09-12. + */ +public class TCompiler { + public static boolean compileClass(Class clazz){ + return Compiler.compileClass(clazz); + } + + public static void main(String[] args){ + try { + System.out.println(TCompiler.compileClass(Class.forName("me.zzw.app.lang.TCompiler"))); + } catch (ClassNotFoundException e) { + e.printStackTrace(); + } + } +} diff --git a/jdk8/pom.xml b/jdk8/pom.xml index 119c55e..58a77dc 100644 --- a/jdk8/pom.xml +++ b/jdk8/pom.xml @@ -16,6 +16,16 @@ guava 19.0 + + log4j + log4j + 1.2.17 + + + junit + junit + 4.12 + \ No newline at end of file diff --git a/jdk8/src/main/java/me/zzw/app/jdk8/api/countedComplete/CountedCompleterApi.java b/jdk8/src/main/java/me/zzw/app/jdk8/api/countedComplete/CountedCompleterApi.java new file mode 100644 index 0000000..e4ba005 --- /dev/null +++ b/jdk8/src/main/java/me/zzw/app/jdk8/api/countedComplete/CountedCompleterApi.java @@ -0,0 +1,53 @@ +package me.zzw.app.jdk8.api.countedComplete; + +import java.util.concurrent.CountedCompleter; + +/** + * Created by infosea on 2016-07-28. + */ +class MyOperation { + void apply(E e) { + System.out.println(e); + } +} + + +class ForEach extends CountedCompleter { + public static void forEach(E[] array, MyOperation op) { + new ForEach(null, array, op, 0, array.length).invoke(); + } + + final E[] array; + final MyOperation op; + final int lo, hi; + + ForEach(CountedCompleter p, E[] array, MyOperation op, int lo, int hi) { + super(p); + this.array = array; + this.op = op; + this.lo = lo; + this.hi = hi; + } + + public void compute() { // version 1 + if (hi - lo >= 2) { + int mid = (lo + hi) >>> 1; + setPendingCount(2); // must set pending count before fork + new ForEach(this, array, op, mid, hi).fork(); // right child + new ForEach(this, array, op, lo, mid).fork(); // left child + } else if (hi > lo) + op.apply(array[lo]); + tryComplete(); + } +} + +public class CountedCompleterApi { + public static void main(String... args) { + String[] strings = new String[]{"hello", "world"}; + ForEach.forEach(strings, new MyOperation()); + + strings = new String[]{"hello", "world", "this", "is ", "a", "countedCompleter"}; + ForEach forEach = new ForEach(null, strings, new MyOperation(),0, 6); + forEach.invoke(); + } +} \ No newline at end of file diff --git a/jdk8/src/main/java/me/zzw/app/jdk8/api/executorService/App.java b/jdk8/src/main/java/me/zzw/app/jdk8/api/executorService/App.java index fa34f6e..9cf5504 100644 --- a/jdk8/src/main/java/me/zzw/app/jdk8/api/executorService/App.java +++ b/jdk8/src/main/java/me/zzw/app/jdk8/api/executorService/App.java @@ -11,39 +11,43 @@ * Created by infosea on 2016-07-27. */ class NetworkService implements Runnable { - private final ServerSocket serverSocket; - private final ExecutorService pool; + private final ServerSocket serverSocket; + private final ExecutorService pool; - public NetworkService(int port, int poolSize) - throws IOException { - serverSocket = new ServerSocket(port); - pool = Executors.newFixedThreadPool(poolSize); - } - - public void run() { // run the service - try { - for (;;) { - pool.execute(new Handler(serverSocket.accept())); - } - } catch (IOException ex) { - pool.shutdown(); - } - } - } - - class Handler implements Runnable { - private final Socket socket; + public NetworkService(int port, int poolSize) + throws IOException { + serverSocket = new ServerSocket(port); + pool = Executors.newFixedThreadPool(poolSize); + } - Handler(Socket socket) { - this.socket = socket; - } + public void run() { // run the service + try { + for (; ; ) { + pool.execute(new Handler(serverSocket.accept())); + } + } catch (IOException ex) { + pool.shutdown(); + } + } +} - public void run() { - // read and service request on socket - } +class Handler implements Runnable { + private final Socket socket; - } + Handler(Socket socket) { + this.socket = socket; + } + byte[] bytes = new byte[128]; + public void run() { + try { + socket.getInputStream().read(bytes); + } catch (IOException e) { + e.printStackTrace(); + } + System.out.println(new String(bytes)); + } +} public class App { @@ -70,4 +74,9 @@ void shutdownAndAwaitTermination(ExecutorService pool) { Thread.currentThread().interrupt(); } } + + public static void main(String... args) throws IOException { + NetworkService service = new NetworkService( 8088, 5); + new Thread(service).start(); + } } diff --git a/jdk8/src/main/java/me/zzw/app/jdk8/api/forkAndJoin/Sums.java b/jdk8/src/main/java/me/zzw/app/jdk8/api/forkAndJoin/Sums.java new file mode 100644 index 0000000..35e44f8 --- /dev/null +++ b/jdk8/src/main/java/me/zzw/app/jdk8/api/forkAndJoin/Sums.java @@ -0,0 +1,41 @@ +package me.zzw.app.jdk8.api.forkAndJoin; + +import java.util.List; +import java.util.concurrent.*; + +import static java.util.Arrays.asList; + +/** + * Created by infosea on 2016-07-28. + * http://ifeve.com/fork-and-join-java/ + */ +public class Sums { + static class Sum implements Callable { + private final long from; + private final long to; + Sum(long from, long to) { + this.from = from; + this.to = to; + } + @Override + public Long call() { + long acc = 0; + for (long i = from; i<=to; i++) { + acc += i; + } + return acc; + } + } + + public static void main(String... args) throws InterruptedException, ExecutionException { + ExecutorService executor = Executors.newFixedThreadPool(2); + List> results = executor.invokeAll(asList( + new Sum(0, 10), new Sum(100, 1_000), new Sum(10_000, 1_000_000) + )); + executor.shutdown(); + + for(Future result : results) { + System.out.println(result.get()); + } + } +} diff --git a/jdk8/src/main/java/me/zzw/app/jdk8/api/forkAndJoin/WordCounter.java b/jdk8/src/main/java/me/zzw/app/jdk8/api/forkAndJoin/WordCounter.java new file mode 100644 index 0000000..c4a2848 --- /dev/null +++ b/jdk8/src/main/java/me/zzw/app/jdk8/api/forkAndJoin/WordCounter.java @@ -0,0 +1,185 @@ +package me.zzw.app.jdk8.api.forkAndJoin; + +import javax.print.Doc; +import java.io.BufferedReader; +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileReader; +import java.util.LinkedList; +import java.util.List; +import java.util.concurrent.ForkJoinPool; +import java.util.concurrent.RecursiveTask; + +/** + * Created by infosea on 2016-07-28. + */ +class Document { + private final List lines; + + Document(List lines) { + this.lines = lines; + } + + List getLines() { + return lines; + } + + static Document fromFile(File file) throws Exception { + List lines = new LinkedList<>(); + try(BufferedReader reader = new BufferedReader(new FileReader(file))){ + String line = reader.readLine(); + while(line != null) { + lines.add(line); + line = reader.readLine(); + } + } + return new Document(lines); + } +} + +class Folder { + private final List subFolders; + private final List documents; + + public Folder(List subFolders, List documents) { + this.subFolders = subFolders; + this.documents = documents; + } + + List getSubFolders() { + return this.subFolders; + } + + List getDocuments() { + return this.documents; + } + + static Folder fromDirectory(File dir) throws Exception { + List documents = new LinkedList<>(); + List subFolders = new LinkedList<>(); + for(File entry : dir.listFiles()) { + if(entry.isDirectory()) { + subFolders.add(Folder.fromDirectory(entry)); + }else{ + documents.add(Document.fromFile(entry)); + } + } + return new Folder(subFolders, documents); + } +} + + +public class WordCounter { + static String[] wordsIn(String line) { + return line.trim().split("(\\s|\\p{Punct})+"); + } + + Long occurrencesCount(Document document, String searchedWord) { + long count = 0; + for(String line : document.getLines()) { + for(String word : wordsIn(line)) { + if(searchedWord.equals(word)) { + count = count + 1; + } + } + } + return count; + } + + Long countOccurrencesOnSingleThread(Folder folder, String searchedWord) { + long count = 0; + for (Folder subFolder : folder.getSubFolders()) { + count = count + countOccurrencesOnSingleThread(subFolder, searchedWord); + } + for (Document document : folder.getDocuments()) { + count = count + occurrencesCount(document, searchedWord); + } + return count; + } + + class DocumentSearchTask extends RecursiveTask { + private final Document document; + private final String searchedWord; + + public DocumentSearchTask(Document document, String searchedWord) { + this.document = document; + this.searchedWord = searchedWord; + } + + @Override + protected Long compute() { + return occurrencesCount(document, searchedWord); + } + } + + class FolderSearchTask extends RecursiveTask { + private final Folder folder; + private final String searchedWord; + + public FolderSearchTask(Folder folder, String searchedWord) { + this.folder = folder; + this.searchedWord = searchedWord; + } + + @Override + protected Long compute() { + long count = 0L; + List> forks = new LinkedList<>(); + for(Folder subFolder : folder.getSubFolders()) { + FolderSearchTask task = new FolderSearchTask(subFolder, searchedWord); + forks.add(task); + task.fork(); + } + for(Document document : folder.getDocuments()) { + DocumentSearchTask task = new DocumentSearchTask(document,searchedWord); + forks.add(task); + task.fork(); + } + for(RecursiveTask task : forks){ + count = count + task.join(); + } + return count; + } + } + + private final ForkJoinPool forkJoinPool = new ForkJoinPool(); + Long countOccurrencesInParallel(Folder folder, String searchedWord) { + return forkJoinPool.invoke(new FolderSearchTask(folder, searchedWord)); + } + + public static void main(String... args) throws Exception { + WordCounter wordCounter = new WordCounter(); + Folder folder = Folder.fromDirectory(new File(args[0])); + + final int repeatCount = Integer.decode(args[2]); + long counts; + long startTime; + long stopTime; + + long[] singleThreadTimes = new long[repeatCount]; + long[] forkedThreadTimes = new long[repeatCount]; + + for (int i = 0; i < repeatCount; i++) { + startTime = System.currentTimeMillis(); + counts = wordCounter.countOccurrencesOnSingleThread(folder, args[1]); + stopTime = System.currentTimeMillis(); + singleThreadTimes[i] = (stopTime - startTime); + System.out.println(counts + " , single thread search took " + singleThreadTimes[i] + "ms"); + } + + for (int i = 0; i < repeatCount; i++) { + startTime = System.currentTimeMillis(); + counts = wordCounter.countOccurrencesInParallel(folder, args[1]); + stopTime = System.currentTimeMillis(); + forkedThreadTimes[i] = (stopTime - startTime); + System.out.println(counts + " , fork / join search took " + forkedThreadTimes[i] + "ms"); + } + + System.out.println("\nCSV Output:\n"); + System.out.println("Single thread,Fork/Join"); + for (int i = 0; i < repeatCount; i++) { + System.out.println(singleThreadTimes[i] + "," + forkedThreadTimes[i]); + } + System.out.println(); + } +} diff --git a/jdk8/src/main/java/me/zzw/app/jdk8/api/future/App.java b/jdk8/src/main/java/me/zzw/app/jdk8/api/future/App.java index 63281a0..72e156d 100644 --- a/jdk8/src/main/java/me/zzw/app/jdk8/api/future/App.java +++ b/jdk8/src/main/java/me/zzw/app/jdk8/api/future/App.java @@ -25,19 +25,23 @@ public class App { List strs = Lists.newArrayList("target", "tar", "get", "target"); ExecutorService executor = Executors.newFixedThreadPool(10); ArchiveSearch searcher = new ArchiveSearchImpl(strs) ; - void showSearch(final String target) - throws InterruptedException { + void showSearch1(final String target) throws InterruptedException { Future future - = executor.submit(new Callable() { - public String call() { - return searcher.search(target); - }}); + = executor.submit(() -> searcher.search(target)); displayOtherThings(); // do other things while searching try { displayText(future.get()); // use future } catch (ExecutionException ex) { cleanup(); return; } } + void showSearch2(final String target) throws InterruptedException { + FutureTask future = new FutureTask(() -> searcher.search(target)); + executor.execute(future); + displayOtherThings(); // do other things while searching + try { + displayText(future.get()); // use future + } catch (ExecutionException ex) { cleanup(); return; } + } private void displayOtherThings() { System.out.println("after search..."); } @@ -53,6 +57,6 @@ private void cleanup() { public static void main(String[] args) throws InterruptedException { App app = new App(); - app.showSearch("target"); + app.showSearch2("target"); } } diff --git a/jdk8/src/main/java/me/zzw/app/jdk8/api/proxy/DynamicProxy.java b/jdk8/src/main/java/me/zzw/app/jdk8/api/proxy/DynamicProxy.java new file mode 100644 index 0000000..95cdaa8 --- /dev/null +++ b/jdk8/src/main/java/me/zzw/app/jdk8/api/proxy/DynamicProxy.java @@ -0,0 +1,76 @@ +package me.zzw.app.jdk8.api.proxy; + + +import org.apache.log4j.Logger; +import org.junit.Test; +import sun.misc.ProxyGenerator; + +import java.io.FileOutputStream; +import java.lang.reflect.InvocationHandler; +import java.lang.reflect.Method; +import java.lang.reflect.Proxy; + +interface Dao { + long insert(); +} + +class DaoImpl implements Dao { + @Override + public long insert() { + return 0; + } +} + +class MyInvocationHandler implements InvocationHandler { + private Object object; + + public MyInvocationHandler(Object object) { + this.object = object; + } + + @Override + public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { + return method.invoke(object, args); + } +} + +/** + * http://www.cnblogs.com/flyoung2008/archive/2013/08/11/3251148.html + */ +public class DynamicProxy { + Logger logger = Logger.getLogger(DynamicProxy.class); + @Test + public void test() { + Object object = Proxy.newProxyInstance(Dao.class.getClassLoader(), + + new Class[]{Dao.class}, + new MyInvocationHandler(new DaoImpl())); + Dao proxy = (Dao)object; + logger.info(Proxy.isProxyClass(object.getClass())); + logger.info(Proxy.isProxyClass(proxy.getClass())); + logger.info(Proxy.getInvocationHandler(proxy)); + logger.info( proxy.insert() ); + + } + + + @Test + public void createProxyClassFile() + { + String name = "ProxySubject"; + byte[] data = ProxyGenerator.generateProxyClass( name, new Class[] { Dao.class } ); + try + { + FileOutputStream out = new FileOutputStream( name + ".class" ); + out.write( data ); + out.close(); + } + catch( Exception e ) + { + e.printStackTrace(); + } + } + +} + + diff --git a/jdk8/src/main/java/me/zzw/app/jdk8/api/reflect/ClassApi.java b/jdk8/src/main/java/me/zzw/app/jdk8/api/reflect/ClassApi.java new file mode 100644 index 0000000..94c9b88 --- /dev/null +++ b/jdk8/src/main/java/me/zzw/app/jdk8/api/reflect/ClassApi.java @@ -0,0 +1,29 @@ +package me.zzw.app.jdk8.api.reflect; + +import com.google.common.base.Strings; +import org.apache.log4j.Logger; +import org.junit.Test; + +/** + * Created by infosea on 2016-07-28. + */ +public class ClassApi { + Logger logger = Logger.getLogger(ClassApi.class); + @Test + public void classApi() { + Object classApi1 =ClassApi.this; + Class classApi2 = ClassApi.this.getClass(); + Class classApi3 = ClassApi.class; + try { + Class classApi4 = Class.forName("me.zzw.app.jdk8.api.reflect.ClassApi"); + logger.info(classApi2.getName()); + logger.info(classApi3.getName()); + logger.info(classApi4.getName()); + logger.info("getSimpleName = " + classApi4.getSimpleName()); + } catch (ClassNotFoundException e) { + e.printStackTrace(); + } + } + + +} diff --git a/jdk8/src/main/java/me/zzw/app/jdk8/api/reflect/DynamicClassLoading.java b/jdk8/src/main/java/me/zzw/app/jdk8/api/reflect/DynamicClassLoading.java new file mode 100644 index 0000000..b433a5e --- /dev/null +++ b/jdk8/src/main/java/me/zzw/app/jdk8/api/reflect/DynamicClassLoading.java @@ -0,0 +1,77 @@ +package me.zzw.app.jdk8.api.reflect; + +import org.junit.Test; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.net.MalformedURLException; +import java.net.URL; +import java.net.URLConnection; + +/** + * Created by infosea on 2016-07-28. + */ +class MyClassLoader extends ClassLoader { + public MyClassLoader(ClassLoader parent) { + super(parent); + } + + public Class loadClass(String name) throws ClassNotFoundException { + if(!"me.zzw.app.jdk8.api.reflect.MyObject".equals(name)) { + return super.loadClass(name); + } + + try { + String url = "file:e:/tutorial/jdk8/target/classes/me/zzw/app/jdk8/api/reflect/MyObject.class"; + URL url1 = new URL(url); + URLConnection connection = url1.openConnection(); + InputStream input = connection.getInputStream(); + ByteArrayOutputStream buffer = new ByteArrayOutputStream(); + int data = input.read(); + while(data != -1) { + buffer.write(data); + data = input.read(); + } + input.close(); + byte[] classData = buffer.toByteArray(); + return defineClass("me.zzw.app.jdk8.api.reflect.MyObject", + classData, 0, classData.length); + } catch (MalformedURLException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } + return null; + } +} +public class DynamicClassLoading { + public static Class loadClass(String className) throws ClassNotFoundException { + ClassLoader classLoader = DynamicClassLoading.class.getClassLoader(); + return classLoader.loadClass(className); + } + + @Test + public void loadClass() throws ClassNotFoundException, IllegalAccessException, InstantiationException { + ClassLoader parentClassLoader = MyClassLoader.class.getClassLoader(); + MyClassLoader myClassLoader = new MyClassLoader(parentClassLoader); + Class myObjectClass = myClassLoader.loadClass("me.zzw.app.jdk8.api.reflect.MyObject"); + + MyObjectInterface object1 = (MyObjectInterface) myObjectClass.newInstance(); + MyObjectSuperClass object2 = (MyObjectSuperClass) myObjectClass.newInstance(); + + //create new class loader so classes can be reloaded. + myClassLoader = new MyClassLoader(parentClassLoader); + myObjectClass = myClassLoader.loadClass("me.zzw.app.jdk8.api.reflect.MyObject"); + object1 = (MyObjectInterface) myObjectClass.newInstance(); + object2 = (MyObjectSuperClass) myObjectClass.newInstance(); + + object1.testInterface(); + object2.testClass(); + + + } + + +} diff --git a/jdk8/src/main/java/me/zzw/app/jdk8/api/reflect/HelloWorld.java b/jdk8/src/main/java/me/zzw/app/jdk8/api/reflect/HelloWorld.java new file mode 100644 index 0000000..a344e41 --- /dev/null +++ b/jdk8/src/main/java/me/zzw/app/jdk8/api/reflect/HelloWorld.java @@ -0,0 +1,14 @@ +package me.zzw.app.jdk8.api.reflect; + +import java.lang.reflect.Method; +import java.util.Arrays; + +/** + * Created by infosea on 2016-07-28. + */ +public class HelloWorld { + + public static void main(String[] args){ + Arrays.asList(HelloWorld.class.getMethods()).stream().forEach((Method method) -> System.out.println(method.getName())); + } +} diff --git a/jdk8/src/main/java/me/zzw/app/jdk8/api/reflect/MyObject.java b/jdk8/src/main/java/me/zzw/app/jdk8/api/reflect/MyObject.java new file mode 100644 index 0000000..e12a9b9 --- /dev/null +++ b/jdk8/src/main/java/me/zzw/app/jdk8/api/reflect/MyObject.java @@ -0,0 +1,19 @@ +package me.zzw.app.jdk8.api.reflect; + +import org.apache.log4j.Logger; + +/** + * Created by infosea on 2016-07-28. + */ +public class MyObject extends MyObjectSuperClass implements MyObjectInterface { + Logger logger = Logger.getLogger(MyObject.class); + @Override + public void testInterface() { + logger.info("implement testInterface"); + } + + @Override + public void testClass() { + logger.info("override testClass"); + } +} diff --git a/jdk8/src/main/java/me/zzw/app/jdk8/api/reflect/MyObjectInterface.java b/jdk8/src/main/java/me/zzw/app/jdk8/api/reflect/MyObjectInterface.java new file mode 100644 index 0000000..4f9ae0c --- /dev/null +++ b/jdk8/src/main/java/me/zzw/app/jdk8/api/reflect/MyObjectInterface.java @@ -0,0 +1,8 @@ +package me.zzw.app.jdk8.api.reflect; + +/** + * Created by infosea on 2016-07-28. + */ +public interface MyObjectInterface { + public void testInterface(); +} diff --git a/jdk8/src/main/java/me/zzw/app/jdk8/api/reflect/MyObjectSuperClass.java b/jdk8/src/main/java/me/zzw/app/jdk8/api/reflect/MyObjectSuperClass.java new file mode 100644 index 0000000..e4ef173 --- /dev/null +++ b/jdk8/src/main/java/me/zzw/app/jdk8/api/reflect/MyObjectSuperClass.java @@ -0,0 +1,8 @@ +package me.zzw.app.jdk8.api.reflect; + +/** + * Created by infosea on 2016-07-28. + */ +public class MyObjectSuperClass { + public void testClass(){} +} diff --git a/jdk8/src/main/java/me/zzw/app/jdk8/api/reflect/README.md b/jdk8/src/main/java/me/zzw/app/jdk8/api/reflect/README.md new file mode 100644 index 0000000..ec8244c --- /dev/null +++ b/jdk8/src/main/java/me/zzw/app/jdk8/api/reflect/README.md @@ -0,0 +1 @@ +http://ifeve.com/dynamic-class-loading-reloading/ \ No newline at end of file diff --git a/jdk8/src/main/java/me/zzw/app/jdk8/generics/genMethods/App.java b/jdk8/src/main/java/me/zzw/app/jdk8/generics/genMethods/App.java new file mode 100644 index 0000000..b7d9890 --- /dev/null +++ b/jdk8/src/main/java/me/zzw/app/jdk8/generics/genMethods/App.java @@ -0,0 +1,26 @@ +package me.zzw.app.jdk8.generics.genMethods; + +/** + * Created by infosea on 2016-07-28. + */ +class Shape { + +} + +class Circle extends Shape { + +} + +class Rectangle extends Shape { + +} + +public class App { + public static void draw(T shape) { + System.out.println(shape); + } + public static void main(String... args) { + Circle circle = new Circle(); + draw(circle); + } +} diff --git a/jdk8/src/main/resources/log4j.properties b/jdk8/src/main/resources/log4j.properties new file mode 100644 index 0000000..e4fcb01 --- /dev/null +++ b/jdk8/src/main/resources/log4j.properties @@ -0,0 +1,9 @@ +# Set root logger level to DEBUG and its only appender to A1. +log4j.rootLogger=DEBUG, A1 + +# A1 is set to be a ConsoleAppender. +log4j.appender.A1=org.apache.log4j.ConsoleAppender + +# A1 uses PatternLayout. +log4j.appender.A1.layout=org.apache.log4j.PatternLayout +log4j.appender.A1.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n \ No newline at end of file diff --git a/nio/data/fromFile.txt b/nio/data/fromFile.txt new file mode 100644 index 0000000..ffa774a --- /dev/null +++ b/nio/data/fromFile.txt @@ -0,0 +1 @@ +text in fromFile \ No newline at end of file diff --git a/nio/data/toFile.txt b/nio/data/toFile.txt new file mode 100644 index 0000000..ffa774a --- /dev/null +++ b/nio/data/toFile.txt @@ -0,0 +1 @@ +text in fromFile \ No newline at end of file diff --git a/nio/fromFile.txt b/nio/fromFile.txt new file mode 100644 index 0000000..e69de29 diff --git a/nio/toFile.txt b/nio/toFile.txt new file mode 100644 index 0000000..e69de29 diff --git a/pom.xml b/pom.xml index 7ad49fa..dbe7913 100644 --- a/pom.xml +++ b/pom.xml @@ -15,6 +15,7 @@ springBatch spark jdk8 + commons-io