Java – IO @ Blocking vs. Non-blocking

Various streams are blocking in Java IO’s. Usually, when a thread invokes a read() or write() operation, that thread is blocked until there is some data to read, or the data is fully written. This results that respective thread cannot do anything in the meantime.

Java NIO’s non-blocking mode enables a thread to request reading data from a channel, and only get what is currently available, or nothing at all, if no data is currently available. Instead of remaining blocked until data becomes available for reading, the thread can go further with something else. This is true for non-blocking writing wherein a thread can request that some data be written to a channel, but not wait for it to be fully written.

What threads spend their idle time on when not blocked in IO calls, is usually performing IO on other channels in the meantime. That is, a single thread can now manage multiple channels of input and output.

!! Happy Revision/Learning !!

@Size vs @Length vs @Column

@Size and @Length are similar which are used to validate the size of a field. The first is a Java-standard annotation and the second is specific to Hibernate. Whereas @Column, is a JPA annotation that we use to control DDL statements.

Example for @Size
This annotation makes the bean independent of JPA and its vendors such as Hibernate

public class Customer {
    ...
    @Size(min = 5, max = 15)
    private String fullName;
    ...
}

Example for @Length
It is Hibernate-specific version of @Size

@Entity
public class Customer {
    …
    @Length(min = 5, max = 15)
    private String fullName;
    …
}

Example for @Column
It is used to indicate specific characteristics of the physical database column.

@Entity
public class Customer {
    …
    @Column(length = 15)
    private String fullName;
    …
}

SOLID Principles

The SOLID principles were first conceptualized by Robert C. Martin and later built upon by Michael Feathers, who introduced us to “SOLID” acronym. As per their study, design principles encourage us to create more maintainable, understandable, and flexible software. Therefore, as our applications grow in size, we can reduce it’s complexity and better management.

Following are the SOLID principles for each developer/architect reference:-

  • Single Responsibility:- This principle states that a class should have only one responsibility and one reason to change. Once acheived, following are the benefits for the same:-
    • Testing – A class with one responsibility will have fewer test cases
    • Loose Coupling – Less functionality in a single class will have fewer dependencies
    • Organized – Smaller, well-organized classes are easier to search than monolithic ones
  • Open/Closed:- Following principle states that classes should be open for extension, but closed for modification. In doing so, we stop ourselves from modifying existing code and causing potential new bugs. By extending the Parent class we can be sure that our existing application won’t be affected.
  • Liskov Substitution:- Functions that use references to base classes must be able to use objects of the derived class without knowing it. In simple words, derived classes must be substitutable for the base class. It’s recommended to call public parent methods to get your results in the sub-classes and not directly using the internal variables. That way you are making sure the parent abstractions get to the required state without side effects or invalid state transitions. It’s also recommended keeping your base Abstractions as simple and minimal as possible, making it easy to extend by the sub-classes.
  • Interface Segregation:- Larger interfaces should be split into smaller ones. By doing so, we can ensure that implementing classes only need to be concerned about the methods that are of interest to them.
  • Dependency Inversion:- The principle of Dependency Inversion refers to the decoupling of software modules. This way, instead of high-level modules depending on low-level modules, both will depend on abstractions.

Profiling @ JVisualVM

This is one of the useful, free utilities that come in the JDK bundle. It’s basically a JMX client application. It helps us to shows stats and improve the application performance after analyzing Memory leaks, Heap data, Garbage Collector, and CPU profiling/consumption. With features like thread analysis and head dump analysis, it is very handy in solving run-time problems, too.

To enable JVisualVM to collect stats of application hosted on a remote server, we have to run our application with JMX System properties. They are as follows:

  • com.sun.management.jmxremote.port is used to specify the port number through which the application will be exposed
  • com.sun.management.jmxremote.ssl is used to specify whether secure sockets layer (SSL) encryption will be activated to secure the connection to the application
  • com.sun.management.jmxremote.authenticate is used to specify whether the connection will be password protected

Finally, our Jar command will look like:-

java -jar -Dcom.sun.management.jmxremote.port=1098 -Dcom.sun.management.jmxremote.authenticate=false -Dcom.sun.management.jmxremote.ssl=false myApplication.jar

Now, we can run jvisualVM from path c:\oracle\bin\jvisualvm and add remote host for an application and could start Profiling.

Rules we need to follow when Overriding a Method in Java

Given below points could be referenced while Overriding a Method in Java:-

1. When the parent class method doesn’t throw any exceptions, the child class method can’t throw any checked exceptions, but it may throw any unchecked

2. When the parent class method throws one or more checked exceptions, the child class method can throw any unchecked exception, including all, none, or a subset of the declared checked exceptions and an even a greater number of these as long as they have the same scope. However, if we try to throw a checked exception that the parent class method doesn’t declare or we throw one with a broader scope, we’ll get a compilation error

3. When the parent class method has a throws clause with an unchecked exception, the child class method can throw none or any number of unchecked exceptions, even though they are not related

Happy Learning 🙂

Difference Between Checked and Unchecked Exceptions in Java

Following are the few points that gives more clarity for Checked and Unchecked Exceptions in Java:-

1. Checked exceptions should be handled in the code using a try-catch block, or else, the method should use the throws keyword to let the caller know about the checked exceptions that might be thrown from the method. Unchecked Exceptions are not required to be handled in the program or to mention them in the throws clause of the method.

2. The Exception is the superclass of all checked exceptions, whereas RuntimeException is the superclass of all unchecked exceptions. Note that RuntimeException is the child class of Exception.

3. Checked exceptions are error scenarios that require being handled in the code, or else, you will get a compile-time error. For example, if you use FileReader to read a file, it throws the FileNotFoundException and we must catch it in the try-catch block or throw it again to the caller method. Unchecked exceptions are mostly caused by poor programming, for example, the NullPointerException when invoking a method on an object reference without making sure that it’s not null.

4. Checked and unchecked exceptions are also known as compile-time and run-time exceptions respectively.

Lombok Annotations

Project Lombok is a boilerplate code remover and space saver that generates code in “.class” file instead of in the source code file. Lombok provides a set of annotations and some of them could be used in day-to-day coding. Let’s have a look at few of them.

@Getter and @Setter:- The @Getter and @Setter annotations provide getter and setter methods for a field respectively. These annotations can be used at the field and class level.

@Getter
@Setter
public class Employee {
	private String empId;
	private String employeeName;
}

@ToString Annotation:- This annotation generates the toString() method in the “.class” file at compile time. There is no need to write explicit code for the toString() method in POJO.

@ToString
public class Employee {
	private String empId;
	private String employeeName;
}

@Builder:- This annotation is used to generate the code required to have your class be instantiable using the builder pattern.

@Builder
public class Employee {
	private String empId;
	private String employeeName;
}

@Log4j:- This annotations is used to generate code related to the logger.

@Log4j
public class MyClass{
	public void greetings() {
		log.info("Good Morning");
	}
}

WeakHashMap @ Java

WeakHashMap is a Hash table-based implementation of the Map interface with weak keys. An entry in a WeakHashMap will automatically be removed when its key is no longer in ordinary use. Both null values and the null key are supported. This class has performance characteristics similar to those of the HashMap class and has the same efficiency parameters of initial capacity and load factor. Like most collection classes, this class is not synchronized. A synchronized WeakHashMap may be constructed using the Collections.synchronizedMap method.

Code Snippet:-

import java.util.Map;
import java.util.Map.Entry;
import java.util.WeakHashMap;

public class MyClass {
	public static void main(final String[] args) {
		final Map map = new WeakHashMap();
		Key key1 = new Key("ACTIVE_KEY-1");
		Key key2 = new Key("ACTIVE_KEY-2");
		
		map.put(key1, new Employee(101, "Tom"));
		map.put(key2, new Employee(102, "Jerry"));
		
		key1 = null;
		System.gc();
		
		for (final Entry entry : map.entrySet()) {
			System.out.println(entry.getKey().getKey() + "   " + entry.getValue());
		}
	}
}

class Key {
	private String key;
	
	public Key(final String key) {
		super();
		this.key = key;
	}

	public String getKey() {
		return key;
	}

	public void setKey(final String key) {
		this.key = key;
	}
}

IdentityHashMap @ Java

IdentityHashMap is a HashTable -based implementation of the Map Interface. Normal HashMap compares keys using the .equals method but Identity HashMap compares its keys using the == operator. Hence, ‘Java’ and new String(‘Java’) are considered as two different keys. The initial size of Identity HashMap is 21, while the initial size of a normal HashMap is 16.

Code Snippet:-

import java.util.IdentityHashMap;
public class MyClass {
	public static void main(final String[] args) {
		final IdentityHashMap identityHashMap = new IdentityHashMap();
		identityHashMap.put("Java", "Java-7");
		identityHashMap.put(new String("Java"), "Java-8");

		for (final String str : identityHashMap.keySet()) {
			System.out.println("Key : " + str + " and Value : " + identityHashMap.get(str));
		}

		System.out.println("Size of map is : " + identityHashMap.size());
	}
}

Output:-

Key : Java and Value : Java-7
Key : Java and Value : Java-8
Size of map is : 2

Test SMTP communication with OpenSSL

We can use the openssl command to have the verification of SMTP sever connectivity over TLS

$ openssl s_client -connect smtpserver.mailprovider.com:25 -starttls smtp

 
CONNECTED(00000004)
depth=3 C = SE, O = AddTrust AB, OU = AddTrust External TTP Network, CN = AddTrust External CA Root
verify error:num=19:self signed certificate in certificate chain
---
Certificate chain
 0 s:/C=US/postalCode=160030/ST=Chandigarh/L=Chandigarh/street=Chandigarh/O=OrgName, Inc./OU=Messaging/OU=Hosted by OrgName/OU=Multi-Domain SSL/CN=securemail.mailprovider.com
   i:/C=GB/ST=Greater Chandigarh/L=Salford/O=COMODO CA Limited/CN=COMODO RSA Organization Validation Secure Server CA
 1 s:/C=GB/ST=Greater Chandigarh/L=Salford/O=COMODO CA Limited/CN=COMODO RSA Certification Authority
   i:/C=SE/O=AddTrust AB/OU=AddTrust External TTP Network/CN=AddTrust External CA Root
 2 s:/C=GB/ST=Greater Chandigarh/L=Salford/O=COMODO CA Limited/CN=COMODO RSA Organization Validation Secure Server CA
   i:/C=GB/ST=Greater Chandigarh/L=Salford/O=COMODO CA Limited/CN=COMODO RSA Certification Authority
 3 s:/C=SE/O=AddTrust AB/OU=AddTrust External TTP Network/CN=AddTrust External CA Root
   i:/C=SE/O=AddTrust AB/OU=AddTrust External TTP Network/CN=AddTrust External CA Root
---
Server certificate
-----BEGIN CERTIFICATE-----
Wj/FMdFEvIbYGHUVUtPswhcJR5jvJQuiP9h/lFgCYcKG/Fa1QZ9/53Cp0tUrZoTd
UrwYlpZA+2CnAgMBAAGjggRZMIIEVTAfBgNVHSMEGDAWgBSa8yvaz61Pti+7KkhI
KhK3G0LBJDAdBgNVHQ4EFgQUutI6MN0OGTTOt77BXbWvuWY2sZcwDgYDVR0PAQH/
MH0wVQYIKwYBBQUHMAKGSWh0dHA6Ly9jcnQuY29tb2RvY2EuY29tL0NPTU9ET1JT
QU9yZ2FuaXphdGlvblZhbGlkYXRpb25TZWN1cmVTZXJ2ZXJDQS5jcnQwJAYIKwYB
BQUHMAGGGGh0dHA6Ly9vY3NwLmNvbW9kb2NhLmNvbTCCARQGA1UdEQSCAQswggEH
cm92aWRlci5jb22CF214NC5tZXNzYWdlcHJvdmlkZXIuY29tghdteDUubWVzc2Fn
ZXByb3ZpZGVyLmNvbYIXbXg2Lm1lc3NhZ2Vwcm92aWRlci5jb22CF214Ny5tZXNz
-----END CERTIFICATE-----
subject=/C=US/postalCode=160030/ST=Chandigarh/L=Chandigarh/street=Chandigarh/O=OrgName, Inc./OU=Messaging/OU=Hosted by OrgName/OU=Multi-Domain SSL/CN=securemail.mailprovider.com
issuer=/C=GB/ST=Greater Chandigarh/L=Salford/O=COMODO CA Limited/CN=COMODO RSA Organization Validation Secure Server CA
---
No client certificate CA names sent
---
SSL handshake has read 6842 bytes and written 558 bytes
---
New, TLSv1/SSLv3, Cipher is AES256-SHA
Server public key is 2048 bit
Secure Renegotiation IS supported
Compression: NONE
Expansion: NONE
No ALPN negotiated
SSL-Session:
    Protocol  : TLSv1.2
    Cipher    : AES256-SHA
    Session-ID: 87077B0F0737A1FF5FF042D484800DD0C70DD24125E88812C5A4EC37BA8DE607
    Session-ID-ctx:
    Master-Key: 4D538CD6FA48143912C634BE3EE36ADFC8D6CBEECAB3D43A2C45E5F31B7B43422A21C5CDA1DE12B0A9DA33C541B6D530
    Key-Arg   : None
    SRP username: None
    TLS session ticket lifetime hint: 300 (seconds)
    TLS session ticket:
    0000 - 33 d7 ad 86 5d b1 a7 0a-97 36 72 43 cc aa e8 0c   3...]....6rC....
    0010 - f0 3b 17 39 e4 c7 81 1d-f7 36 f4 ff 04 19 f7 9e   .;.9.....6......
    0020 - a6 16 6b 21 33 b7 eb d3-54 50 b8 3a 2f 72 cb bf   ..k!3...TP.:/r..
    0030 - 31 44 7d 53 73 86 df a0-72 a9 90 5c 73 c9 0c 46   1D}Ss...r..\s..F
    0040 - c8 4b 79 be 86 a7 ae a0-23 1c 43 e5 fd ef a0 cc   .Ky.....#.C.....
    0050 - 49 e3 df e8 0f 2b fa 7d-9d 8b 7c de 20 a4 fc 6f   I....+.}..|. ..o
    0060 - 95 7e 37 e0 15 f9 a6 e6-34 3d da 7a 40 5f ba f7   .~7.....4=.z@_..
    0070 - 92 2d 03 89 5d 17 f5 28-85 fa 02 e0 50 cc 01 83   .-..]..(....P...
    0080 - 3d 77 2c 1f ef e8 2c 9b-31 68 d5 6d 9a ff e0 dd   =w,...,.1h.m....
    0090 - cf 43 86 fa 02 07 e0 d8-c8 d7 d3 e0 db 6d f8 ce   .C...........m..

    Start Time: 1545224851
    Timeout   : 300 (sec)
    Verify return code: 19 (self signed certificate in certificate chain)
---
250 STARTTLS

500 5.5.1 Command unrecognized: ""
quit
221 2.0.0 mx4.mailprovider.com Closing connection
closed