Java programming notes

Who should read it: anyone looking for a quick overview of Java programming basic concepts.

Below are some common concepts about Java programming language:

Volatile: Volatile is a keyword that can be used only with variables. It can not be used within a method or a class.

We can use volatile when we want to read and write long/double variables. It can be used to achieve synchronization. Volatile guarantees that the value will be read from the main memory.

Synchronized block: There are two versions: a synchronized method and a synchronized statement. Synchronization helps to avoid multiple threads accessing the same code at the same time. For more on it, read here.

Static keyword: Static keyword indicates that the method or field that it declared static, belongs to the class. In other words, there’s the same copy of the field or method across all instances.

Class: A class is a blueprint that can define behavior using methods.

Object: An object is an in-memory instance that is created using the blueprint called, class.

Exception Handling: When a program is interrupted due to an unexpected event, that captured event may be called an exception. Use try/catch to catch an exception. If an exception is not caught, throw the exception to the other program so that another program handles it. In Java, there are three kinds of exceptions:

  • Checked exceptions: these are subject to try and catch.
  • Errors: These are generally exceptions that occur due to external situations.
  • Runtime exception: These are exceptions internal to application and these are generally occur due to unanticipated scenarios.

JDBC drivers: Java Database Connectivity (JDBC) is an API in Java that helps to connect a Java program with a database. JDBC API supports a wide range of databases. JDBC provides four types of drivers:

  • Type 1 JDBC-ODBC Bridge: Type 1 JDBC driver provides the connectivity to database via Open Database Connectivity (ODBC) drivers. It is limited to some options and the performance of type 1 driver is not great as it needs the translation of code from JDBC to ODBC format.
  • Type 2 Partial Java Driver: It is a partially Java enabled driver. It needs the binary code into client’s machines. The performance of it is slower than type 3 and type 4.
  • Type 3 Driver: It is a fully Java enabled driver that converts the net-protocol to the DMBS specific protocol. The limitation is that it needs separate JDBC middle-ware server to translate native specific connection interface.
  • Type 4 Driver: This allows direct connections to databases by using network protocol that sends the data to DBMS into the DBMS specific format. This is a very popular driver type.

Java collections:

Java has these collections:

  • Collection: It is a root of collection hierarchy.
    • List: List is an ordered collection.
      • Arraylist is an implementation of List.
    • Set: A collection that has no duplicates.
      • SortedSet: It is a sorted version of Set.
    • Queue: This holds multiple elements prior to execution. Queue typically has elements in FIFO (First In First Out) order.
    • Deque: This collection also holds multiple elements prior to execution. Deque can be both FIFO and LIFO (Last In First Out).
  • Map: Map object holds key and values. Maps can not contain any duplicate keys.
    • SortedMap: It is a sorted version of Map.

Note: I will further elaborate collections in the upcoming updates.

Comparator versus Comparable:

  • Comparable compares objects. We can override compareTo() method.
  • Comparator is external to the element we are comparing.
  • When we need to compare objects with the natural order, we should use Comparable. When we need to compare objects with their attributes, we should use Comparator.

Equals and Hashcode methods:

Equals compares two objects. Hashcode() method helps to get a hash code integer number of an object. Hashcode() method is used to compare two objects. To compare two objects, first we can compare their hash codes. If hash codes are same, next we can compare attributes of two objects.

Serializable and externalizable: Serializable serializes the object via JVM. It stores the object in a way that later it can be recreated. Externalizable allows us to store selected features of an object. Externalizable extends Serializable and add two methods: readExternal() and writeExternal(). To use externalizable, ensure that default constructor of the object’s class is public. Otherwise, it will not serialize the object and throw an error.

String intern() and deduplication: Java strings use heap memory, to store each string literals, even if it is the same string. String intern() can help avoid the storage of same string literals repeatedly. intern() avoid duplication of string strings. intern() uses string pool, to avoid storing more than one same string values in the heap memory. String intern() is a non-static method.

Multi-threading in Java: A thread is a smallest unit of processing. To achieve multi tasking, we use multi-threading and multi-processing. Multi threading does not allocate separate memory. It takes less time for threads to switch the context. We can can multiple processes running on a computer. Each process takes separate memory address space. Each process can have one or more threads in it. Threads share same address space.

Other Thread related topics:

  • Thread states:
    • New: a new thread, not started yet
    • Runnable: a thread running in JVM (Java Virtual Machine)
    • Blocked: a thread that is blocked, waiting for a monitor lock
    • Waiting: a thread waiting for another thread to perform
    • Time_waiting: a thread waiting for another thread for a time period
    • Terminated: a thread that is exited
  • ThreadLocal: ThreadLocal allows to create and read variables within the same thread. If we have two threads executing same code, these two threads can not see each other’s variables.
  • InterruptedException: InterruptedException is thrown when a thread is interrupted while waiting, sleeping, or otherwise occupied. For details, refer to this article.
  • Livelock, Deadlock, and Starvation:
    • Deadlock is a situation in that the processes block each other.
    • Livelock is a situation in which the states of the processes constantly change. This situation does not allow any process to finish the task.
    • Starvation: it is a situation in that all processes do not get the allocation of CPU time to complete a task.
    • For more, refer to this article.

Concurrent utilities: java.util.concurrent package has utilities to create concurrent applications.

Java NIO: Java NIO is an alternative to Java IO. Java NIO allows non blocking IO.

Java thread dump analysis: A thread dump provides a snapshot of currently running processes. If there is a performance problem or a deadlock problem, analyzing thread dump can help to understand/trouble shoot it. jStack is a simple utility to generate thread dumps. This is a simple article describing thread dump analysis.

Memory leaks: Memory leaks is a situation of having unused memory that is not garbage collected. If an application has severe performance issues or crashing suddenly or throwing Java Out Of Memory Error, these are symptoms of memory leaks. Minimizing static variables and using singleton pattern with lazy loads are useful techniques to minimize or avoid memory leaks.

Java app profiling and profiling tools: Java profilers can help to estimate how memory will be allocated for the program. It can help to improve the code. Some example of profiling tools are JProfiler and JavaVisualVM.

Synthetic class, method, and field: Synthetic class, method, and field are elements introduced by Java compiler. These are for Java’s runtime internal purposes. Java Synthetic items can be useful in debugging code. To know if a method is exposed to synthetic, we can use Java’s reflection API.

Java Bridge methods: These are intermediate methods created between source and target. Type eraser is a process of ensuring type constraints at the compile time.

Garbage Collection: Garbage collection tracks objects on heap memory and removes memory of unused objects.

Marker interface: A marker interface is an interface that has no field and no method.

Functional interface: It has a single abstract method.

Method reference: Method reference is a type of a lambda expression. There are four kinds of method references:

  • Static methods
  • Instance methods of particular objects
  • Instance methods of an arbitrary object of a particular type
  • Constructor

Class loaders: Class loaders load classes at runtime, on a need basis. There are different types of class loaders:

  • Bootstrap Class loader: Bootstrap Class loader is a part of JVM and written in native code.
  • Extension Class loader: It is a child of Bootstrap Class loader and loads extension of standard Java Classes.
  • System Class loader: A system Class loader loads application specific Classes into the JVM.
  • Custom Class loader: To load Classes outside local hard drive or network, we may need to use a customer Class loader.
  • Context Class loader: Context Class loader provides an alternative method to the class-loading delegation.

JVM shutdown hooks: JVM shutdown hooks are functions that JVM allows to run before shutting the JVM down. We can use these functions to release resources, before a JVM shuts down. A Caveat to these hooks is that JVM can run these hooks only in a normal termination. If a JVM is forced killed, it won’t get a chance to run these hooks.

Java Optional class: Java Optional class is introduced in Java 8. It is used to deal with NullPointerException.

References:

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s