Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

모던자바의 역습

어느덧 스무살이 된 자바. 좋든싫든 프로그래밍의 세계에 몸담고 있는 이상 부딪히지 않을 수 없는 언어인데요, 이 자바에 대한 올바른 모습의 이해화 앞으로 나아가야 할 방향을 모색해본다는 의미에서 "모던 자바의 역습"이라는 타이틀로 실시한 온라인 세미나의 슬라이드 자료입니다.

진행자: 김대우(http://lekdw.blogspot.kr/)
정도현(http://moreagile.net)

이번 세미나는 게임개발자이신 김대우님을 모시고 진행하게 되었는데요 자바 언어와 관련 하여 다음과 같은 주제로 두시간에 걸쳐 발표를 진행합니다.

- 간단히 살펴보는 자바20년의 발자취
- 자바를 둘러싼 진실 혹은 거짓(성능,생산성,품질)
- SI영역 이외에서 자바의 가치
- 모던자바의 역습: 자바8과 함수형 프로그래밍
- 자바 개발의 새로운 패러다임들

  • Be the first to comment

모던자바의 역습

  1. 1. 김대우 젬플레이 이사 http://lekdw.blogspot.kr/ 정도현(정개발) 나는 프로그래머다 MC 일본 Mamezou소속 컨설턴트 http://Iamprogrammer.io http://moreagile.net
  2. 2. James Gosling Patrick Naughton https://en.wikipedia.org/wiki/Java_(programming_language)
  3. 3. https://en.wikipedia.org/wiki/Java_(programming_language)
  4. 4. J2SE 5.0 Java SE 7 Java SE 8 https://en.wikipedia.org/wiki/Java_version_history
  5. 5. 연도별 언어 인기도 http://www.tiobe.com/index.p hp/content/paperinfo/tpci/ind ex.html
  6. 6. http://benchmarksgame.alioth.debian.org/u64/which-programs-are-fastest.html
  7. 7. http://www3.ntu.edu.sg/home/ehchua/programming/java/j5b_io.html
  8. 8. http://www.evanjones.ca/software/java-bytebuffers.html
  9. 9. http://netty.io/wiki/using-as-a-generic-library.html
  10. 10. http://terracotta.org/products/bigmemory
  11. 11. 모바일 게임 서버와 같이 Life Cycle이 짧은 데이터(객체)를 주로 처리하 는 경우, 별다른 튜닝없이 -server, -d64, -Xms, -Xmx 옵션으로 충분.
  12. 12. http://www.drdobbs.com/jvm/the-comparative-productivity-of-programm/240005881 Language Hours Per Function Point ASP* 06.1 Visual Basic 08.5 Java 10.6 SQL 10.8 C++ 12.4 C 13.0 C# 15.5 PL/1 14.2 COBOL 16.8 ABAP 19.9
  13. 13. Checkstyle Error Prone FindBugs PMD SonarQube
  14. 14. http://readwrite.com/2011/01/24/the-java-ecosystem-infographic
  15. 15. JUnit SLF4J API Module Scala Library Logback Classic Module Guava: Google Core Libraries for Java Mockito Google APIs Client Library for Java Apache Log4j Commons IO SLF4J LOG4J-12 Binding osgi.core JavaServlet(TM) Specification TestNG ScalaTest Commons Lang Joda-Time Spring Context Mockito H2 Database Engine Java Servlet API http://www.77dev.com/2014/05/java-trends-top-100-mostly-used.html
  16. 16. JCL 1.1.1 implemented over SLF4J jackson-databind SLF4J Simple Binding Apache CommonsCodec Apache HttpClient Apache Commons Lang Commons Logging Spring Core osgi.cmpn Google Guice - Core Library SpringTestContext Framework Jetty :: Server Core Maven Plugin API FindBugs-jsr305 BeanValidation API Spring Beans Groovy Jackson-core EasyMock Spock Framework - Core Module
  17. 17. Java8
  18. 18. http://www.slideshare.net/shintanimoto/from-old-java-to-modern-java
  19. 19. private List m_list=null; private int process_file(String str_file_name){ String str_line; List list_lines=new ArrayList(); int i_result=read_file(str_file_name,list_lines); if(i_result==0){ List list_record=new ArrayList(); for(int i=0;i<list_lines.size();i++){ str_line=(String)list_lines.get(i); Record record=new Record(); i_result=parse_line(str_line,record); if(i_result!=0){ return i_result; } list_recordord.add(record); } m_list=list_record; return 0; }else{ return i_result; } } http://www.slideshare.net/shintanimoto/from-old-java-to-modern-java C-ish java
  20. 20. private List resultList; private List processFile(String fileName)throws SystemException { List lines = readFile(fileName); List recordList = new ArrayList(); for (int i = 0; i < lines.size(); i++) { String line = (String) lines.get(i); Record record = parseLine(line); recordList.add(record); } return recordList; } http://www.slideshare.net/shintanimoto/from-old-java-to-modern-java Java 1.4
  21. 21. private List<Record> processFile(String fileName)throws SystemException { List<String> lines = readFile(fileName); List<Record> recordList = new ArrayList(); for (String line : lines) { Record record = parseLine(line); recordList.add(record); } return recordList; } Java 1.7 generic + foreach
  22. 22. private List<String> readFile(String fileName) { List<String> lines = new ArrayList<String>(); BufferedReader reader = null; try { reader = new BufferedReader(new FileReader(fileName)); String line; while ((line = reader.readLine()) != null) { lines.add(line); } } catch (FileNotFoundException ex) { throw new SystemException(FILE_NOT_FOUND, ex); } catch (IOException ex) { throw new SystemException(FILE_READ_ERROR, ex); } finally { try { if (reader != null) { reader.close(); } } catch (IOException ex) { // 이건 무시? } } return lines; }
  23. 23. private List<String> readFile(String fileName) { List<String> lines = new ArrayList<>(); try (FileReader in = new FileReader(fileName); BufferedReader reader = new BufferedReader(in)) { String line; while ((line = reader.readLine()) != null) { lines.add(line); } } catch (FileNotFoundException ex) { throw new SystemException(FILE_NOT_FOUND, ex); } catch (IOException ex) { throw new SystemException(FILE_READ_ERROR, ex); } return lines; } Java 7
  24. 24. private List<String> readFile(String fileName) { try { return Files.readAllLines(Paths.get(fileName), Charset.defaultCharset()); } catch (IOException ex) { throw new SystemException(FILE_READ_ERROR, ex); } } Java 7
  25. 25. https://ko.wikipedia.org/wiki/함수형_프로그래 밍
  26. 26. public static <E extends Comparable<? super E>> List<E> quickSort(List<E> arr) { if (!arr.isEmpty()) { E pivot = arr.get(0); //This pivot can change to get faster results List<E> less = new LinkedList<E>(); List<E> pivotList = new LinkedList<E>(); List<E> more = new LinkedList<E>(); for (E i: arr) { if (i.compareTo(pivot) < 0) less.add(i); else if (i.compareTo(pivot) > 0) more.add(i); else pivotList.add(i); } less = quickSort(less); more = quickSort(more); less.addAll(pivotList); less.addAll(more); return less; } return arr; } http://rosettacode.org/wiki/Sorting_algorithms/Quicksort#Java Java 7
  27. 27. public static <T> List<T> Quicksort(List<T> v, BiFunction<T, T, Integer> comparer) { if (v.size() < 2) return v; T pivot = v.get(v.size() / 2); List<T> l = new LinkedList<T>(Quicksort(v.stream() .filter(x -> comparer.apply(x, pivot) < 0) .collect(Collectors.toList()), comparer)); l.addAll( v.stream().filter(x -> comparer .apply(x, pivot) == 0).collect(Collectors.toList()) ); l.addAll( Quicksort(v.stream() .filter(x -> comparer.apply(x, pivot) > 0) .collect(Collectors.toList()), comparer) ); return l; } Java 8
  28. 28. qsort [] = [] qsort (x:xs) = qsort (filter (< x) xs) ++ [x] ++ qsort (filter (>= x) xs) https://en.wikibooks.org/wiki/Algorithm_Implementation/Sorting/Quicksort#Haskell Haskell
  29. 29. package org.ingini.spark.java8; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.util.Arrays; import java.util.TreeMap; import static java.util.function.Function.identity; import static java.util.stream.Collectors.counting; import static java.util.stream.Collectors.groupingBy; public class WordsCounterJava { public static final String REGEX = "s+"; public TreeMap<String, Long> count(String source) throws IOException { return Files.lines(Paths.get(source)) .map(line -> line.split(REGEX)) .flatMap(Arrays::stream) .collect(groupingBy(identity(), TreeMap::new, counting())); } }
  30. 30. -Djava.util.concurrent.ForkJoinPool.common.parallelism=1
  31. 31. SELECT * FROM BOOK WHERE BOOK.PUBLISHED_IN = 2011 ORDER BY BOOK.TITLE jOOQ create.selectFrom(BOOK) .where(BOOK.PUBLISHED_IN.eq(2011)) .orderBy(BOOK.TITLE) http://www.jooq.org/
  32. 32. http://java2practice.com/2014/03/16/java-8-functional-interface-example/ Thread t =new Thread(new Runnable(){ public void run(){ System.out.println("Runnable implemented by using Lambda Expression"); } }); Thread t = new Thread(()->{ System.out.println("Runnable implemented by using Lambda Expression"); }); Java 7 Java 8
  33. 33. interface DefaultInterfaceTest{ void show(); default void display(){ System.out.println("Default method from interface can have body..!"); } } public class DefaultInterfaceTestImpl implements DefaultInterfaceTest{ public void show(){ System.out.println("show method"); } //we dont need to provide any implementation to default method. public static void main(String[] args){ DefaultInterfaceTest obj = new DefaultInterfaceTestImpl(); obj.show();//out puts: show method obj.display();//outputs : Default method from interface can have body..! } } Default Method
  34. 34. •Function <T, R> - T를 입력으로 R을 출력으로 반환 •Predicate <T> - T를 입력으로 boolean을 출력으로 반환 •Consumer <T> - T를 입력으로 아무것도 반환하지 않는다 •Supplier <T> - 입력을 취하지 않고 T를 반환 •BinaryOperator <T> - 2 개의 T를 입력으로 하나의 T를 출력으로 반환
  35. 35. http://www.ibm.com/developerworks/library/j-jvmc2/index.html
  36. 36. Runnable task = () -> { String threadName = Thread.currentThread().getName(); System.out.println("Hello " + threadName); }; task.run(); Thread thread = new Thread(task); thread.start();
  37. 37. ExecutorService executor = Executors.newSingleThreadExecutor(); executor.submit(() -> { String threadName = Thread.currentThread().getName(); System.out.println("Hello " + threadName); }); try { //attempt to shutdown executor executor.shutdown(); executor.awaitTermination(5, TimeUnit.SECONDS); } catch (InterruptedException e) { System.err.println("tasks interrupted"); } finally { if (!executor.isTerminated()) { executor.shutdownNow(); } System.out.println("shutdown finished"); } Executors http://winterbe.com/posts/2015/04/07/java8-concurrency-tutorial-thread-executor-examples/
  38. 38. http://ariya.ofilabs.com/2014/03/nashorn-the-new-rhino-on-the-block.html
  39. 39. interface CustomerRepository extends Repository<Customer, Long> { @Query("select c from Customer c") Stream<Customer> streamAllCustomers(); } try (Stream<Customer> customers = repository.streamAllCustomers()) { // use the stream here } Support for JDK 8' Stream in repository methods
  40. 40. interface CustomerRepository extends Repository<Customer, Long> { @Async CompletableFuture<List<Customer>> readAllBy(); } CompletableFuture<List<Customer>> future = repository.readAllBy().thenApply(this::doSomethingWithCustomers); while (!future.isDone()) { log.info("Waiting for the CompletableFuture to finish..."); TimeUnit.MILLISECONDS.sleep(500); } List<Customer> processedCustomers = future.get();
  41. 41. http://doc.akka.io/docs/akka/2.3.0-RC1/java/lambda-actors.html import akka.actor.AbstractActor; import akka.event.Logging; import akka.event.LoggingAdapter; import akka.japi.pf.ReceiveBuilder; import scala.PartialFunction; import scala.runtime.BoxedUnit; public class MyActor extends AbstractActor { private final LoggingAdapter log = Logging.getLogger(context().system(), this); @Override public PartialFunction<Object, BoxedUnit> receive() { return ReceiveBuilder. match(String.class, s -> s.equals("test"), s -> log.info("received test")). matchAny(o -> log.info("received unknown message")).build(); } }
  42. 42. https://blogs.oracle.com/javatraining/entry/announcing_jdk_8_mooc_lambdas

×