Saturday, 19 January 2019

How to print odd and even numbers in order with two threads

Background

Let us say you have two threads - one thread prints even numbers and other one prints odd numbers. You need to design this in such a way that all the numbers are printed in the natural order i.e 1,2,3,4 etc. 

This is more of a synchronization questions rather than a data structure question. You need to understand how threads, synchronization works in order to be able to solve this question. 

How to print odd and even numbers in order with two threads

We can do this two ways -
  1. Using Sempahores
  2. Using wait and notify

Let us see how we can do this using semaphores -

public static void withSemaphores() throws InterruptedException, ExecutionException {

 Semaphore oddLock = new Semaphore(1);
 Semaphore evenLock = new Semaphore(0);

 Runnable printOdd = () -> {
  for (int i = 1; i < 10; i = i + 2) {
   try {
    oddLock.acquire();
   } catch (Exception e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
   ;
   System.out.println(i);
   evenLock.release();
  }
 };

 Runnable printEven = () -> {
  for (int i = 2; i < 10; i = i + 2) {
   try {
    evenLock.acquire();
   } catch (Exception e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
   System.out.println(i);
   oddLock.release();

  }
 };

 new Thread(printOdd).start();
 new Thread(printEven).start();
}


Before we see how this is actually working you need to understand how semaphores work. They essentially are like permits. You can initialize the semaphore with the initial permits. Let us say semaphore has 2 permits, to begin with. In this case, 2 threads can acquire these permits. The 3rd thread which comes has to wait till one of the 2 permits become available again. Threads that have acquired the permits can release them once they are done. Permits are acquired by acquire() method and released by release() method. To read more about Semaphores you can refer a post I had written earlier -

Also, note I have used Java 8 lambda syntax in the code above. You can read more about lambds -
Now with this understanding let's see how the above logic works.


printOdd runnable is responsible for printing odd numbers whereas printEven prints even number. For loop is designed in such a way and it increments by 2 to continue printing respective numbers. We need to start with 1 which is odd, so old thread starts first. Notice we have 2 semaphores - one for odd and one for even. Odd semaphore has 1 permit whereas even semaphore has 0, to begin with. The odd thread can get the permit from an odd semaphore and print the odd value which is 1. Meanwhile, the even thread will get blocked since no permits are available for even semaphore. Only when an odd thread releases even semaphore permit, even thread will go ahead and print 2. That's how each thread locks each other till numbers are printed in sequence.

You can do the same with the wait and notify. You can see both of the above methods on my GitHub repository on data structures - https://github.com/aniket91/DataStructures/blob/master/src/com/osfg/questions/PrintOddEven.java 


Related Links

Thursday, 17 January 2019

How to use Callable interface with Threads in Java?

Background

In one of the previous posts on Creating Threads with Executor service, we saw an interface called Callable. Executor has a method called submit that took Callable object and returned a future object which had the results. Unlike the Runnable interface, we can use Callable interface to return the result or throw checked Exceptions. In this post, we will see how to use Callable interface with plain Thread construct.

How to use Callable interface with Threads in Java?

We know that Thread takes Runnable interface only. No surprises there. So we cannot directly use objects implementing the Callable interface. Also to get the result we need Future object as we saw in Executors. Remember any design pattern that suits this use case? yes, it is Adapter Pattern. Java provides a class called FutureTask which implements Runnable and Future, combining both functionalities conveniently. Let's see an example of how we can do this -

package com.osfg;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;


public class Test {
 public static void main(String args[]) throws InterruptedException, ExecutionException {

  Callable<String> callable = () -> {
   Thread.sleep(5000);
   return "Hello!";
  };

  FutureTask<String> futureTask = new FutureTask<>(callable);
  Thread t = new Thread(futureTask);
  t.start();

  while (!futureTask.isDone()) {
   System.out.println("Task not done yet!");
   Thread.sleep(1000);
  }

  System.out.println(futureTask.get());
 }

}




You can see here that our Callable waits for 5 seconds and returns the results. And in the main thread, we do a check every 1 second to see if the result is available in the FutureTask. So if you run above code you will get -

Task not done yet!
Task not done yet!
Task not done yet!
Task not done yet!
Task not done yet!
Hello!

FutureTask has following methods -

  • public boolean cancel(boolean mayInterrupt): Used to stop the task. It stops the task if it has not started. If it has started, it interrupts the task only if mayInterrupt is true.
  • public Object get() throws InterruptedException, ExecutionException: Used to get the result of the task. If the task is complete, it returns the result immediately, otherwise, it waits until the task is complete and then returns the result.
  • public boolean isDone(): Returns true if the task is complete and false otherwise

Related Links

Sunday, 30 December 2018

How to write your own attribute directive in Angular?

Background

In the last post, we saw how to use structural directives like *ngIf and *ngFor that can be used to modify DOM elements. 
Attribute directives can change the appearance or behavior of an element, component, or another directive. In this post, I am going to show you how to write your own attribute directives in Angular.

For this, we are going to create a directive which on single click will enlarge our text and on double click get it back to original size. 

How to write your own attribute directive in Angular?

Let's start by writing our directive class file. Under the app folder create a new file called enlarge.directive.ts.  In this file add following code -


import { Directive, ElementRef, HostListener, Input, Renderer2 } from '@angular/core';
@Directive({
  selector: '[appEnlarge]'
})
export class EnlargeDirective {


  constructor(private el: ElementRef, private renderer: Renderer2) { }


  @Input('appEnlarge') appEnlargeSize: string;


  @HostListener('click') onclick() {
    this.enlarge( this.appEnlargeSize || '100px');
  }


  @HostListener('dblclick') ondblclick() {
    this.enlarge('50px');
  }


  private enlarge(enlargeSize: string) {
    this.renderer.setStyle(this.el.nativeElement, 'font-size', enlargeSize);
  }
}


Let's go over this code and try to understand what we are doing here.  1st line has a couple of imports that we will understand as we go ahead. Next line has an annotation called @Directive which states that this class is a directive and its selector is appEnlarge. So you could use this directive as follows -
  • <p appEnlarge>Directive applied for this content!</p>
We will see this in action in some time. Next, we have a constructor where we have access to the native element and the renderer. We can use APIs from renderer or Native element to actually make changes to the element.

Next, we have an input called appEnlargeSize. Here the user can specify how much the context needs to be enlarged. Notice how we have used an alias here in the bracket. This is so that we could specify input and directive in the same binding as below -
  • <p [appEnlarge]="'120px'">Directive applied for this content!</p>
Then we are using HostListener APIs for single and double click to actually do our transformation - which is increasing the font size. You can see all HostListener APIs here -
 Notice how in enlarge function we have used renderer API of setStyle to apply our desired style. You can see all renderer2 APIs here -

Now that your directive is done let's import it and declare it in our main module. Go to app.module.ts  and import it. Also, add it in the declaration section. Your app module should look like below -

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';


import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import {EnlargeDirective} from './enlarge.directive'

@NgModule({
  declarations: [
    AppComponent,
    EnlargeDirective
  ],
  imports: [
    BrowserModule,
    AppRoutingModule
  ],
  providers: [],
  bootstrap: [AppComponent],
})
export class AppModule { }

And that's it. Save all your changes and start your angular app using -
  • ng serve
Go to http://localhost:4200/ and see your changes.

Single click on the text to enlarge it and double click it to bring it to its original size.






This is not a great example with perfect CSS and animation but I hope this gives you an idea of how you can write custom directives in angular.  These are very powerful techniques to change the appearance of your components. Let me know if you have any questions. Thanks.


This is the last post of the year 2018 :). So wishing all a very happy new year! Hoping coming year would be more awesome with a lot of more learning and sharing!

Related Links

Thursday, 27 December 2018

Using structural directives in Angular

Background

There are 3 kinds of directives in 
  1. Components—directives with a template.
  2. Structural directives—change the DOM layout by adding and removing DOM elements.
  3.  Attribute directives—change the appearance or behavior of an element, component, or another directive.
We have already seen how to create components, how components interact with each other. Structural Directives change the structure of the view whereas Attribute directives are used as attributes of elements. You can use build in directives provide by angular or build your own.

In this post, I will explain structural directives such as *ngIf and *ngFor.


Using structural directives in Angular

As mentioned before structural directives manipulate the DOM structure by adding or removing elements from the DOM.  An asterisk (*) precedes the directive attribute name. Let's see an example by using *mgIf. This structural directive is used to decide if the element on which it is applied (including its children) are added in DOM or not.

So in your AppComponent code make changes so that the HTML template looks like below -

<div class="hello-world">

  <h1 *ngIf="showMessage">Hello World!</h1>
  <br/>

  <button (click)="toggleVisibility()">Toggle Visibility</button>
</div>


Notice the way we are using *ngIf. It says if showMessage variable evaluates to true then show this h1 element and if not remove it from the DOM. Then we have a button which says "Toggle Visibility" that essentially toggles the showMessage variable flag. Let's see the component typescript code to understand this better. Your component code would look like following -

import { Component } from '@angular/core';


@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {

  showMessage: boolean = false;

  toggleVisibility = () => {
    this.showMessage = !this.showMessage;
  }

}


Notice the showMessage variable of type boolean. It is set to false at the beginning and as you click the button this flag is toggles which change the visibility of our H1 element. Please note that *ngIf removes the element from the DOM and does not just change the visibility. So when I say changes visibility I mean it being part of the DOM. So let's give this a try. Start your app with -
  • ng serve





Notice how the h1 elements take part of DOM and when it is not visible it gets removed. Your button position will get adjusted based on that.

NOTE: When the condition is false, NgIf removes its host element from the DOM, detaches it from DOM events (the attachments that it made), detaches the component from Angular change detection, and destroys it. The component and DOM nodes can be garbage-collected and free up memory.

The asterisk is "syntactic sugar" for something a bit more complicated. Internally, Angular translates the *ngIf attribute into a <ng-template> element, wrapped around the host element.


Now let's take a look at *ngFor directive.

Change the component code to have an array of cities.


import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {

  cities: string[] = ["Mumbai", "Bangalore","Delhi","Chennai","Hyderabad"];

}


Now you can change this components HTML code as follows -

<div class="hello-world">
  <ul>
      <li *ngFor="let city of cities">{{city}}</li>
  </ul>
</div>


This essentially creates an unordered list element and inside it, iterates over each of the cities in the array and creates a list element. This would look like below -




NOTE: Angular desugars this notation into a marked-up <ng-template> that surrounds the host element and its descendants. Each structural directive does something different with that template.

As mentioned before you could also create your own structural directives. To read more on these go to the angular documentation - https://angular.io/guide/structural-directives

Related Links

Wednesday, 26 December 2018

How to dynamically create a component in Angular?

Background

In the last few posts, we have been seeing how to write applications in Angular. If you wish to revisit some of them take a look at the Related Links section at the bottom of this post. In this post, I will show you how to dynamically create components on Angular. I am assuming you already have the boilerplate code we have written so far. This would be an extension to it.


How to dynamically create a component in Angular?

Let us start making changes from the AppComponent. If you remember this is the component we have added in the bootstrap property of our root module. Go to the HTML content of this component, remove all the code we had added before for routing and replace it with the following code -

<div class="hello-world">
  <h1>{{title}}</h1>


  <button (click)="genComponent('Botton 1 Clicked!')">Button 1</button>
  <button (click)="genComponent('Botton 2 Clicked!')">Button 2</button>


  <template #messagecontainer>
  </template>


</div>

It is a simple HTML content. Let me explain this first. 

  • We have a simple h1 tag which has a bound value called title. title value would be provided by the corresponding component definition in the typescript file. We will come to the changes in typescript file in a moment. 
  • Next, we have 2 buttons that call the function genComponent on the click event. This function definition would again go in the typescript file which we will see shortly.
  • Lastly, we have a template tag where we will dynamically load our component. This new component as we will see has a bound value called msg which is what you see as the argument of genComponent function.
Now let's see how the typescript file for this looks like -

I am going to create a new component in the same AppComponent file. If you wish you can create a new file for it. The component is as follows -

@Component({
  selector: 'app-child',
  template: `
<h2>Message : {{msg}}</h2>
`
})
export class ChildComponent {
  @Input() msg: string;
}

As you can see this ChildComponent which we intend to create dynamically take an argument msg as input. We will see how we can pass this input when we dynamically create this. You can also see it's HTML content - It simply has an H2 tag with the bound msg input.

Now, let's take a look at AppComponents definition -

import { Component, Input, ViewChild, ViewContainerRef, ComponentFactoryResolver, OnDestroy } from '@angular/core';




@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnDestroy {
  title = 'angulardemo';
  componentRef: any;


  @ViewChild('messagecontainer', { read: ViewContainerRef }) entry: ViewContainerRef;


  constructor(private resolver: ComponentFactoryResolver) { }


  genComponent(msg) {
    this.entry.clear();
    const factory = this.resolver.resolveComponentFactory(ChildComponent);
    this.componentRef = this.entry.createComponent(factory);
    this.componentRef.instance.msg = msg;
  }
  destroyComponent() {
    this.componentRef.destroy();
  }


  ngOnDestroy() {
    this.destroyComponent();
  }
}

Let us see what this is doing -
  • We already say the content of app.component.html above where we removed the navigator outlet and added 2 buttons and a template for dynamically loading our CHildComponent.
  • Inside the component definition, we have a variable called title which we say in the HTML template inside h1 tag.
  • Then we have an entry variable which points to the template tag we have created in AppCpmponents HTML file.
  • We can access template as the ViewChild inside the Component class. The template is a container in which, we want to load the ChildComponent dynamically. Therefore, we have to access template as ViewConatinerRef.ViewContainerRef represents container where one or more view can be attached.
  • Next, we have defined a constructor where we have injected ComponentFactoryResolver dependency. We need this to create the component dynamically.
  • Then we have 2 methods  - genComponent and destroyComponent that is used to create and destroy our ChildComponent dynamically. Notice how we are storing the reference of the new component in componentRef and using it.
  • In genCompinent we are doing the following -
    • Clearing the container
    • Creating a factory for ChildComponent
    • Creating component using above factory
    • Passing the value msg input using component reference instance method
  • Also, notice we are calling destroyComponent in ngOnDestroy lifecycle hook of angular component. You could add this login inside an event of your own as well. 
  • You also saw how our ChildComponent has an input called msg and you can see in genComponent function we are passing this input as this.componentRef.instance.msg.
  • Also, take care of all the imports that are on the 1st line of the above code.
NOTE: The entry component which is a reference to the template tag has APIs to create and destroy components.

The final changes that we need would be in the AppModule itself. We need to define our new Child component in declaration and entry components. So import the new ChildComponent in the AppModule and put it under declaration and entryComponents 


import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { NewEmployeeComponent } from './employee/new-employee/new-employee.component';
import { SubempComponent } from './employee/subemp/subemp.component';



@NgModule({
  declarations: [
    AppComponent,
    NewEmployeeComponent,
    SubempComponent,
    ChildComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule
  ],
  providers: [],
  bootstrap: [AppComponent],
  entryComponents: [ChildComponent]
})
export class AppModule { }

Now you should be all set to test out your code. Start your angular application with -

  • ng serve
and open your application on the set port (default 4200)-






Related Links

t> UA-39527780-1 back to top