воскресенье, 29 июля 2018 г.

JMM - Java memory model

JMM
An archtecture's memory model tells programs what guarantees they can expect from the memory system, and specifies the special instructions required (called memory barriers) to get the additional memory coordination guarantees required when sharing data.

The JMM defines a partial ordering called happens-before on all actions within the program. To guarantee that the thread executing action B can see the results of action A, there must be a happens-before relationship between A and B. In the absence of a happens-before ordering between two operations, the JVM is free to reorder them as is pleases.

The rules for happen-before are:

Program order rule. Each action in a thread happens-before every action in that thread that comes later in the program order.

Monitor lock rule. An unlock on a monitor lock happens-before every subsequent lock on that same monitor lock.

Volatile variable rule. A write to a volatile field happens-before every subsequent read of that same field.

Thread start rule. A call to Thread.start on a thread happens-before every action in the started thread.

Thread termination rule. Any action in a thread happens-before any other thread detects that thread has terminated, either by successfully return from Thread.join or by Thread.isAlive returning false.

Interruption rule. A thread calling interrupt on another thread happens-before the interrupted thread detects the interrupt.

Finalizer rule. The end of a constructor for an object happens-before the start of the finalizer for that object.

Transitivity. If A happens-before B, and B happens-before C, then A happens-before C.

воскресенье, 22 июля 2018 г.

Failure at job interview

What to do if you got rejected after the interview or you've just failed it?

Do not despair. Do not take rejection as your tragedy. Life is not only success. Often there are failures. This is not good or bad. This is just a norm of life.

After the interview try to understand which questions you couldn't answer?

Interview is a good opportunity to check your knowledge as well as to understand what the company is all about you are going to work on?

After you could identify your gaps in knowledge you can learn and fix it. Every subsequent interview increase your chances for success.

After every interview you increase the knowledge of market needs. In the end you'll land your job.

воскресенье, 8 июля 2018 г.

Concurrent collections. Java 8

Concurrent collections.

What are the reasons to use new concurrent collections when we can use old plain collections using wrappers like Collections.synchronized(List/Set/Map)? The problem in this case will be that all accesses to the collection will use one lock. In its turn this will slow down performance.

We can ask what is the price in this case? For example take a look at HashTable and ConcurrentHashMap by the following link: https://www.ibm.com/developerworks/java/library/j-jtp07233/index.html.

Here are the results:
Threads    ConcurrentHashMap    Hashtable
1    1.00    1.03
2    2.59    32.40
4    5.58    78.23
8    13.21    163.48
16    27.58    341.21
32    57.27    778.41

Absolute numbers are not important but it is more valid to compare relative numbers.

What can we do about it? Maybe it will be better to write our own implementation of concurrent collection? It it possible but hard to achieve and more over there are already good implementations. Many useful concurrent collections are located at  java.util.concurrent package.

Concurrent collections make synchronized collections largely obsolete.

That way instead of HashMap one can use ConcurrentHashMap.
In case when a number of search iterations outnumbers the number of adding or removing operations one can use CopyOnWriteArrayList instead of ArrayList.

As for the Queue implementations there are a lot of implementations:

    1. LinkedBlockingQueue — an optionally bounded FIFO blocking queue backed by linked nodes. An optionally-bounded blocking queue based on linked nodes.  Linked queues typically have higher throughput than array-based queues but less predictable performance in most concurrent applications. The optional capacity bound constructor argument serves as a way to prevent excessive queue expansion. The capacity, if unspecified, is equal to Integer.MAX_VALUE. Linked nodes are dynamically created upon each insertion unless this would bring the queue above capacity.
   
    2. ArrayBlockingQueue — a bounded FIFO blocking queue backed by an array. A bounded blocking queue backed by an array.
   
    3. ConcurrentLinkedQueue - An unbounded thread-safe queue based on linked nodes. This queue orders elements FIFO (first-in-first-out). This implementation employs an efficient non-blocking algorithm based on one described in Simple, Fast, and Practical Non-Blocking and Blocking Concurrent Queue Algorithms by Maged M. Michael and Michael L. Scott.
   
    It is not obvious which implementation to use? It depends. One should choose the implementation based on tests.
   
    4. PriorityBlockingQueue — an unbounded blocking priority queue backed by a heap. An unbounded blocking queue that uses the same ordering rules as class PriorityQueue and supplies blocking retrieval operations.

    5. DelayQueue — a time-based scheduling queue backed by a heap. An unbounded blocking queue of Delayed elements, in which an element can only be taken when its delay has expired. 
   
    6. SynchronousQueue — a simple rendezvous mechanism that uses the BlockingQueue interface. Synchronous queues are similar to rendezvous channels used in CSP and Ada. They are well suited for handoff designs, in which an object running in one thread must sync up with an object running in another thread in order to hand it some information, event, or task.

 7. In JDK 7, TransferQueue is a specialized BlockingQueue in which code that adds an element to the queue has the option of waiting (blocking) for code in another thread to retrieve the element. TransferQueue has a single implementation:

    LinkedTransferQueue — an unbounded TransferQueue based on linked nodes. This implementation outperforms SynchronousQueue by factor of 3 to 14. See http://cs.oswego.edu/pipermail/concurrency-interest/2009-February/005886.html.
   
Deques and work stealing.
    Just as blocking queues lend themselves to the producer-consumer pattern, deques lend themselves to a related pattern called work stealing.

четверг, 5 июля 2018 г.

Java. How to start learning threads.

There are a lot of different ways to start learning Java threads.
Here is my approach to learn threads:
  1. Read the Java language tutorials on concurrency at https://docs.oracle.com/javase/tutorial/essential/concurrency/index.html.
  2. Learn basic constructs like synchronized and volatile.
  3. Learn about Dinning philosophers problem.
  4. Read Effective Java Programming Language guide 3rd edition section 11 Concurrency:
    1. Item 78. Synchronize access to shared mutable data
    2. Item 79. Avoid excessive synchronization
    3. Item 80. Prefer executors, tasks and streams to threads
    4. Item 81. Prefer concurrency utilities to wait and notify
    5. Item 82. Document thread safety
    6. Item 83. Use lazy initialization judiciously
    7. Item 84. Don't depend on the thread scheduler
  5. Try to read Java Concurrency in Practice.
I'm not sure I have covered everything, but it is a good ground to start with.
Regards.

воскресенье, 1 июля 2018 г.

Java synchronized keyword

Java multithreading has 2 key aspects - visibility and automicity.

  • For synchronization in Java one can use synchronized keyword. 
  • Keyword synchronized is not equivalent to atomic, but synchronization can be used to achieve atomicity. 
  • When subclassing a class overridden method should also define synchronized in its signature. 
  • A synchronized method can call another synchronized method on its own instance.