Monday, October 30, 2017

Maximum and Minimum values of a shared resource if shared within 5 threads

Since int is a primitive and since we want a sharable resource , so it must be a reference which needs to be shared within 5 threads.

If Integer being used, since Integer is Immutable hence any change on Integer reference will create a new Object , so it must be avoided.

Its desirable to create own NonMutableInteger reference and share the reference to multiple thread using Threadpool

/* To check the minimum and maximum value of count
 * Minimum - Nothing to be Guaranteed(Race condition can happen)
 * Maximum  - 25*/

public class ThreadMinMaxCount {
     public static void main(String[] args) {
         
          /* Integer is an Immutable class and hence not used */
          NonMutableInteger count = new NonMutableInteger(0);
          ExecutorService service = Executors.newFixedThreadPool(5);
          for (int i = 0; i < 5; i++)
              service.execute(new Task(count));
         
          System.out.println(count.i);
          service.shutdown();
     }
}

class Task implements Runnable {

     NonMutableInteger count;

     public Task(NonMutableInteger count) {
          this.count = count;
     }

     @Override
     public void run() {
          for (int i = 0; i < 5; i++)
              count.increment();
     }
}

class NonMutableInteger {
     int i;

     public NonMutableInteger(int i) {
          this.i = i;
     }

     public int getMutableInteger() {
          return i;
     }

     public void increment() {
          i++;
     }
}

Output (Run multiple times)
10
5
20

No comments:

Post a Comment