Friday, 19 March 2021

Attribute Directive

Attribute directives deal with changing the look and behavior of an element, component, or another directive.


When to use ?

These are used when we  want logic or events to change the appearance or behavior of the view.
When we have a UI element that will be common throughout our app, we can implement an attribute directive and share it across components and modules to avoid repeating the code for the same functionality.

Component Directive

Created with @Component Decorator.

This type of directive is the most common directive type.

Only type of directives which have a view attached i.e they have a template associated.

What are Directives ?

Directives are the Document Object Model (DOM) instruction sets, which decide how logic implementation can be done.

They add additional behavior to elements in your Angular applications.

These are Typescript class which is declared with decorator @Directive or @Component.

Based on Type of operation that can be performed , Directives are further classified into:  

Component Directive 
Attribute Directive
Structural Directive

Wednesday, 10 February 2021

Single Responsibility principle

In this article you're going to master SOLID principles of object-oriented design and architecture. These principles embody more than 40 years of academic research and industry experience, passed to us from previous generations of software engineers. Therefore, by learning SOLID, you gain universal, time-proven tools to build high-quality software.

SOLID is an acronym that stands for five different principles:

  • Single Responsibility Principle

  • Open Closed Principle

  • Liskov Substitution Principle

  • Interface Segregation Principle

  • Dependency Inversion Principle

In this course, you will learn about all five SOLID principles in detail and understand their importance. You will see how these principles manifest themselves in real-world software architecture and discover how they translate into actionable guidelines for writing clean and maintainable code. Speaking about code... SOLID code is flexible, extensible and readable. It is a joy to work with!

In addition to in-depth discussion of SOLID, in this course you will also find many interesting historical facts about the people behind these principles. These short historical references will allow you to see the bigger picture, and they will also make the course much more interesting and engaging for you.

So, if you're a professional software developer and you're serious about design, architecture and clean code, this course is for you!

What you’ll learn

  • Discover the theory behind SOLID principles
  • See common SOLID use cases
  • Learn SOLID architecture practices
  • Understand the scope of applicability of SOLID principles
  • Discover the role of abstractions in software design
  • Acquire pragmatic mindset and treat SOLID principles as tools

Are there any course requirements or prerequisites?

  • Knowledge of any object-oriented language
  • Developers who want to learn SOLID software architecture and write clean and maintainable applications

SRP:- Single Responsibility principle

Means the class should be only one reason to change, There can be more reason but at the pint of implementing we should keep this in mind as well.

If there is and , or in definition that may violate single responsibility principle. 

Wednesday, 18 December 2019

How to create thread pool executor in java

package kp;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

public class MyPooledThread extends Thread {

private BlockingQueue<Runnable> taskQueue = null;
private boolean isStopped = false;
CountDownLatch latch = null;

public MyPooledThread(BlockingQueue<Runnable> queue, CountDownLatch latch) {
taskQueue = queue;
this.latch = latch;
}

@Override
public void run() {
while (!isStopped()) {
try {
Runnable runnable = taskQueue.poll(5, TimeUnit.SECONDS);
if(runnable != null){
runnable.run();
doStop();
}
latch.countDown();
System.out.println("count down");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

public synchronized void doStop() {
this.isStopped = true;
//this.interrupt();
}

public synchronized boolean isStopped() {
return isStopped;
}
}



-----------------------------------------------------------------------------------------------------------------


package kp;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.CountDownLatch;

public class  MyThreadPoolExecuter {

BlockingQueue<Runnable> queue = null;
List<Thread> threads = new ArrayList<Thread>();
CountDownLatch latch = null;
private boolean isStopped = false;

public MyThreadPoolExecuter(int noOfThreads, BlockingQueue<Runnable> queue, CountDownLatch latch) {
this.queue = queue;
this.latch = latch;

for (int i = 0; i < noOfThreads; i++) {
Thread t = new MyPooledThread(this.queue, latch);
threads.add(t);
t.start();
}
}

public synchronized void execute(Runnable r) {
if (this.isStopped) {
new IllegalStateException("Threadpool is stopped");
}
try {
queue.put(r);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

public synchronized void stop() {
this.isStopped = true;
for (Thread thread : threads) {
((MyPooledThread)thread).doStop();
}
}
}


---------------------------------------------------------------------------------------------------------------------

package kp;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.CountDownLatch;

public class MyThreadPoolExecuterTestDrive {

public static void main(String[] args) {
CountDownLatch latch = new CountDownLatch(4);
MyThreadPoolExecuter executer = new MyThreadPoolExecuter(4,new ArrayBlockingQueue<Runnable>(4), latch);
executer.execute(()->{
System.out.println("I am thread 1");
});
executer.execute(()->{
System.out.println("I am thread 2");
});
executer.execute(()->{
System.out.println("I am thread 3");
});
executer.execute(()->{
System.out.println("I am thread 4");
});
executer.execute(()->{
System.out.println("I am thread 5");
});
try {
latch.await();
//executer.stop();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

}

Custom ConcurrentHashMap Implementation in java

package kp;

import java.util.HashMap;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock.WriteLock;

public class MyConcurrentHashMap<K, V> extends HashMap<K, V> {

private static final long serialVersionUID = 1L;

private ReentrantReadWriteLock[] lock = new ReentrantReadWriteLock[16];

public MyConcurrentHashMap() {
super();

for (int i = 0; i < 16; i++) {
lock[i] = new ReentrantReadWriteLock();
}

}

@Override
public V get(Object key) {

ReentrantReadWriteLock lock = getLock(key);
WriteLock wl = lock.writeLock();

if (lock.isWriteLocked()) {
try {
wl.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

lock.readLock().lock();
V value = super.get(key);
lock.readLock().unlock();
return value;
}

@Override
public V put(K key, V value) {

ReentrantReadWriteLock lock = getLock(key);
while (lock.getReadLockCount() > 0) {
try {
lock.readLock().wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
lock.writeLock().lock();
V val = super.put(key, value);
lock.writeLock().unlock();
return val;
}

private ReentrantReadWriteLock getLock(Object key) {
int hash = hashCode(key);
return lock[hash / 100];
}

private int hashCode(Object key) {

return (key == null ? 0 : key.hashCode() % 1600);
}

}

------------------------------------------------------------------------------------------------------------------

package kp;

public class MyConcurrentHashMapTestDrive {

public static void main(String[] args) {

MyConcurrentHashMap<Integer, String> myConcurrentHashMap = new MyConcurrentHashMap<Integer, String>();
WriteMap w1 = new WriteMap(myConcurrentHashMap);
WriteMap w2 = new WriteMap(myConcurrentHashMap);
ReadMap r1 = new ReadMap(myConcurrentHashMap);
w1.setName("First Thread");
w2.setName("Second Thread");
w1.start();
w2.start();
r1.start();

}

}

class WriteMap extends Thread {
MyConcurrentHashMap<Integer, String> cMap;
public WriteMap(MyConcurrentHashMap<Integer, String> cMap){
this.cMap = cMap;
}
public void run(){
int i=1;
while(true){
cMap.put(i, this.currentThread().getName());
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}

class ReadMap extends Thread {
MyConcurrentHashMap<Integer, String> cMap;
public ReadMap(MyConcurrentHashMap<Integer, String> cMap){
this.cMap = cMap;
}
public void run(){
int i=1;
while(true){
System.out.println(cMap.get(i));
}
}
}





BlockingQueue Implementaion in java

package kp;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

public class BlockingQueueExample {

public static void main(String[] args) throws InterruptedException {
BlockingQueue<String> queue = new ArrayBlockingQueue<String>(1024);
     Producer producer = new Producer(queue);
     Consumer consumer = new Consumer(queue);
     new Thread(producer).start();
     new Thread(consumer).start();
     Thread.sleep(4000);
}
}

class Producer implements Runnable{

BlockingQueue< String> q=null;
public Producer(BlockingQueue<String> queue) {
this.q=queue;
}
public void run() {
try{
q.put("1");
Thread.sleep(1000);
q.put("2");
Thread.sleep(1000);
q.put("3");
Thread.sleep(1000);
q.put("4");
}
catch (Exception e) {
e.printStackTrace();
}
}

}

class Consumer implements Runnable {

BlockingQueue<String> queue=null;

public Consumer(BlockingQueue< String> b) {
this.queue=b;
}
public void run() {
try {
for (String string : queue) {
System.out.println(queue.take());
}
         

}
catch (Exception e) {
e.printStackTrace();
}
}
}

LRU Implementation in Java

package kp;

import java.util.LinkedHashMap;

public class LRUCache<K, V> extends LinkedHashMap<K, V> {
private static final long serialVersionUID = 1L;
private int size;

public LRUCache(int size) {
super(size, 0.75f, true);
this.size = size;
}

@Override
protected boolean removeEldestEntry(java.util.Map.Entry<K, V> paramEntry) {
return size() > size;
}

public static void main(String args[]) {

LRUCache<String, String> lruCache = new LRUCache<String, String>(7);

lruCache.put("2", "2");
lruCache.put("1", "1");
lruCache.put("3", "3");
lruCache.put("4", "4");
lruCache.put("5", "5");
lruCache.put("6", "6");
lruCache.put("7", "7");



//System.out.println("---" + lruCache.get("1"));
//System.out.println("---" + lruCache.get("2"));
//System.out.println("---" + lruCache.get("3"));

System.out.println(lruCache);
}

}

How to print hello world sequentially using thread in java.

package kp;

public class HelloWorldByWaitNotify {

public static void main(String[] args) {
Object o = new Object();
World worldObj = new World(o);
Hello hello = new Hello(worldObj);
Thread helloThread = new Thread(hello);
Thread worldThread = new Thread(worldObj);
helloThread.start();
worldThread.start();
Thread helloThread1 = new Thread(hello);
Thread worldThread1 = new Thread(worldObj);
helloThread1.start();
worldThread1.start();
}
}

class Hello implements Runnable {
World worldObj;

public Hello(World worldObj) {
this.worldObj = worldObj;
}

@Override
public void run() {
while (true) {
synchronized (worldObj) {
if (!this.worldObj.isWorld) {
System.out.println("Hello");
this.worldObj.isWorld = true;
worldObj.notify();
}
}
}
}
}

class World implements Runnable {
public boolean isWorld = false;
Object o;

public World(Object o) {
this.o = o;
}

@Override
public void run() {
while (true) {
synchronized (this) {
try {
if (!this.isWorld) {
this.wait();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("WORLD!!!!!!");
this.isWorld = false;
}
}
}
}

Friday, 25 January 2019

What do you mean by analysis and design


What do you mean by analysis and design?

Systems Analysis. It is a process of collecting and interpreting facts, identifying the problems, and decomposition of a system into its components. ... It is a problem solving technique that improves the system and ensures that all the components of the system work efficiently to accomplish their purpose.

Analysis:

1. Basically, it is the process of determining what needs to be done before how it should be done. In order to accomplish this, the developer refers the existing systems and documents. So, simply it is an art of discovery.
Design:
It is the process of adopting/choosing the one among the many, which best accomplishes the users needs. So, simply, it is compromising mechanism.

2. What are the steps involved in designing?
Before getting into the design the designer should go through the SRS prepared by the System Analyst.
The main tasks of design are Architectural Design and Detailed Design.
In Architectural Design we find what are the main modules in the problem domain.
In Detailed Design we find what should be done within each module.

3. What are the main underlying concepts of object orientation?
Objects, messages, class, inheritance and polymorphism are the main concepts of object orientation.

4. What do u meant by "SBI" of an object?
SBI stands for State, Behavior and Identity. Since every object has the above three.

State:
It is just a value to the attribute of an object at a particular time.
Behaviour:
It describes the actions and their reactions of that object.
Identity:
An object has an identity that characterizes its own existence. The identity makes it possible to distinguish any object in an unambiguous way, and independently from its state.

5. Differentiate persistent &amp; non-persistent objects?
Persistent refers to an object's ability to transcend time or space. A persistent object stores/saves its state in a permanent storage system with out losing the information represented by the object.
A non-persistent object is said to be transient or ephemeral. By default objects are considered as non-persistent.

6. What do you meant by active and passive objects?
Active objects are one which instigate an interaction which owns a thread and they are responsible for handling control to other objects. In simple words it can be referred as client.
Passive objects are one, which passively waits for the message to be processed. It waits for another object that requires its services. In simple words it can be referred as server.

Diagram:
client server
(Active) (Passive)

7. What is meant by software development method?
Software development method describes how to model and build software systems in a reliable and reproducible way. To put it simple, methods that are used to represent ones' thinking using graphical notations.

8. What are models and meta models?
Model:
It is a complete description of something (i.e. system).
Meta model:
It describes the model elements, syntax and semantics of the notation that allows their manipulation.

9. What do you meant by static and dynamic modeling?
Static modeling is used to specify structure of the objects that exist in the problem domain. These are expressed using class, object and USECASE diagrams.
But Dynamic modeling refers representing the object interactions during runtime. It is represented by sequence, activity, collaboration and statechart diagrams.

10. How to represent the interaction between the modeling elements?
Model element is just a notation to represent (Graphically) the entities that exist in the problem domain. e.g. for modeling element is class notation, object notation etc.

Relationships are used to represent the interaction between the modeling elements.
The following are the Relationships.

Association: Its' just a semantic connection two classes.

e.g.:

Aggregation: Its' the relationship between two classes which are related in the fashion that master and slave. The master takes full rights than the slave. Since the slave works under the master. It is represented as line with diamond in the master area.
ex:
car contains wheels, etc.

car

Containment(Composition): This relationship is applied when the part contained with in the whole part, dies when the whole part dies.
It is represented as darked diamond at the whole part.
example:
class A{
//some code
};

class B
{
A aa; // an object of class A;
// some code for class B;
};
In the above example we see that an object of class A is instantiated with in the class B. so the object class A dies when the object class B dies.we can represnt it in diagram like this.

Generalization: This relationship used when we want represents a class, which captures the common states of objects of different classes. It is represented as arrow line pointed at the class, which has captured the common states.


Dependency: It is the relationship between dependent and independent classes. Any change in the independent class will affect the states of the dependent class.
DIAGRAM:
class A class B

11. Why generalization is very strong?
Even though Generalization satisfies Structural, Interface, Behaviour properties. It is mathematically very strong, as it is Antisymmetric and Transitive.
Antisymmetric: employee is a person, but not all persons are employees. Mathematically all As’ are B, but all Bs’ not A.
Transitive: A=&gt;B, B=&gt;c then A=&gt;c.
A. Salesman.
B. Employee.
C. Person.
Note: All the other relationships satisfy all the properties like Structural properties, Interface properties, Behaviour properties.

12. Differentiate Aggregation and containment(Composition)?
Aggregation is the relationship between the whole and a part. We can add/subtract some properties in the part (slave) side. It won't affect the whole part.
Best example is Car, which contains the wheels and some extra parts. Even though the parts are not there we can call it as car.
But, in the case of containment the whole part is affected when the part within that got affected. The human body is an apt example for this relationship. When the whole body dies the parts (heart etc) are died.

13. Can link and Association applied interchangeably?
No, You cannot apply the link and Association interchangeably. Since link is used represent the relationship between the two objects.
But Association is used represent the relationship between the two classes.
link :: student:Abhilash course:MCA
Association:: student course

14. what is meant by "method-wars"?
Before 1994 there were different methodologies like Rumbaugh, Booch, Jacobson, Meyer etc who followed their own notations to model the systems. The developers were in a dilemma to choose the method which best accomplishes their needs. This particular span was called as "method-wars"


These terms signify the relationships between classes. These are the building blocks of object oriented programming and very basic stuff. But still for some, these terms look like Latin and Greek. Just wanted to refresh these terms and explain in simpler terms.

Association


Association is a relationship between two objects. In other words, association defines the multiplicity between objects. You may be aware of one-to-one, one-to-many, many-to-one, many-to-many all these words define an association between objects. Aggregation is a special form of association. Composition is a special form of aggregation.

Example: A Student and a Faculty are having an association.

Aggregation


Aggregation is a special case of association. A directional association between objects. When an object ‘has-a’ another object, then you have got an aggregation between them. Direction between them specified which object contains the other object. Aggregation is also called a “Has-a” relationship.


Composition


Composition is a special case of aggregation. In a more specific manner, a restricted aggregation is called composition. When an object contains the other object, if the contained object cannot exist without the existence of container object, then it is called composition.

Example: A class contains students. A student cannot exist without a class. There exists composition between class and students.


Difference between aggregation and composition

Composition is more restrictive. When there is a composition between two objects, the composed object cannot exist without the other object. This restriction is not there in aggregation. Though one object can contain the other object, there is no condition that the composed object must exist. The existence of the composed object is entirely optional. In both aggregation and composition, direction is must. The direction specifies, which object contains the other object.

Example: A Library contains students and books. Relationship between library and student is aggregation. Relationship between library and book is composition. A student can exist without a library and therefore it is aggregation. A book cannot exist without a library and therefore its a composition. For easy understanding I am picking this example. Don’t go deeper into example and justify relationships!

Abstraction


Abstraction is specifying the framework and hiding the implementation level information. Concreteness will be built on top of the abstraction. It gives you a blueprint to follow to while implementing the details. Abstraction reduces the complexity by hiding low level details.

Example: A wire frame model of a car.

Generalization


Generalization uses a “is-a” relationship from a specialization to the generalization class. Common structure and behaviour are used from the specializtion to the generalized class. At a very broader level you can understand this as inheritance. Why I take the term inheritance is, you can relate this term very well. Generalization is also called a “Is-a” relationship.

Example: Consider there exists a class named Person. A student is a person. A faculty is a person. Therefore here the relationship between student and person, similarly faculty and person is generalization.

Realization


Realization is a relationship between the blueprint class and the object containing its respective implementation level details. This object is said to realize the blueprint class. In other words, you can understand this as the relationship between the interface and the implementing class.

Example: A particular model of a car ‘GTB Fiorano’ that implements the blueprint of a car realizes the abstraction.

Dependency


Change in structure or behaviour of a class affects the other related class, then there is a dependency between those two classes. It need not be the same vice-versa. When one class contains the other class it this happens.

Example: Relationship between shape and circle is dependency.