Wednesday, March 27, 2024

Tuesday, April 25, 2017

Installing angular and node.js

This is painful to install angular on ubuntu. I'd like to do it in a fancy way using npm tool. The instruction says that there are ony a few things to do:

install nodejs
install npm
install angular via npm

Okay.... I'm starting with apt-get update, apt-get install nodejs, apt-get install npm, .
And then I see versions conflicts, unexpected errors on creating angular project etc.

I had to uninstall all the packages and start from the very beggining,
Fortunately I found a nice explanation how to install it:

https://www.digitalocean.com/community/tutorials/node-js-ubuntu-14-04-ru

It's better to skip the first section and just consequentely execute commands from section 'Установка при помощи PPA'.

After you got npm installed, just run npm install -g @angular/cli

I hope your time and nerves will be saved

Wednesday, October 26, 2016

Friday, November 6, 2015

A few words about java 8 performance, sorting complexity and leetcode task


There is an easy leetcode task:

Given two strings s and t, write a function to determine if t is an anagram of s.
For example,
s = "anagram", t = "nagaram", return true.
s = "rat", t = "car", return false.
And the function signature is 
public boolean isAnagram(String s, String t) {
}
At the first glance it could be solved with two algorithms.
The first algorithm:
1. convert input strings to char arrays
2. sort char arrays
3. compare arrays symbol-by-symbol, if they are not identical return false, otherwise we have valid anagram and must return true
Coplexity of the first algorithm equals to complexety of sorting char array which "offers O(n log(n)) performance" 

The second algorithm:
1. Iterate through all symbols of the 's' string and put each symbol to the map where key is the symbol itself and the value is the counter (if we met a symbol we need to increment the counter)
2. Iterate through all symbols of the 't' string and decrement the counter for each symbol in the map 
3. Iterate through all map values and check if counter equals '0' for every symbol (map key), it means that we got valid anagram
Complexity of the second algorithm equals to complexity of iterating through the arrays and symbol-counter map which is no more than O(n).
Looks like the second solution should work faster but leetcode checker engine doesn't think so...

Tuesday, March 31, 2015

Concurrent collections: CopyOnWriteArrayList


Working with collections in a multi-thread application is a challenge. Just imagine the list which is accessible by a few threads and every thread is seeking for a chance to change the list data, that’s a typical showcase of the ConcurrentModificationException. In order to get rid of this and other problems JDK (since version 1.5) provides improved mechanisms for storing ‘Iterable’ data in multithread application.
This article is an overview of widely used concurrent collection such as CopyOnWriteArrayList

The name of the collection is very straightforward, every ‘write’ operation (add, remove, set) causes the copying and creation of the modified collection. It allows us to prevent ConcurrentModificationException as long as every thread’s iterator will have its own copy of the collection. The official Oracle documentation names such iterators as “snapshot” style iterator; this iterator “uses a reference to the state of the array at the point that the iterator was created”

This is the add operation for CopyOnWriteArrayList


public boolean add(E e) {
    final ReentrantLock lock = this.lock;
    lock.lock();
    try {
        Object[] elements = getArray();
        int len = elements.length;
        Object[] newElements = Arrays.copyOf(elements, len + 1);
        newElements[len] = e;
        setArray(newElements);
        return true;
    } finally {
        lock.unlock();
    }
}

Every time you modify collection the new copy of the whole collection is created – it’s quite expensive operation and that’s why it’s not recommended to use CopyOnWriteArrayList for frequently modified data. Another interesting method from the listing is setArray(newElements); it updates actual array and every new thread’s iterator will have updated version of the array – other thread iterators (which run in parallel) won’t be affected using their own local copies of the array.
Question: two or more threads modify the CopyOnArrayList simultaneously, what will be the result of their job?

Saturday, March 28, 2015

What is ThreadLocal?

Take a look on the following piece of code:

private int var;

public synchronized void changeVar() {
 var++;
}

Using the synchronized block we define that the var is available only for a thread which captures the monitor/lock of the synchronized block. For example, thread-A changes the value of var and leaves the block (releases monitor), after that thread-B captures the monitor and modifies the value of var changed by thread-A, var gets value 2. That’s a normal and expected behavior, but sometimes we need to have our variables with thread visibility scope.

What I mean is having var independently modified by thread-A and thread-B, if the thread-A calls changeVar method 10 times then var will have value 10 only for thread-A, thread-B may have var equals 0 if the thread has not call changeVar method; to do that we may use ThreadLocal (http://docs.oracle.com/javase/7/docs/api/java/lang/ThreadLocal.html) instance.

Monday, March 23, 2015

What is Future?



"The future depends on what you do today" M. Gandhi



Future is java interface: public interface Future<V>
A Future represents the result of an asynchronous computation.
Methods of Future interface are provided to check if the computation is complete, to wait for its completion, and to retrieve the result of the computation.  The class that implements Future might look as follows


  public class FutureImpl implements Future<String> {   

    public boolean cancel(boolean mayInterruptIfRunning) {      
      return false;
    }

    public boolean isCancelled() {      
      return false;
    }

    public boolean isDone() {     
      return false;
    }

    public String get() throws InterruptedException, ExecutionException {     
      return null;
    }

    public String get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException,
        TimeoutException {      
      return null;
    }       
  }
 

Methods of Future:
cancel() - attempts to cancel execution of this task. This attempt will fail if the task has already completed, has already been cancelled, or could not be cancelled for some other reason.
isDone() - Returns true if this task completed. Completion may be due to normal termination, an exception, or cancellation -- in all of these cases, this method will return true
get() - Waits if necessary for the computation to complete, and then retrieves its result.
get(long timeout, TimeUnit unit) - Waits if necessary for at most the given time for the computation to complete, and then retrieves its result, if available