Tuesday, 9 October 2018

  • Creational design patterns are design patterns that deal with object creation mechanisms, trying to create objects in a manner suitable to the situation
  • The basic form of object creation could result in design problems or in added complexity to the design. Creational design patterns solve this problem by somehow controlling this object creation.
  • Creational design patterns are composed of two dominant ideas.
    • Encapsulating knowledge about which concrete classes the system uses.
    • Hiding how instances of these concrete classes are created and combined.
  • Creational design patterns are further categorized as
    • Object-creational patterns
      • Object-creational patterns deal with Object creation.
      • Object creation to another object
    • Class-creational patterns
      • Class-creational patterns deal with Class-instantiation.
      • Object creation to subclasses.
  • Five well-known design patterns that are parts of creational patterns are the
    • Builder pattern
      • Separate the construction of a complex object from its representation so that the same construction process can create different representations
    • Factory method pattern
      • Centralize creation of an object of a specific type choosing one of several implementations
    • Abstract factory pattern
      • A class requests the objects it requires from a factory object instead of creating the objects directly
    • Singleton pattern
      • Restrict instantiation of a class to one object
    • Prototype pattern
      • Used when the type of objects to create is determined by a prototypical instance, which is cloned to produce new objects
    • Dependency Injection pattern
      • A accepts the objects it requires from an injector instead of creating the objects directly

Friday, 5 October 2018


  • Spring Boot is a Spring framework module which provides RAD (Rapid Application Development) feature to the Spring framework.
  •  It is highly dependent on the starter templates feature
  • Starter Template
    • Spring Boot starters are templates that contain a collection of all the relevant  dependencies that are needed to start a particular functionality. 
    • For example, If you want to create a Spring WebMVC application then in a traditional setup, you would have included all required dependencies yourself. It leaves the chances of version conflict which ultimately result in more runtime exceptions.
    • With String boot, to create MVC application all you need to import is spring-boot-starter-web dependency.
    •  We do not need to provide version information into child dependencies. All versions are resolved in relation to version of parent starter
  


  •  Bootstrap the application
    • To run the application, we need to use @SpringBootApplication annotation. Behind the scenes, that’s equivalent to @Configuration, @EnableAutoConfiguration, and @ComponentScan together.
    • It enables the scanning of config classes, files and load them into spring context. In below example, execution start with main() method. It start loading all the config files, configure them and bootstarp the application based on application properties in application.properties file in /resources folder.
    • YlbSBA.java
    • @ComponentScan({ "com.ylb.web", }) @SpringBootApplication public class YlbSBA { public static void main(String[] args) { SpringApplication.run(YlbSBA.class, args); } }
      application.properties

      ### Server port ######### server.port=8080 ### Context root ######## server.contextPath=/home

    • To execute the application, you can run the main() method from IDE such eclipse, or you can build the jar file and execute from command prompt.
    • $ java -jar spring-boot-demo.jar


  • Embedded server
    • Spring boot applications always include tomcat as embedded server dependency. It means you can run the Spring boot applications from the command prompt without needling complex server infrastructure.
    • You can exclude tomcat and include any other embedded server if you want. Or you can make exclude server environment altogether. It’s all configuration based.
    • For example, below configuration exclude tomcat and include jetty as embedded server.
    • To remove embedded tomcat and deploy in external server
      • pom.xml
        • Make starter -tomcat dependency to provided
                       
      • YLBSBA.java
        • Ovrride configure methode from SpringBootServletInitializer
        • @ComponentScan({ "com.ylb.web", }) @SpringBootApplication public class YlbSBA extends SpringBootServletInitializer { public static void main(String[] args) { SpringApplication.run(YlbSBA.class, args); } /** * spring boot dedicated tomcat config step #2 */ @Override protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) { return builder.sources(YlbSBA.class); } }

  • Spring boot autoconfiguration
    • Autoconfiguration is enabled with @EnableAutoConfiguration annotation. Spring boot auto configuration scans the classpath, finds the libraries in the classpath and then attempt to guess the best configuration for them, and finally configure all such beans.
  • Actuator
    • Spring Boot Actuator help you monitor and manage your application health when you push it to production.
    • You can choose to manage and monitor your application by using HTTP endpoints.
  • Advantages of Spring boot
    • Spring boot helps in resolving dependency conflict. It identifies required dependencies and import them for you.
    • It has information of compitable version for all dependencies. It minimizes the runtime classloader issues.
    • It’s “opinionated defaults configuration” approach helps you in configuring most important pieces behind the scene. Override them only when you need. Otherwise everything just works, perfectly. It helps in avoiding boilerplate code, annotations and XML configurations.
    • It provides embedded HTTP server Tomcat so that you can develop and test quickly.
    • It has excellent integration with IDEs like eclipse and intelliJ idea.
  •  Spring Cloud?
    • It provides microservices infrastructure like provide use services such as Service Discovery, Configuration server and Monitoring.
    • Eureka is the Netflix Service Discovery Server and Client. Eureka Server is using Spring Cloud.
    • @EnableEurekaServer annotation uses to create  eureka server.
    • @EnableDiscoveryClient annotation also allows us to query Discovery server to find miroservices.
    • Spring provide smart RestTemplate for service discovery and load balancing by using @LoadBalanced annotation with RestTemplate instance.
    • @EnableEurekaClient makes Micro-service as EurekaClient

Wednesday, 3 October 2018


  • A Thread is a single sequential flow control within a program.
  • Multi Threading  means that you could have multiple threads of execution inside the same program.
  • Creating and Starting Java Threads
    • By implementing Runnable Interface
    • By implementing Callable Interface
    • By Extending Thread Class
  • Race Conditions and Critical Sections
    • The problems arise when multiple threads access the same resources.
    • In fact, problems only arise if one or more of the threads write to same resource.
  • Thread Safety and Shared Resources
    • Code that is safe to call by multiple threads simultaneously is called thread safe.
    • Race condition only occur when multiple threads update shared resources.Therefore it is important to know what resources Java threads share when executing.
    • Local Variables
      • Local variables are stored in each thread's own stack. That means that local variables are never shared between threads and it is thread safe.
      • That also means that all local primitive variables are thread safe.
    • Local Object References
      • All objects are stored in the shared heap.
      • If an object created locally never escapes the method it was created in, it is thread safe.
    • Object Members
      • Object members are stored on the heap along with the object.
      • if two threads call a method on the same object instance and this method updates object members, the method is not thread safe.




  • Tuesday, 2 October 2018



    • How to create Immutable List in java?
      • Once your lis has been initialized, you can do
      • list = Collections.unmodifiableList(list);
    • Why ConcurrentHashMap does not allow null keys and null values ?
      • We all know that ConcurrentHashMap (optimized version of  Hashtable) doesn't allow null key or null values. 
      • The reason behind this implementation is due to ambiguity nature of the ConcurrentMap (ConcurrentHashMap & ConcurrentSkipListMaps) when it comes to multithreading environment. 
      • The main reason is that if map.get(key) returns null, we can't detect whether the key explicitly maps to null vs the key isn't mapped.
      • In ConcurrentHashMap, It might be possible that key 'K' might be deleted in between the get(k) and containsKey(k) calls.
      • if (concurrentHashMap.containsKey(k)) { return concurrentHashMap.get(k); } else { throw new KeyNotPresentException(); }
      • The above example i am  explaining with two thread(1 & 2). In Line 2, after checking thread 1 with the key "K" in concurrentHashMap(Line 1 -contains some value for the key "K"),  it will returns null (if thread 2 removed the key 'K' from concurrentHashMap). Instead of throwing KeyNotPresentException , it actually returns null.
      • As a result, the code will return null as opposed to KeyNotPresentException (Expected Result if key is not present).
    • When to use ConcurrentHashMap in Java?
      • ConcurrentHashMap is best suited when you have multiple readers and few writers
      • If writers greater than readers, or writer is equal to reader, then performance of ConcurrentHashMap effectively reduces to synchronized map or Hashtable.
      •  Performance of CHM drops, because you got to lock all portion of Map, and effectively each reader will wait for another writer, operating on that portion of Map. 
      • ConcurrentHashMap is a good choice for caches, which can be initialized during application start up and later accessed my many request processing threads.
      •  As javadoc states, CHM is also a good replacement of Hashtable and should be used whenever possible, keeping in mind, that CHM provides slightly weeker form of synchronization than Hashtable.
    • How to design a good key for HashMap?
      • If a key()  is overridden  then the corresponding hashcode() must be overridden.
      • Key’s hash code is used primarily in conjunction to its equals() method, for putting a key in map and then searching it back from map. So if hash code of key object changes after we have put a key-value pair in map, then its almost impossible to fetch the value object back from map. It is a case of memory leak. To avoid this, map keys should be immutable. These are few things to create an immutable of class.
      • This is the main reason why immutable classes like String, Integer or other wrapper classes are a good key object candidate.
    • Difference between HashMap and ConcurrentHashMap
      • In concurrentHashMap, the difference lies in internal structure to store these key-value pairs. ConcurrentHashMap has an addition concept of segments. It will be easier to understand it you think of one segment equal to one HashMap [conceptually]. A concurrentHashMap is divided into number of segments [default 16] on initialization. ConcurrentHashMap allows similar number (16) of threads to access these segments concurrently so that each thread work on a specific segment during high concurrency.
      • This way, if when your key-value pair is stored in segment 10; code does not need to block other 15 segments additionally. This structure provides a very high level of concurrency.
    • Difference between HashMap and Collections.synchronizedMap(HashMap)?
      • Sunchronized hash map can be accessed by only one thread at a time.
    • Difference between ConcurrentHashMap and Collections.synchronizedMap( HashMap )?
      • ConcurrentHashMap is consist of internal segments which can be viewed as independent HashMaps, conceptually. All such segments can be locked by separate threads in high concurrent executions. In this way, multiple threads can get/put key-value pairs from ConcurrentHashMap without blocking/waiting for each other.
      • In Collections.synchronizedMap(), we get a synchronized version of HashMap and it is accessed in blocking manner. This means if multiple threads try to access synchronizedMap at same time, they will be allowed to get/put key-value pairs one at a time in synchronized manner.
    • Difference between HashTable and Collections.synchronized(HashMap)?
      • Both are synchronized version of collection. Both have synchronized methods inside class. Both are blocking in nature i.e. multiple threads will need to wait for getting the lock on instance before putting/getting anything out of it.
      • So what is the difference. Well, NO major difference for above said reasons. Performance is also same for both collections.
      • Only thing which separates them is the fact HashTable is legacy class promoted into collection framework. It got its own extra features like enumerators.
    • How to convert an array of String to arraylist?
    • String[] words = {“RAKESH”, “RAVI”,”AZAR”}; List wordList = Arrays.asList(words); //Now you can iterate over the list
    • How to reverse the list?
    • Collections.reverse(list);
    • Can a null element added to a TreeSet or HashSet?
      • Yes
      • A null element can be added only if the Set contains one element,  because when a second element is added then as per set definition a check is made to check duplicate value and comparison with null element will throw NullPointerException.
    • What are IdentityHashMap and WeakHashMap?
      • IdentityHashMap is similar to HashMap except that it uses reference equality when comparing elements. IdentityHashMap class is not a widely used Map implementation. While this class implements the Map interface, it intentionally violates Map’s general contract, which mandates the use of the equals() method when comparing objects. IdentityHashMap is designed for use only in the rare cases wherein reference-equality semantics are required.
      • WeakHashMap is an implementation of the Map interface that stores only weak references to its keys. Storing only weak references allows a key-value pair to be garbage collected when its key is no longer referenced outside of the WeakHashMap. This class is intended primarily for use with key objects whose equals methods test for object identity using the == operator. Once such a key is discarded it can never be recreated, so it is impossible to do a look-up of that key in a WeakHashMap at some later time and be surprised that its entry has been removed.
    • What are different Collection views provided by Map interface?
      • key set view
      • value set view
      • entry set view
    • How to make a collection read only?
    • Collections.unmodifiableList(list);
    • TreeMap sorted based on the ?
      • Key
    • How to add objects in tree set?
      • While creating the set pass comparator class’s objects as argument.
      • The comparator class’s comparator method should be overridden with needed logic(use properties of the pojo object)
      public static void main(String[] args) { Set set = new TreeSet(new ComparatorSk()); set.add(new Student(2,"sonu")); set.add(new Student(5,"lion")); set.add(new Student(6,"aval")); set.add(new Student(9,"mallan")); set.add(new Student(8,"bilal")); Iterator ir = set.iterator(); while(ir.hasNext()) { Student obj = ir.next(); System.out.println("Id = " +obj.getId()+ " Name = " +obj.getName()); } } public class ComparatorSk implements Comparator { public int compare(Student o1, Student o2) { if(o1.getId() > o2.getId()){ return 1; } else { return -1; } } }
    • Why doesn't Collection extend Cloneable and Serializable?
      • Many Collection implementations (including all of the ones provided by the JDK) will have a public clone method, but it would be mistake to require it of all Collections. For example, what does it mean to clone a Collection that's backed by a terabyte SQL database? Should the method call cause the company to requisition a new disk farm? Similar arguments hold for serializable
      • If the client doesn't know the actual type of a Collection, it's much more flexible and less error prone to have the client decide what type of Collection is desired, create an empty Collection of this type, and use the addAll method to copy the elements of the original collection into the new one.
    • Why Map interface doesn’t extend Collection interface?
      • Although Map interface and it’s implementations are part of Collections Framework, Map are not collections and collections are not Map. Hence it doesn’t make sense for Map to extend Collection or vice versa.
      • If Map extends Collection interface, then where are the elements? Map contains key-value pairs and it provides methods to retrieve list of Keys or values as Collection but it doesn’t fit into the “group of elements” paradigm
    • What is an Iterator?
      • Iterator interface provides methods to iterate over any Collection. 
      •  We can get iterator instance from a Collection using iterator() method.
      • Iterator  always denies other threads to modify the collection object which is being iterated by it.
      •  Iterators allow the caller to remove elements from the underlying collection during the iteration.
    • What is difference between Enumeration and Iterator interface?
      • Enumeration is twice as fast as Iterator and uses very less memory. 
      • Enumeration is very basic and fits to basic needs. But Iterator is much safer as compared to Enumeration because it always denies other threads to modify the collection object which is being iterated by it.
      • Iterators allow the caller to remove elements from the underlying collection that is not possible with Enumeration. 
    • What is different between Iterator and ListIterator?
      • We can use Iterator to traverse Set and List collections whereas ListIterator can be used with Lists only.
      • Iterator can traverse in forward direction only whereas ListIterator can be used to traverse in both the directions.
      • ListIterator inherits from Iterator interface and comes with extra functionalities like adding an element, replacing an element, getting index position for previous and next elements.
    • What do you understand by iterator fail-fast property?
      • Iterator fail-fast property checks for any modification in the structure of the underlying collection everytime we try to get the next element. If there are any modifications found, it throws ConcurrentModificationException
      • All the implementations of Iterator in Collection classes are fail-fast by design except the concurrent collection classes like ConcurrentHashMap and CopyOnWriteArrayList.
      •  Fail-Fast iterators immediately throw ConcurrentModificationException if there is structural modification of the collection. 
      •  Structural modification means adding, removing or updating any element from collection while a thread is iterating over that collection.
      •  Iterator on ArrayList, HashMap classes are some examples of fail-fast Iterator.
      •  How Fail Fast Iterator works ?
        • To know whether the collection is structurally modified or not, fail-fast iterators use an internal flag called modCount(list.modeCount) which is updated each time a collection is modified.
        • Fail-fast iterators checks the modCount flag whenever it gets the next value (i.e. using next() method), and if it finds that the modCount has been modified after this iterator has been created, it throws ConcurrentModificationException.
    • What is difference between fail-fast and fail-safe?
      • Iterator fail-safe property work with the clone of underlying collection, hence it’s not affected by any modification in the collection.
      • By design, all the collection classes in java.util package are fail-fast whereas collection classes in java.util.concurrent are fail-safe.
      • Fail-fast iterators throw ConcurrentModificationException whereas fail-safe iterator never throws ConcurrentModificationException.
    • How to avoid ConcurrentModificationException while iterating a collection?
      • We can use concurrent collection classes to avoid ConcurrentModificationException while iterating over a collection, for example CopyOnWriteArrayList instead of ArrayList.
    • Why there are no concrete(particular) implementations of Iterator interface?
      • Iterator interface declare methods for iterating a collection but it’s implementation is responsibility of the Collection implementation classes.
      • Every collection class that returns an iterator for traversing has it’s own Iterator implementation nested class.
    • What is UnsupportedOperationException?
      • UnsupportedOperationException is the exception used to indicate that the operation is not supported. It’s used extensively in JDK classes, in collections framework java.util.Collections.
      • UnmodifiableCollection throws this exception for all add and remove operations.
    • What is difference between ArrayList and LinkedList?
      • ArrayList is an index based data structure backed by Array, so it provides random access to it’s elements with performance as O(1) but LinkedList stores data as list of nodes where every node is linked to it’s previous and next node. So even though there is a method to get the element using index, internally it traverse from start to reach at the index node and then return the element, so performance is O(n) that is slower than ArrayList.
      • Insertion, addition or removal of an element is faster in LinkedList compared to ArrayList because there is no concept of resizing array or updating index when element is added in middle.
      • LinkedList consumes more memory than ArrayList because every node in LinkedList stores reference of previous and next elements.
    • Which collection classes provide random access of it’s elements?
      • ArrayList, HashMap, TreeMap, Hashtable classes provide random access to it’s elements. 
    • What is EnumSet?
      • java.util.EnumSet is Set implementation to use with enum types. All of the elements in an enum set must come from a single enum type that is specified, explicitly or implicitly, when the set is created.
    • Which collection classes are thread-safe?
      • Vector, Hashtable and Stack are synchronized classes, so they are thread-safe and can be used in multi-threaded environment.
      • Java 1.5 Concurrent API included some collection classes that allows modification of collection while iteration because they work on the clone of the collection, so they are safe to use in multi-threaded environment. 
    • What is BlockingQueue?
      • java.util.concurrent.BlockingQueue is a Queue that supports operations that wait for the queue to become non-empty when retrieving and removing an element, and wait for space to become available in the queue when adding an element.
      • Java provides several BlockingQueue implementations such as ArrayBlockingQueue, LinkedBlockingQueue, PriorityBlockingQueue, SynchronousQueue etc.
      • Also BlockingQueue used for producer-consumer problem.
    •  What is Collections Class?
      • ajava.util.Collections is a utility class consists exclusively of static methods that operate on or return collections. 
      • This class contains methods for collection framework algorithms, such as binary search, sorting, shuffling, reverse etc. 
    • What is Comparable and Comparator interface?
      • Comparable interface has compareTo(T obj) method which is used by sorting methods. We should override this method in such a way that it returns a negative integer, zero, or a positive integer if “this” object is less than, equal to, or greater than the object passed as argument.
      • Comparator interface compare(Object o1, Object o2) method need to be implemented that takes two Object argument, it should be implemented in such a way that it returns negative int if first argument is less than the second one and returns zero if they are equal and positive int if first argument is greater than second one.
      • Comparable helps in preserving default natural sorting, whereas Comparator helps in sorting the elements in some special required sorting pattern.
    • How can we create a synchronized collection from given collection?
    • use Collections.synchronizedCollection(Collection c)
    • What is Big-O notation? Give some examples?
      • The Big-O notation describes the performance of an algorithm in terms of number of elements in a data structure
      • ArrayList get(index i) is a constant-time operation and doesn’t depend on the number of elements in the list. So it’s performance in Big-O notation is O(1).
      • Example 2: A linear search on array or list performance is O(n) because we need to search through entire list of elements to find the element. 
    • Why can’t we write code as List<Number> numbers = new ArrayList<Integer>();?
      • Generics doesn’t support sub-typing because it will cause issues in achieving type safety. That’s why List<T> is not considered as a subtype of List<S> where S is the super-type of T. To understanding why it’s not allowed, let’s see what could have happened if it has been supported.
    • Why can’t we create generic array? or write code as List<Integer>[] array = new ArrayList<Integer>[10];
      • We are not allowed to create generic arrays because array carry type information of it’s elements at runtime. 
      • This information is used at runtime to throw ArrayStoreException if elements type doesn’t match to the defined type. Since generics type information gets erased at runtime by Type Erasure, the array store check would have been passed where it should have failed. Let’s understand this with a simple example code


    • Java collections framework belongs to java.util package       
    •          Collection's works a bit like arrays, except their size can change dynamically, and they have more advanced behaviour than arrays.
    •      There are two "groups" of interfaces: Collection's and  Map's


    1.    Collection
      1. List
        1. The java.util.List interface is a subtype of the java.util.Collection interface
        2. It represents a n ordered list of objects, meaning you can access the elements of a List in a specific order, and by an index too.
        3. You can add an element anywhere in the list, change an element anywhere in the list, or remove an element from any position in the list.
        4. You can also add the same element more than once to a List.
        5. The List Implementations are,
          1. Arraylist
          2. Vector
          3. Linkedlist
      2. Set
        1. It represents set of objects, meaning each element can only exists once in a Set.
        2. Internal datas structure of set is hashmap and unique key feature of hashmap made set accept only unique objects 
        3. The List Implementations are,
          1. HashSet
          2. LinkedHashSet
          3. TreeSet
      3. Queue
        1. A queue is also ordered, but you'll only ever touch elements at one end. All elements get inserted at the "end" and removed from the "beginning" (or head) of the queue. You can find out how many elements are in the queue, but you can't find out what, say, the "third" element is. You'll see it when you get there.
        2. The Queue Implementations are,
          1. Linkedlist
          2. PriorityQueue 
      4. Dequeue
        1. Deque is short for "double ended queue". With an ordinary queue, you add things to one end and take them from the other. With a double ended queue, you can add things to either end, and take them from either end.
        2. The Dequeue Implementations are
          1. Linkedlist
          2. ArrayDeque
      5. Stack
        1.  Stack is liner type data structure, i.e. they are arranging in liner manner. In stack whatever is stored first it comes out last. It works in LIFO manner(Last in first out)
        2. In stack you can’t add element in between. They are like a stack of coins, i.e. if you want to take the last coin, then all the upper coins have to be removed one by one.
    2.    Map
      1. Map Interface Store data as key value pair
        1. Hashmap
        2. Hashtable
        3. Treemap
        4. Linked Hashmap
    • Arraylist
      • ArrayList is implemented as a resizable array. It's elements can be accessed directly by using the get and set methods, since ArrayList is essentially an array.
      • When an element is inserted into an ArrayList, the object will need to expand its internal array if it runs out of room. the ArrayList increases its array size by 50 percent.
    • Vector
      • The chief difference from ArrayList is that its methods are synchronized (ArrayList's are not). That means it is easier to use in multi-threaded environments, but it does incur the synchronization overhead.
      • When an element is inserted into  a Vector, the object will need to expand its internal array if it runs out of room. A Vector defaults to doubling the size of its array
    • Linkedlist
      •  A linked list is a data structure consisting of a group of nodes which together represent a sequence. Each     node is composed of a data and a reference to the next node in the sequence. This structure allows for efficient insertion or removal of elements from any position in the sequence. 
      • In a singly linked list each node has only one link which points to the next node in the list.
    • HashSet
      • It makes no guarantees about the sequence of the elements when you iterate them
    • LinkedHashSet
      • LinkedHashSet differs from HashSet by guaranteeing that the order of the elements during iteration is the same as the order they were inserted into the LinkedHashSet.
    • TreeSet
      • Guarantees the order of the elements when iterated, but the order is the sorting order of the elements.
    • PriorityQueue 
      • Stores its elements internally according to their natural order (if they implement Comparable), or according to a Comparator passed to the PriorityQueue.
    • ArrayDeque
      • ArrayDeque stores its elements internally in an array. If the number of elements exceeds the space in the array, a new array is allocated, and all elements moved over. In other words, the ArrayDeque grows as needed, even if it stores its elements in an array
    • Stack
      • A Stack is a data structure where you add elements to the "top" of the stack, and also remove elements from the top again.
      • This is also referred to as the "Last In First Out (LIFO)" principle.
    • Hashmap
      • HashMap maps a key and a value. It does not guarantee any order of the elements stored internally in the map
    • Hashtable
      • Hashtable is synchronized
      • Hashtable does not allow null keys or values.
    • Treemap
      • TreeMap also maps a key and a value. Furthermore it guarantees the order in which keys or values are iterated - which is the sort order of the keys or values.
    • Linked Hashmap
      • Having order when iterate

    Wednesday, 26 September 2018


    Consider there are two threads,
    Even Thread
    - Print only Even numbers
    Odd Thread
    - Print only Odd numbers
    Print numbers from 1 to 50 by switching Odd and Even Threads,
    Approach:
    step 1. Create each threads with synchronized block
    step 2. Create Monitor object with shared thread status and shared number
    step 3. loop through mo.number and wait or execute based on the shared thread status
     
          Even.java  
    public class Even implements Runnable { private static MonitorObject mo = new MonitorObject(); public Even(MonitorObject mo) { this.mo = mo; } public void run() { try { synchronized (mo) { while (mo.number <= 50) { if (!mo.isEven) { mo.wait(); } else { if (mo.number % 2 == 0) { System.out.println(mo.number); } mo.number++; mo.isEven = false; mo.notifyAll(); } } } } catch (InterruptedException e) { e.printStackTrace(); } } }
     
          Odd.java  
    public class Odd implements Runnable { private static MonitorObject mo = new MonitorObject(); public Odd(MonitorObject mo) { this.mo = mo; } public void run() { try { synchronized (mo) { while (mo.number <= 50) { if (mo.isEven) { mo.wait(); } else { if (mo.number % 2 != 0) { System.out.println(mo.number); } mo.isEven = true; mo.number++; mo.notifyAll(); } } } } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
     
          MonitorObject.java  
    public class MonitorObject { public static boolean isEven = false; public static int number = 0; }
     
          App.java  
    public class App { private static MonitorObject mo = new MonitorObject(); public static void main(String[] args) { mo.isEven = true; Thread even = new Thread(new Even(mo)); even.start(); Thread odd = new Thread(new Odd(mo)); odd.start(); } } /* ****** OUTPUT ******** 0,1,2,3,4,5,6,7,8,9... ******* OUTPUT ******** */

    Sunday, 5 August 2018

    Spring Boot - OAuth2

    • http://javainuse.com/spring/spring-boot-oauth-authorization-code

    Search This Blog

    Contact us

    Name

    Email *

    Message *