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.

What can be done with Java, but should better be done with Erlang (@pavlobaron)

5,134 views

Published on

Slides of my talk at the Erlang Factory 2012 in San Francisco

Published in: Technology, News & Politics
  • Be the first to comment

  • Be the first to like this

What can be done with Java, but should better be done with Erlang (@pavlobaron)

  1. 1. What can be done withJavabut should better be done withErlang
  2. 2. Pavlo Baron Geek‘s Guide pavlo.baron@codecentric.deTo The Working Life @pavlobaron
  3. 3. Hey, dude.What sort of applicationshould be optimally implementedusing your language?
  4. 4. .NET dude: win*
  5. 5. Python dude: sci*
  6. 6. Ruby dude: cool*
  7. 7. Clojure, Groovy, Scala dude: java*
  8. 8. Putonghua dude: 谢谢
  9. 9. Java dude: *
  10. 10. Erlang dude:fit → do();_ → badarg.
  11. 11. This dude in front of youis very picky.
  12. 12. So, let assume that: = =
  13. 13. List<Integer> l = Arrays.asList(1, 2, 3, 4, 5);List<Integer> r = new ArrayList<Integer>(); for (int i : l) { r.add(i * 2); }
  14. 14. List<Integer> l = Arrays.asList(1, 2, 3, 4, 5);Iterable<Integer> t = Iterables.transform(l, new Function<Integer, Integer>() { public Integer apply(Integer i) { return I * 2; } });
  15. 15. And this is just a simple map.It gets even worsewith filter and fold
  16. 16. [X * 2 || X <- lists:seq(1, 5)].
  17. 17. so what?
  18. 18. List<Integer> l = Arrays.asList(1, 2, 3, 4, 5); Iterable<Integer> t = Iterables.transform(l, new Function<Integer, Integer>() {public Integer apply(Integer i) {return I * 2;}});
  19. 19. your colleagues will love it
  20. 20. That works!
  21. 21. synchronized (this) { if (!crawledSites.contains(site)) { linkedSites.add(site); } }…public class CountingSemaphore { private int signals = 0; public synchronized void take() { this.signals++; this.notify(); } public synchronized void release() throws InterruptedException { while (this.signals == 0) wait(); this.signals--; }}
  22. 22. 1> A = 5.52> A = 10.** exception error: no match ofright hand side value 103>
  23. 23. so what?
  24. 24. The simplest way to avoid problemswith concurrency is to share onlyimmutable data between threads.Immutable data is data which cannot be changed.(from a Java concurrency tutorial)
  25. 25. Immutable class:- all its fields are final- class declared as final- “this” reference is not allowed toescape during construction
  26. 26. Any fields which refer tomutable data objects:- are private- have no setter method- are never directly returned ofotherwise exposed to a caller- if they are changed internallyin the class this change is notvisible and has no effectoutside of the class
  27. 27. That works!
  28. 28. 1> F = fun(F) -> F(F) end.#Fun<erl_eval.6.80247286>2> F(F).…..................hours later................BREAK: (a)bort (c)ontinue (p)roc info(i)nfo (l)oaded (v)ersion (k)ill (D)b-tables(d)istributiona
  29. 29. so what?
  30. 30. ...for (paramFiber = recursion1.doit__1(paramEProc, paramEObject); paramFiber == EProc.TAIL_MARKER; paramFiber = (EFun)localFiber.getCallee()) { S_O localS_O; switch (localFiber.up()) { case 2: paramEProc.tail.go(paramEProc, localFiber.down()); localS_O = new S_O(); localS_O.f0 = paramEProc; localFiber.setState(localS_O, this, 1); return null; case 3: null; return null; case 1: localS_O = (S_O)localFiber.curState; paramEProc = (EProc)localS_O.f0; case 0: } }...
  31. 31. That works!
  32. 32. 1> F = fun([_|_]) ->1> io:format("string~n");1> (B) ->1> io:format("integer~n")1> end.#Fun<erl_eval.6.80247286>2> F(15).integerok3> F("whatever").stringok4>
  33. 33. so what?
  34. 34. That works!
  35. 35. try { // Create a new class loader with the directory ClassLoader cl = new URLClassLoader(urls); // Load in the class Class cls = cl.loadClass("MyReloadableClassImpl"); // Create a new instance of the new class myObj = (MyReloadableClass)cls.newInstance();} catch (IllegalAccessException e) {} catch (InstantiationException e) {} catch (ClassNotFoundException e) {}
  36. 36. Excessive class-reloading usingClassLoader hierarchies isexpensive and leads to JVMinstance fatigue
  37. 37. Thats why its stronglyrecommended to do hotdeployment in app servers
  38. 38. % hot_swap:sum(Num)% adds 1 to Num1> c(hot_swap).{ok,hot_swap}2> hot_swap:sum(1).2...% hot_swap.erl has changed.% now it adds 2 to Num…3> c(hot_swap).{ok,hot_swap}4> hot_swap:sum(1).35>
  39. 39. code_change(OldVsn, State, Extra) -> ...code to convert state (and more) during code change... {ok, NewState}.
  40. 40. so what?
  41. 41. JVM HotSwap is limited tomethod bodies.OSGi is invasive andstate-unaware
  42. 42. so what?
  43. 43. your managers will love *Rebelin production
  44. 44. your ops will love *Rebelin production
  45. 45. That works!
  46. 46. 1> A = 20.202> self().<0.32.0>3> 5 / 0.** exception error: bad argument in anarithmetic expression in operator //2 called as 5 / 04> self().<0.36.0>5> A.206>
  47. 47. so what?
  48. 48. That works!
  49. 49. 1> bit_size(<<3:5>>).52>
  50. 50. so what?
  51. 51. That works!
  52. 52. QueueConnectionFactory connFactory = new QueueConnectionFactory();QueueConnection conn = connFactory.createQueueConnection();QueueSession session = conn.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);Queue q = new Queue("world");QueueSender sender = session.createSender(q);TextMessage msg = session.createTextMessage();msg.setText("Hello there!");sender.send(msg);QueueReceiver receiver = session.createReceiver(q);conn.start();Message m = receiver.receive();if (m instanceof TextMessage) { TextMessage txt = (TextMessage) m;}session.close();conn.close();
  53. 53. register(serv, spawn(?MODULE, loop, [])),serv ! {self(), “Hello there!”},receive {_Pid, Msg} -> …end.…loop() -> receive {From, Txt} -> … loop();
  54. 54. $ erl +P 134217727Erlang R14B04 (erts-5.8.5) [source] [64-bit][smp:8:8] [rq:8] [async-threads:0] [hipe][kernel-poll:false]Eshell V5.8.5 (abort with ^G)1> erlang:system_info(process_limit).1342177272>
  55. 55. so what?
  56. 56. import kilim.Mailbox;import kilim.Pausable;import kilim.Task;public class SimpleTask extends Task { static Mailbox<String> mb = new Mailbox<String>(); public static void main(String[] args) throws Exception { new SimpleTask().start(); Thread.sleep(10); mb.putnb("Hello "); mb.putnb("Worldn"); mb.putnb("done"); } public void execute() throws Pausable { while (true) { String s = mb.get(); if (s.equals("done")) break; System.out.print(s); } System.exit(0); }}
  57. 57. your ops will love thisin production
  58. 58. That works!
  59. 59. QueueConnectionFactory connFactory = new QueueConnectionFactory();QueueConnection conn = connFactory.createQueueConnection();QueueSession session = conn.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);Queue q = new Queue("world");QueueSender sender = session.createSender(q);TextMessage msg = session.createTextMessage();msg.setText("Hello there!");sender.send(msg);QueueReceiver receiver = session.createReceiver(q);conn.start();Message m = receiver.receive();if (m instanceof TextMessage) { TextMessage txt = (TextMessage) m;}session.close();conn.close();
  60. 60. {serv, serv@pc} ! {self(), “Hello there!”},receive {_Pid, Msg} -> …end.…loop() -> receive {From, Txt} -> … loop();
  61. 61. so what?
  62. 62. import org.gridgain.grid.*;import org.gridgain.grid.gridify.*;import org.gridgain.grid.gridify.aop.spring.*;public final class GridifyHelloWorldSessionExample { private GridifyHelloWorldSessionExample() { //ensure singleton } @Gridify(taskClass = GridifyHelloWorldSessionTask.class, timeout = 3000) public static int sayIt(String phrase) { System.out.println(phrase); return phrase.length(); } public static void main(String[] args) throws GridException { if (args.length == 0) { GridFactory.start(); } else { GridFactory.start(args[0]); } try { int phraseLen = sayIt("Hello World"); System.out.println(„number of characters is " + phraseLen + "."); } finally { GridFactory.stop(true); } }}
  63. 63. your ops will love thisin production
  64. 64. That works!
  65. 65. One GC per OS process.Complex generation management.Different GC stategies.Stop the world situations possible
  66. 66. One GC per Erlang process.Simple generation management.(Mostly) one GC stategy.Stop the world situations unlikely.
  67. 67. so what?
  68. 68. That works!
  69. 69. Hey, dude.So do you imply Erlang is betterthan Java for everything?
  70. 70. Erlang dude: body() -> [ #h1 { text="My Simple Application" }, #label { text="What is your name?" }, #textbox { }, #button { text="Submit" } ].
  71. 71. Java dude: LOL at you
  72. 72. Ruby on rails dude: ROFL at yall
  73. 73. Erlang dude:calc_month(S) -> L = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"], find_ix(L, S, 1).
  74. 74. Java dude: LOL at you
  75. 75. Erlang dude:Doing number crunching, you wouldcompletely utilize the available cores withfew (as many) threads.Erlang is for time sharing and doesntlike long blocking processes.
  76. 76. Java dude: LOL at you
  77. 77. C dude: ROFL at yall
  78. 78. Thank you
  79. 79. Some code examples were taken from public blogs / sites Most images originate from istockphoto.com except few ones takenfrom Wikipedia and product pages or generated through public online generators

×