Sunday, September 18, 2016

SPRING BOOT: Complete Gold Mine!

Starting from controller to JPA using Spring Data! Why didn't I find this video before!!??

Friday, September 9, 2016

JAVA MULTITHREADING: Producer-Consumer Pattern

So, imagine that we have a buffer.

The buffer can hold 10 items at once & is thread-safe in nature.

Now, a producer() method constantly populates it, another method called consumer() pulls one value out of it, every 1 second in average.

The code below is pretty interesting as this will cause both the threads to run and halt, synchronously, depending upon the state of 'queue' object.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
import java.util.Random;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

public class App{
 //This is like a buffer which can hold 10 objects; here 10 integers
 //This is a thread-safe data-structure
 private static BlockingQueue<Integer> queue = new ArrayBlockingQueue<>(10);
 
 //Main method where 2 threads are run
 //1st method runs producer() method
 //2nd method runs consumer() method
 public static void main(String[] args) throws InterruptedException {
  
  Thread t1 = new Thread(new Runnable(){//<--To run producer() method
   @Override
   public void run() {
    try {
     producer();
    } catch (InterruptedException e) {
     e.printStackTrace();
    }
   } 
  });
  
  Thread t2 = new Thread(new Runnable(){//<--To run consumer() method

   @Override
   public void run() {
    try {
     consumer();
    } catch (InterruptedException e) {
     e.printStackTrace();
    }
   }
  });
  
  t1.start();
  t2.start();
  
  t1.join();
  t2.join();//<--Actually, only one join() is enough here.
  
  System.out.println("Program ended!");
  
  
 }
 
 private static void producer() throws InterruptedException{
  Random random = new Random();
  while(true){//<--This run infinitely, to keep the queue full at all times
   queue.put(random.nextInt(100));//<--Generates integers within 100
  }
 }
 
 private static void consumer() throws InterruptedException{
  Random random = new Random();
  
  while(true){
   Thread.sleep(100);//<--Guarantees thread sleeping for 0.1s
   
   if(random.nextInt(10) == 0){//<--Generates a zero in 1 second statistically
    Integer value = queue.take();
    
    System.out.println("Taken value: " + value + "; Queue size: " + queue.size());
   }
   
  }
 }
}

JAVA: Object type Pass-By-Value vs Pass-By-Reference

The code below basically makes changes to an object inside a method, and the changes are reflected in the original object too.

This is because when we are passing an object via method arguments, we pass an alias to that object. Now, any member of the object accessed and changed inside the called method will have permanent effects.
Running the code below returns that Java passes values by reference. This is only true for object data types.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
class Ideone
{
 public static void main( String[] args ){
    Dog aDog = new Dog("Max");
    foo(aDog);

    if (aDog.getName().equals("Max")) { //true
        System.out.println( "Java passes by value." );

    } else if (aDog.getName().equals("Fifi")) {
        System.out.println( "Java passes by reference." );
    }
}

public static void foo(Dog d) {
    d.getName().equals("Max"); // true

    d.name = "Fifi";//<--One can use setters too. Same result
    d.getName().equals("Fifi"); // true
}
}
class Dog{
 public String name;
 
 public Dog(String name){
  this.name = name;
 }
 
 public String getName(){
  return this.name;
 }
 public void setName(String name){
  this.name = name;
 }
}





Now run this code. It'll return saying that Java passes by value. This is because once the control returns to main() method, the object reference aDog points to its previous assignment.



 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
class Ideone
{
 public static void main( String[] args ){
    Dog aDog = new Dog("Max");
    foo(aDog);

    if (aDog.getName().equals("Max")) { //true
        System.out.println( "Java passes by value." );

    } else if (aDog.getName().equals("Fifi")) {
        System.out.println( "Java passes by reference." );
    }
}

public static void foo(Dog d) {
    d.getName().equals("Max"); // true

    d = new Dog("Fifi");//<--This right here is limited to the scope of this function
    d.getName().equals("Fifi"); // true
}
}
class Dog{
 public String name;
 
 public Dog(String name){
  this.name = name;
 }
 
 public String getName(){
  return this.name;
 }
 public void setName(String name){
  this.name = name;
 }
}

Thursday, September 8, 2016

JAVA MULTITHREADING: Thread synchronization using Countdown Latches

Using CountDownLatch is very useful in situation where certain threads need to complete before something else can be started.
This has no timeout feature like ExecuterService's awaitTermination() method.

The latch.await() method will pass back control to the main() method only when the countDown has reached ZERO; or if the thread is interrupted.

Here we have a total of 3 threads, each one doing certain things.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class App{
 public static void main(String[] args) {
  CountDownLatch latch = new CountDownLatch(3);//<--takes 3 because 3 threads
  ExecutorService executorService = Executors.newFixedThreadPool(3);
 
  for(int i=0; i<3; i++){
   executorService.submit(new Processor(latch));// <-- passing latch by alias.
  }
  
  System.out.println("All the threads submitted! Running 3 threads at a time!");
  
  //Causes the current thread to wait until 
  //the latch has counted down to zero, unless 
  //the thread is interrupted. 
  try {
   latch.await();
  } catch (InterruptedException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  
  System.out.println("Completed!");
 }
}

class Processor implements Runnable{
 //Alias to hold latch that shall be passed through constructor
 private CountDownLatch latch;
 
 public Processor(CountDownLatch latch) {
  // TODO Auto-generated constructor stub
  this.latch = latch;
 }
 @Override
 public void run() {
  // TODO Auto-generated method stub
  System.out.println("Started!" + latch.getCount());
  
  try {
   Thread.sleep(3000);
  } catch (InterruptedException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  
  //This will count-down latch by 1.
  latch.countDown();// <-- Change made here will affect original latch.
 }
 
}

JAVA MULTITHREADING: Thread Pool Using ExecutorService class

So, let's say you want to limit the number of threads executing at once.  This can be achieved through ExecutorService class.

Context:

  1. We have a runnable class, named Processor.
  2. Inside main(), we are declaring how many threads can run at once out of a thread pool that we'll create shortly.
  3. We create a thread pool by submitting all the threads to the executerService object.
  4. Then we shutdown() the executerService, which basically means it'll no longer accept submit() requests.
  5. Finally, we wait until the code execution completes for all threads. The timeout period is given as 1 day.
  6. Once done, we print saying all the tasks were completed.
Result:
It takes all the thread submit requests in, then starts 2 at once. Once one of the thread terminates, the third one is started. Basically, not more than 2 threads can remain active at once.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class App{
 public static void main(String[] args) {
  //This here defines the max. number of threads that can run at once
  ExecutorService executorService = Executors.newFixedThreadPool(2);
  
  //Through this loop, 5 threads shall be submitted to the executor.
  for(int i=0; i<5; i++){
   executorService.submit(new Processor(i));
  }
  
  //The executer shall no longer take any more submit requests
  executorService.shutdown();
  
  //A console output indicating the same
  System.out.println("All tasks submitted!");
  
  //Blocks until all tasks have completed execution after a shutdown request, 
  //or the timeout occurs, or the current thread is interrupted, whichever happens first.
  //Kinda like using join() method for threads
  try {
   executorService.awaitTermination(1, TimeUnit.DAYS);
  } catch (InterruptedException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  
  System.out.println("All tasks completed!");
 }
 
 
}

class Processor implements Runnable{
 private int id;
 
 public Processor(int id) {
  // TODO Auto-generated constructor stub
  this.id = id;
 }
 @Override
 public void run() {
  System.out.println("STARTING " + id);
  // TODO Auto-generated method stub
  
  try {
   Thread.sleep(5000);//<-- Pretending to do some work
  } catch (InterruptedException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  System.out.println("COMPLETED " + id);
 }
 
}

JAVASCRIPT: Accessing selected value inside SELECT(dropdown) element

This is what a SELECT element looks like:


<select id= "tsoID">
  <!-- Volvo is here selected -->
  <option value="volvo" selected="selected">Volvo</option>
  <option value="saab">Saab</option>
  <option value="mercedes">Mercedes</option>
  <option value="audi">Audi</option>
</select>


It can get pretty tricky to programmatically find the 'value' of the chosen option inside <select> tag.

However, the work becomes simpler in this way:


var e1 = document.getElementById("tsoID");
var e1Value = e1.options[e1.selectedIndex].value;

Basically, find the element by ID and then get the value of the selected option by accessing at index = e1.selectedIndex

This will return 'volvo' inside e1Value.

Wednesday, September 7, 2016

JAVA MULTITHREADING: Multiple Locks Using Synchronized Code Blocks

So even 'synchronized' methods don't cut it all the time. When writing to a single resource, the aforementioned keyword does it.

The problem usually arises when there are two or more resources to write to synchronously.

Using synchronized methods only leads to racing conditions where one thread is completely halted by the execution of the other thread. This leads to double time taken for 2 resources, triple for 3 and so on.

When one resource is being written to, the other resource is free and should be accessible for R/W! This is what we'll be dealing with in this log.

Running the code below would result in 4-6 seconds depending on your computer.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class Worker {
 private Random random = new Random();
 
 
 /**
  * Two independent fields can be seen below.
  * Operation on one should not affect the operation on another
  */
 private List<Integer> list1 = new ArrayList<Integer>();
 private List<Integer> list2 = new ArrayList<Integer>();
 
 private synchronized void stageOne() { // <-- You might think this would help
  try{
   Thread.sleep(1);
  }catch(InterruptedException e){
   e.printStackTrace();
  }
  
  list1.add(random.nextInt(100));
 }
 
 private synchronized void stageTwo() {
  try{
   Thread.sleep(1);
  }catch(InterruptedException e){
   e.printStackTrace();
  }
  
  list2.add(random.nextInt(100));
 }
 public void process() {
  for(int i=0; i<1000; i++){
   stageOne();
   stageTwo();
  }
 }
 public void execute(){
  System.out.println("Starting...");
  
  long start = System.currentTimeMillis();
  Thread t1 = new Thread(new Runnable(){

   @Override
   public void run() {
    // TODO Auto-generated method stub
    process();
   }
   
  });
  t1.start();
  
  Thread t2 = new Thread(new Runnable(){

   @Override
   public void run() {
    // TODO Auto-generated method stub
    process();
   }
   
  });
  t2.start();
  
  try {
   t1.join(); // <-- This is to take control from main() and execute until done
   t2.join();
  } catch (InterruptedException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  
  long end = System.currentTimeMillis();
  
  System.out.println("Time taken = " + (end-start));
  System.out.println("List1 size = " + list1.size() + ", List2 size = " + list2.size());
 }
 
 public static void main(String[] args){
  Worker worker = new Worker();
  worker.execute();
 }
}

This time interval is too long because of the bottleneck formed by the use of synchronized methods.




********************************************************************************


Is there a way out, or a way to reduce the time interval?
Hell yes!

A very new concept -- SYNCHRONIZED BLOCKS (NOT FREAKING METHODS LIKE BEFORE)!

Execution time would be half for this one, since there are two resources being simultaneously accessed. Had there been three resources and corresponding number of threads, that is 3 threads, the time taken would be reduced by 3. NOW THAT'S A FREAKING LOT, HOMIE!


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class Worker {
 private Random random = new Random();
 
 
 /**
  * Two independent fields can be seen below.
  * Operation on one should not affect the operation on another
  */
 private List<Integer> list1 = new ArrayList<Integer>();
 private List<Integer> list2 = new ArrayList<Integer>();
 
 private void stageOne() { // <-- You might think this would help
  synchronized(list1){
   try{
    Thread.sleep(1);
   }catch(InterruptedException e){
    e.printStackTrace();
   }
   
   list1.add(random.nextInt(100));
  }
  
 }
 
 private void stageTwo() {
  synchronized(list2){
   try{
    Thread.sleep(1);
   }catch(InterruptedException e){
    e.printStackTrace();
   }
   
   list2.add(random.nextInt(100));
  }
  
 }
 public void process() {
  for(int i=0; i<1000; i++){
   stageOne();
   stageTwo();
  }
 }
 public void execute(){
  System.out.println("Starting...");
  
  long start = System.currentTimeMillis();
  Thread t1 = new Thread(new Runnable(){

   @Override
   public void run() {
    // TODO Auto-generated method stub
    process();
   }
   
  });
  t1.start();
  
  Thread t2 = new Thread(new Runnable(){

   @Override
   public void run() {
    // TODO Auto-generated method stub
    process();
   }
   
  });
  t2.start();
  
  try {
   t1.join(); // <-- This is to take control from main() and execute until done
   t2.join();
  } catch (InterruptedException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  
  long end = System.currentTimeMillis();
  
  System.out.println("Time taken = " + (end-start));
  System.out.println("List1 size = " + list1.size() + ", List2 size = " + list2.size());
 }
 
 public static void main(String[] args){
  Worker worker = new Worker();
  worker.execute();
 }
}

Monday, September 5, 2016

DOS: Kill a process on a port

1. Open CMD in Administrator/Elevated mode.
2. Run netstat -a -n -o
3. Locate the port that you want to free up and corresponding PID!
4. Kill the PID inside Task Manager!

Easy peazy!

JAVA MULTITHREADING: Thread Synchronization using 'synchronized' keyword

So imagine a situation where a single primitive type variable is being accessed concurrently by two different threads.

Here, the final value of the 'count' variable is supposed to reach 20000 at last. But it won't!

NOT without the use of  'synchronized' keyword. It can be used ONLY WITH METHODS!


Taken from a verified answer on StackOverflow:
Synchronized methods enable a simple strategy for preventing thread interference and memory consistency errors: if an object is visible to more than one thread, all reads or writes to that object's variables are done through synchronized methods.

In a very, very small nutshell: When you have two threads that are reading and writing to the same 'resource', say a variable named foo, you need to ensure that these threads access the variable in an atomic way. Without the synchronized keyword, your thread 1 may not see the change thread 2 made to foo, or worse, it may only be half changed. This would not be what you logically expect.

*******************************************************************************

The output of the below code will be 20000.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
public class App {
 
 private int count = 0;
 private synchronized void increment(){
  count++;
 }
 
 public void doWork(){
  Thread t1 = new Thread(new Runnable(){
   public void run(){
    for(int i=0; i<10000; i++){
     increment();
     System.out.println("Inside 1");
    }
   }
  });
  
  Thread t2 = new Thread(new Runnable(){
   public void run(){
    for(int i=0; i<10000; i++){
     increment();
     System.out.println("Inside 2");
    }
   }
  });
  
  t1.start();
  t2.start();
  
  try {
   t1.join();// <-- This makes main() wait until t1 is done running
   t2.join();// <-- After t1 thread completes execution, t2 makes it wait until it's done
   /**
    * It is to be noted that t1 and t2 have been running parallely and do not affect the
    * execution of one another. They only pause the execution of the method from which they
    * are called.
    */
  } catch (InterruptedException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  System.out.println("Count is " + count);
 }
 
 public static void main(String[] args){
  App app = new App();
  app.doWork();
 }
}

Sunday, September 4, 2016

C++: Creating Custom Exceptions

 #include <cmath>  
 #include <iostream>  
 #include <exception>  
 #include <stdexcept>  
 using namespace std;  

 struct MyException : public exception  
 {  
  const char * what () const throw ()  
  {  
   return "n and p should be non-negative";  
  }  
 };  

 class Calculator{  
   public:  
   int power(int n, int p){  
    if(n>=0 && p>=0){  
      return pow(n,p);  
    }else{  
      throw MyException();  
    }  
   }  
 };  

 int main()  
 {  
   Calculator myCalculator=Calculator();  
   int T,n,p;  
   cin>>T;  
   while(T-->0){  
    if(scanf("%d %d",&n,&p)==2){  
      try{  
         int ans=myCalculator.power(n,p);  
         cout<<ans<<endl;   
      }  
      catch(exception& e){  
        cout<<e.what()<<endl;  
      }  
    }  
   }  
 }  

JAVA MULTITHREADING: Basic Thread Synchronization using Volatile

This is about graceful shutdown of a thread from another thread!
Use this when you do not want threads having their own cached copies of variables!!
  • Imagine Processor class which extends Thread class. 
  • It overrides the run() method and introduces a freaking new boolean variable calling running.
  • It has another method too called shutdown().
  • Now, overridden method run() is basically a while loop running based on the value of running variable.
  • As defined using Scanner class inside main() method, once the user presses an enter key, the value of the running variable is made false and the execution of the run() method stops.

import java.util.Scanner;

public class App {
 public static void main(String[] args){
  Processor processor = new Processor();
  processor.start();
  System.out.println("Press enter to stop!");
  
  Scanner scanner = new Scanner(System.in);
  scanner.nextLine();
  processor.shutdown();
  scanner.close();
 }
}

class Processor extends Thread{
 private /*volatile*/ boolean running = true;
 
 public void run(){
  while(running){
   System.out.println("Hello");
   
   try {
    Thread.sleep(100);
   } catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
  }
 }
 
 public void shutdown(){
  running = false;
 }
}



In some cases, to optimize the execution, the JVM caches the values of variables like running.
This might lead to run() method never knowing, if at all, there’s a change in the value of running FROM ANOTHER THREAD!

This caching problem for variables can be solved by marking the variables with keyword ‘volatile’. PROBLEM SOLVED!

JAVA MULTITHREADING: Creating and starting Threads

There are altogether 3 ways to create a thread. They are as follows:
  1. By extending Thread class
  2. By implementing Runnable interface
  3. By using an anonymous class of Runnable interface type


FIRST METHOD:
As can be seen from the picture, the App class consists of a main method. 

Apart from that, it has a separate internal class called Runner which extends Thread class.

Here, it has been chosen to override the run() method of the Thread class, to do something custom for us. After printing the string, the thread sleeps for 100 milliseconds.

Inside the main() method, we have two new instances of Runner class type. Both of these invoke their start() method.


It is important to notice that start() method has been called and not the run() method defined earlier. 

This is to avoid running the method on the application’s main thread. 

Calling start() method makes sure that the runner1 object runs on a separate new thread.

The output of the above programs looks like this:






SECOND METHOD:
The body of the App class remains almost the same.

The only difference this time is that the internal class Runner IMPLEMENTS the Runnable method instead of the inheritance as in the previous case.

Here, it becomes mandatory to implement the run() method of Runnable interface.

Inside main(), two new objects get created of Thread class type AND a new Runner object is passed as parameter inside the constructor of the Thread class.



The output remains the same.



THIRD METHOD:  This probably is the best method, as it doesn't require an extra internal class definition.
This method uses anonymous class to create a new Thread.


Here, a new Thread object has been created and a Runnable type object has been passed inside t1's constructor after defining the run() method.

This is a derivation of the second method.