package ru.job4j.nonblock;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;

/**
 * Created on 19.09.17
 * Simple cache class.
 * @author Wamdue
 * @version 1.0
 */
public class NonBlockCache {
    /**
     * internal map.
     */
    private ConcurrentHashMap<Integer, Task> map = new ConcurrentHashMap<>();
    /**
     * version counter.
     */
    private AtomicLong version = new AtomicLong(0);

    public void add(int id, Task task) {
        this.map.putIfAbsent(id, task);
        this.inc();
    }

    /**
     * update task if it can be fount in map.
     * @param id - id to search
     * @param task - new task.
     */
    public void update(int id, Task task) {
        long temp = this.getVersion();
        if (this.map.contains(id)){
            if (temp != this.getVersion()) {
                throw new OptimisticException();
            }
            map.computeIfPresent(id, (k, v) -> task);
            this.inc();
        }
    }

    /**
     * Version show.
     * @return current version.
     */
    private long getVersion() {
        return this.version.get();
    }

    /**
     * Delete task from cache.
     * @param id - id to delete.
     */
    public void delete(int id) {
        long temp = this.getVersion();
        if (this.map.contains(id)){
            if (temp != this.getVersion()) {
                throw new OptimisticException();
            }
            map.remove(id);
            this.inc();
        }
    }

    /**
     * method to calculate version counter.
     */
    private void inc() {
        boolean updated = false;
        while (!updated) {
            long prevVersion = this.version.get();
            updated = this.version.compareAndSet(prevVersion, prevVersion + 1);
        }
    }
}

@@ -166,16 +166,19 @@
  class.%0A
+ *%0A
  * @auth
@@ -602,24 +602,31 @@
 unt in map.%0A
+     *%0A
      * @para
@@ -622,32 +622,34 @@
     * @param id 
+  
 - id to search%0A 
@@ -781,34 +781,43 @@
     
-if (this.map.contains(id))
+map.computeIfPresent(id, (k, v) -%3E 
 %7B%0A  
@@ -938,47 +938,17 @@
     
-map.computeIfPresent(id, (k, v) -%3E task
+this.inc(
 );%0A 
@@ -954,34 +954,35 @@
             
-this.inc()
+return task
 ;%0A        %7D%0A
@@ -972,32 +972,34 @@
  task;%0A        %7D
+);
 %0A    %7D%0A%0A    /**%0A
@@ -1019,16 +1019,23 @@
 n show.%0A
+     *%0A
      * @
@@ -1179,16 +1179,23 @@
  cache.%0A
+     *%0A
      * @
@@ -1333,16 +1333,17 @@
 ins(id))
+ 
 %7B%0A      

Refactor NonBlockingCache class, task #4741