Upgrade to Pro — share decks privately, control downloads, hide ads and more …

"synchronized" is obsolete

"synchronized" is obsolete

The "synchronized" keyword in Java allows defining critical sections of code, where shared resources must only be accessed by one thread at a time.

Since Java 5, several alternative ways of handling shared resources have sprung up, such as atomic references and map operations, backed by modern CAS operations in modern hardware.

But ultimately, new deployment environments such as kubernetes which achieve resiliency by having redundant load-balanced processes, have render this keyword obsolete, since the lock provided by it is only effective inside one JVM process.

Enrique Zamudio

February 20, 2020
Tweet

More Decks by Enrique Zamudio

Other Decks in Programming

Transcript

  1. Who? •Been programming for 25 years •19 of those spent

    on Java •Named Java Champion in 2015 •Doing backend development since 2004
  2. Map<String, List<?>> map; synchronized(this) { List<?> list = map.get(key); if

    (list == null) { list = new ArrayList<>(); map.put(key, list); } list.add(element); }
  3. Map<String, BigDecimal> map; synchronized(this) { BigDecimal num = map.get(key); if

    (num == null) { num = new BigDecimal.ZERO; } num = num.add(value); map.put(key, num); }
  4. LinkedBlockingQueue • Can take elements concurrently • Can deliver elements

    concurrently • Blocks calling thread when empty • Unblocks consumers as soon as there's something in it • Every element is delivered to exactly one consumer
  5. Thread pool Worker thread 1 Worker thread 2 Worker thread

    3 Worker thread 4 Worker thread 5 Worker thread 6 Task Task Task Task Task Task Task Task Task Task Task Task Task Task Task
  6. Thread pool Task Task Task Task Task Task Task Task

    Task Task Task Task Task Task Task Runnable Callable Future
  7. SET lock_name <random value> NX PX 30000 if (value.equals(redis.get(lock_name)) {

    redis.del(lock_name); } else { //lock is held by someone else }
  8. FencedLock • Developed by Hazelcast • Implements java.util.concurrent.locks.Lock interface •

    Raft consensus algorithm • Reentrant by default, but configurable
  9. ¿?