Monday, 29 April 2019

Difference between throw and throws in java

Throw vs Throws in java

In this guide, we will discuss the difference between throw and throws keywords. 

1. Throws clause is used to declare an exception, which means it works similar to the try-catch block. On the other hand throw keyword is used to throw an exception explicitly.
2. If we see syntax wise than throw is followed by an instance of Exception class and throws is followed by exception class names.
For example:
throw new ArithmeticException("Arithmetic Exception");
and
throws ArithmeticException;
3. Throw keyword is used in the method body to throw an exception, while throws is used in method signature to declare the exceptions that can occur in the statements present in the method.
For example:
Throw:
...
void myMethod() {
   try {
      //throwing arithmetic exception using throw
      throw new ArithmeticException("Something went wrong!!");
   } 
   catch (Exception exp) {
      System.out.println("Error: "+exp.getMessage());
   }
}
...
Throws:
...
//Declaring arithmetic exception using throws
void sample() throws ArithmeticException{
   //Statements
}
...
4. You can throw one exception at a time but you can handle multiple exceptions by declaring them using throws keyword.
For example:
Throw:
void myMethod() {
   //Throwing single exception using throw
   throw new ArithmeticException("An integer should not be divided by zero!!");
}
..
Throws:
//Declaring multiple exceptions using throws
void myMethod() throws ArithmeticException, NullPointerException{
   //Statements where exception might occur
}
These were the main differences between throw and throws in Java. Lets see complete examples of throw and throws keywords.

Throw Example

To understand this example you should know what is throw keyword and how it works
public class Example1{  
   void checkAge(int age){  
 if(age<18)  
    throw new ArithmeticException("Not Eligible for voting");  
 else  
    System.out.println("Eligible for voting");  
   }  
   public static void main(String args[]){  
 Example1 obj = new Example1();
 obj.checkAge(13);  
 System.out.println("End Of Program");  
   }  
}
Output:
Exception in thread "main" java.lang.ArithmeticException: 
Not Eligible for voting
at Example1.checkAge(Example1.java:4)
at Example1.main(Example1.java:10)

Throws Example

To understand this example you should know what is throws clause and how it is used in method declaration for exception handling.
public class Example1{  
   int division(int a, int b) throws ArithmeticException{  
 int t = a/b;
 return t;
   }  
   public static void main(String args[]){  
 Example1 obj = new Example1();
 try{
    System.out.println(obj.division(15,0));  
 }
 catch(ArithmeticException e){
    System.out.println("You shouldn't divide number by zero");
 }
   }  
}
Output:
You shouldn't divide number by zero

Wednesday, 24 April 2019

Nginx Questions & Answers

1) Explain what is Nginx?
Nginx is a web server and a reverse proxy server for HTTP, HTTPS, SMTP, POP3 and IMAP protocols.
2) Mention some special features of Nginx?
Special features of the Nginx server includes
  • Reverse proxy/ L7 Load Balancer
  • Embedded Perl interpreter
  • On the fly binary upgrade
  • Useful for re-writing URLs and awesome PCRE support
3) Mention what is the difference between Nginx and Apache?
                            Nginx                                 Apache
  • Nginx is an event based web server
  • All request are handled by a single thread.
  • Nginx avoids child processes idea.
  • Nginx resembles speed
  • Nginx is better when it comes to memory consumption and connection
  • Nginx is better when you want load-balancing
  • For PHP, Nginx might be preferable as it supports PHP internally
  • Nginx do not support O.S like IBMi and OpenVMS.
  • Nginx comes only with core features
  • Nginx performance and scalability do not depend on hardware
  •  Apache is a process based server
  • Single thread handles a single request.
  • Apache is based on child processes
  • Apache resemble power
  • Apache is not up-to the mark when it comes to memory consumption and connection
  • Apache will refuse new connections when traffic reaches the limit of processes
  • Apache support’s PHP, Python, Perl and other languages using plugins. It is useful when application is based on Python or Ruby
  • Apache support much wider range of O.S
  • Apache provides lot more functionality than Nginx
  • Apache is dependent on hardware components like CPU and memory
4) Explain how Nginx can handle HTTP requests?
Nginx uses the reactor pattern.  The main event loop waits for the OS to signal a readiness event- such that the data is accessible to read from a socket, at which instance it is read into the buffer and processed.  A Single thread can serve tens of thousands of simultaneous connections.
5) In Nginx how you can prevent processing requests with undefined server names?
A server that just drops the requests can be defined as

Server {
listen                80;
server_name  “ “ ;
return              444;
}
Here the server name is kept as an empty string which will match request without the “Host” header field, and a special Nginx’s non-standard code 444 is returned that terminates the connection.
Nginx-logo
6) What is the advantage of using a “reverse proxy server”?
The reverse proxy server can hide the presence and characteristics of the origin server. It acts as an intermediate between internet cloud and web server. It is good for security reason especially when you are using web hosting services.
7) Mention what is the best usage of Nginx server?
The best usage of Nginx server is to deploy dynamic HTTP content on a network with using SCGI, WSGI application servers, FastCGI handlers for scripts.  It can also serve as a load balancer.
8) Mention what is the Master and Worker Processes in Nginx Server?
  • Master processes: It reads as well as evaluates configuration and maintains worker processes.
  • Worker processes: It actually does the processing of the requests.
9) Explain how you can start Nginx through a different port other than 80?
To start Nginx through a different port, you have to go to /etc/Nginx/sites-enabled/ and if this is the default file, then you have to open file called “default.” Edit the file and put the port you want
Like server { listen 81; }
10) Explain is it possible to replace Nginx errors like 502 error with 503?
  • 502= Bad gateway
  • 503= Server overloaded
Yes, it is possible but you to ensure that fastcgi_intercept_errors is set to ON, and use the error page directive.

Location / {
fastcgi_pass 127.0.01:9001;
fastcgi_intercept_errors on;
error_page 502 =503/error_page.html;
#…
}
11) In Nginx, explain how you can keep double slashes in URLs?
To keep double slashes in URLs you have to use merge_slashes_off;
Syntax: merge_slashes [on/off]
Default: merge_slashes on
Context: http, server
12) Explain what is ngx_http_upstream_module is used for?
The ngx_http_upstream_module is used to define groups of servers that can reference by the fastcgi pass, proxy pass, uwsgi pass, memcached pass and scgi pass directives.
13) Explain what is C10K problem?
C10K problem is referred for the network socket unable to handle a large number of client (10,000) at the same time.
14) Mention what is the use of stub_status and sub_filter directives?
  • Stub_status directive: This directive is used to know the current status of Nginx like current active connection, total connection accepted and handled current number of read/write/wait connection
  • Sub_filter directive: It is used to search and replace the content in response, and quick fix for stale data
15) Explain does Nginx support compress the request to the upstream?
You can compress the request to the upstream by using the Nginx module gunzip. The gunzip module is a filter that decompresses responses with “Content Encoding: gzip” for clients or servers that do not support “gzip” encoding method.
16) Explain how you can get the current time in Nginx?
To get the current time in Nginx, you have to use variables from SSI module, $date_gmt and $date_local.
  • Proxy_set_header THE-TIME $date_gmt;
17) Explain what is the purpose of –s with Nginx Server?
To run the executable file of Nginx –s parameter is used.
18) Explain how to add modules in Nginx Server?
During the compilation process, Nginx modules must be selected as such run-time selection of modules is not supported by Nginx.

Saturday, 13 April 2019

From Java 8 to Java 11 – Quick Guide

Preface

We are all familiar with Java 8 and its ingenious features, but over 4 years have passed from the day of Java 8 release and Java has made a few more big steps forward, with which not all of us had a chance to familiarize. And that’s definitely high time to make up for it, because during this time we already had Java 9 release, which had been quickly superseded by Java 10 and there is Java 11 release just around the corner, which is going to be an important release, because similarly to Java 8, it will be a long-term-support version.

New Java release cycle

Oracle has announced that after releasing Java 9, they are changing the release cycle scheme to a much faster one. Instead of releasing only major increments twice a decade, we’ll be getting Java updates twice a year and a LTS version every three years. That is a big shift and in our opinion a very good response to accusations that Java is not adapting to market needs fast enough.
That said, Java 9 was released in 2017 with immediate plan for being superseded by Java 10 in March 2018. Similarly Java 11 is planned to replace Java 10 in September 2018.

Java 9

Project Jigsaw

The flagship feature of Java 9 was Jigsaw project that introduced modularity to monolithic Java SE ecosystem. The primary goal of the Jigsaw project was to make the Java SE Platform and the JDK more easily scalable down to small computing devices.
Modularization of the JDK enables the source code to be completely restructured in order to make it easier to maintain. Module is a self-describing collection of code, data and resources. It consists of module-info.java file and one or more packages. Modules offer stronger encapsulation than jars.

JShell

Java 9 finally provided a Read-Eval-Print Loop (REPL) tool. This is an interactive programming tool which is continually reading user input, evaluating it and printing the output value or a description of the state change the input caused.
Let’s declare a sample stream:
Then create method that will print it for us:
Now, invoke already declared method:
Jshell supports Tab completion to type commands faster. For example put “names.co” in your Jshell command prompt and then press Tab key:
jshell> names.co
You will see all possible methods, that you can invoke on above stream, that starts with “co”.
Except Java language expressions, Jshell provides it’s own commands:
jshell> /imports
Will return list of imports. Please notice, that Jshell by default returns couple of them:
All of needed packages or classes that are not listed above, can be imported like in normal Java class.
Did you forget an already defined variable? That’s not a problem! Just type:
The same way you can list all of declared methods:
If you want close Jshell tool, just type:

Default garbage collector

Oracle proposed to make G1 garbage collector (which was first introduced in Java 8) the default one from Java 9. Switching to G1 provides better overall experience than a throughput-oriented collectors such as the Parallel GC, which was the default one in prior Java versions.

Language changes in Java SE 9

Private methods in interfaces

Starting from Java 9, we can define private methods in interfaces.
Let’s say we have interface that returns number of available white and red items:
We can extract common business logic to private methods and make them cleaner:
Thanks to this we gain more flexibility in exposing only intended methods to API users and can avoid code duplication in default methods.

Optional Class

Java 9 comes with new methods in Optional class.
Optional.ifPresentOrElse()
Let’s assume that we have two methods to display information about shopping basket depending on its presence.
Instead of writing traditional if/else construction
We can use ifPresentOrElse method:
Optional.or()
Other new method available in Optional class is or. If value is present, method will return Optional describing the value, otherwise returns an Optional produced by the supplying function:
Optional.stream()
Since Java 9 we can treat the Optional instance as a Stream and utilize all methods from Stream API. This makes it also much more convenient to work with streams of Optionals.

Immutable Collection Factory

Java 9 came with static methods on the List, Set and Map interfaces for creating unmodifiable instances of those collections. Till now, to create immutable collection, programmers had to construct it, store it in a local variable, fill with add method and wrap into a unmodifiable collection.
Now, you can replace it with:
It’s also trivial to create an immutable map:

CompletableFuture improvements

The newest version of Java introduces several new methods to CompletableFuture class. Most significant one relates to timeouts.
orTimeout exceptionally completes a ComplatableFuture if it’s not completed in given time:
The other one is completeOnTimeout:
The method completes current CompletableFuture with “value in case of timeout” if not completed before the timeout.

Enhancements in @Deprecated

Java 9 provides enhancements for @Deprecated annotation by adding two new parameters to it:
since – defines version in which the annotated element became deprecated
forRemoval – indicates whether the annotated element is subject to removal in future version

Java 10

Java 10 didn’t come with groundbreaking features, however, it was delivered as promised, only 6 months after Java 9 release and we need to commend that, because in the past years there were always problems with delivering promised Java updates on time.

Keyword “var” (Local-Variable Type Inference)

Probably the most recognisable feature of this release (at least from developer’s point of view). The var keyword that has been introduced can replace strict variable type declaration if the type may be easily inferred by the compiler. Therefore we can type less, don’t need to duplicate type information and it just makes the code look nicer.
We can use var in the context of local variables (instantly initialized), for loops and try-with-resources blocks.
We can’t use var e.g. when declaring class fields or method parameters.
A few examples of correct usage of var:
And a few code samples with var which will not compile:
Also it’s important that the compiler will resolve the exact type of the object that a variable is initialized with. Therefore we will get a compilation error in the following situation:

Additions to JDK

A few small additions came also to the standard class library. For instance, there is a new overloaded version of Optional.orElseThrow() which doesn’t take any parameters and throws NoSuchElementException by default.
Additionally, API for creating unmodifiable collections has been improved by adding List.copyOf()Set.copyOf()Map.copyOf() methods, which are factory methods for creating unmodifiable instances from existing collections. Also, Collectors class has some new methods like toUnmodifiableListtoUnmodifiableSettoUnmodifiableMap.

Parallel Full GC for G1

As we mentioned before, G1 is the default GC starting from Java 9. It was mainly designed to avoid full collections and preventing the “stop the world” event. It increased the performance significantly, however, there was still probability that if concurrent collections couldn’t reclaim memory quickly enough, then classic full GC would be used as a fallback.
Therefore in Java 10 they took care of this particular situation too and improved the algorithm to parallelize the full GC.

Java 11

Local-Variable Syntax for Lambda Parameters

Currently when we want to specify lambda parameters types, we need to do this explicitly and can’t use var keyword introduced in Java 10.
The second line won’t compile in Java 10, but will compile in Java 11.
But, hey, why do we need that at all? If we can write it like this:
even in Java 8 and type inference will do the trick.
Yes, it’s true, but sometimes you have to use explicit typing in lambda and then var may be useful, e.g. when you want to make a parameter final or add annotations.

Launch Single-File Source-Code Programs

With that feature simple, single-file programs (which are common especially at early stages of learning Java) won’t need to be compiled separately. Typing simply
will run the program immediately.

More than just features

Currently, list of planned features for Java 11 is quite small, but release is planned for September 2018 and perhaps some extra features will be added up to that time.
However, these are not fancy features what is going to make Java 11 release so important, but the fact that this version will be the LTS version and thus it will be the most reliable substitute for popular Java 8.

Conclusion

The change of Java release cycle, many syntax-sugar features that came in Java 9 & 10, plenty of safety & performance improvements and the approaching Java 11 platform long term support bring the conclusion that Oracle has a vision for adopting innovation to the language and maintains high level of stability at the same time. This all makes Java development even more interesting and we’re sure that there are more great news coming our way.
This article presented a subset of features introduced to Java between versions 9 and 11, which in our subjective vision are the most interesting and useful ones from Java developer’s perspective. Hope you enjoyed it.
Keywords:
Java 9, JDK 9, Java 10, JDK 10, Java 11, JDK 11, var, local-variable, Jigsaw, modularity, Jshell, REPL, GC, G1, Garbage Collector, Private method, Interfaces, Immutable, collections, List, Set, Map, CompletableFuture, timeout, deprecated
Sources:

http://openjdk.java.netJava 11 – Quick Guide

Getting started with Elasticsearch and Node.js

  In this article we're going to look at using Node to connect to an Elasticsearch deployment, index some documents and perform a simple...