Java 17

 Lambda Expression

  • Interface with a single abstract method is called as functional interface
    • It is denoted with annotation @FunctionalInterface
  • Anonymous Classes, are created When we implement an interface in line, the implementation is hidden, and all we have is the reference to that implementation. that is the interface implementation name
  • Lambda is replacement of anonymous functions.
  • Lambda can only be used with functional interfaces.
  • Anonymous and inheritance implementation can be used with abstract classes and interfaces.
    • It is an in place implementation
    • It is not reusable
    • They were used very often before functional interfaces.
    • In line means on the spot implementation.
    • Lambda in functional Interfaces replaces Anonymous functions.
    • Spring exclusively deals with interfaces using inversion of control.
    • Composition design pattern is easy to implement with interfaces.
    • In agile methodology, where changes are consistent interfaces are valuable.
    • Annotations provide metadata for code We are writing.
  • Interface is a pure abstract class.
  • JSR or Java specification requests Must be followed while building a JDK.
  • JDBC Specs Was released for database drivers. It is filled with interfaces and has only two classes.
    • JDBC driver releases must be based on JDBC specifications.
  • Interfaces play a vital role in consistency while development.
  • Interface once written are not modified generally.
  • Lambda is an in line representation of a code.
  • If we are inheriting from a functional interface, our child interface, which is also a functional interface must not have any abstract methods in it.
    • We can have default methods.
  • Starting Java 9 We can write, a void main Inside interface to test other default functions and static methods.
  • Whenever we declare anything in interface, it becomes public static void by default.
  • Lambda expression is writing code with more symbols and less words
    • Makes our code very concise and easy to maintain.
  • When it comes to inheritance The child interface should not be functional. That is, it should not have abstract methods.
  • Whenever we declare anything in interface, it becomes public static void by default.
  • Var is a data type whose Type is revealed at run time.
    • We can’t use other data types with var In method parameters.
    • (int a,var b)->{} won’t compile
    • Var can only be used in lambda, they can’t be used in proper methods.
    • Var Was introduced in Java 9
  • Primitives are not the part of object oriented concept of Java.
    • Primitives Don’t have get class method() So assigning them to var Is risky As we can’t determine its time.
    • Better to use var Only for objects
    • Primitives are stored on top of stack(int,float,double,bool,byte)
    • Each primitive gets a stack of a particular size.
  • When we declare primitives within the brackets they define the scope/lifetime Of Premitive
  • Garbage collection does not works on primitives.
  • Garbage collection only works with reference types, which may be available outside the scope.
  • Primitives may Have scope in class or method.
  • It is always better to use wrapper over primitives As it supports generics.
  • We can declare variables in lambda, but they will not be exposed outside.
  • Controlling of threads Is done by JVM Thread scheduler.
  • JVM consist of four parts
    • Class loader
    • Garbage collector
    • Thread Scheduler
    • Programme Access memory
      • Program managed area.
  • Thread scheduler Is responsible for managing lifetime of threads.
  • NDA-Non Deterministic Automata.
  • Default methods and multiple inheritance
    • Default methods are also called as defender methods or virtual extension methods.
    • To test default methods in interface, main method create inner class Which implements interface use its object to call default method.
  • Comparable is not used with lambda’s, Because we compare objects.
    • Comparator Is mostly used while overriding its sort method.
  • We can override and overload default methods.
  • When we implement two interfaces with same default method, then we have to override one of the methods.
  • String builder in thread safe String buffer is not.
  • Static methods can’t be overridden. They must be called with interface name as they are not inherited.
  • Predicate Joining
  • EJB(Enterprise Archive(EJB))
Predicates and Method Reference
  • A lambda expression That evaluate to either true or false is called as predicate.
  • Predicate interface is inside, Java util functions package.
  • Predicate can be passed as a parameter to a method.
  • Predicate interface has only one abstract method that is test. 
  • Whenever we declare in interface, everything becomes public, static final.
  • We can join predicates using “and”,”or”,”negate”.
  • Predicates are very useful for doing testing.
  • These are used for testing boundary value conditions.
  • Types of Packaging distributable in java.
    • Java Archive(non exec, runnable)
      • runnable has void main.
    • War
      • Web Archive
    • Ear
      • Enterprise Archive(EJB)
  • Function
    • A predicate which returns more than boolean That is any Java type is called as function.
      • A function can return any java object.
    • It is a predefined interface to return a response.
    • Bifunction Can take two Inputs and returns an output.
    • To send multiple values to a function, we use list or an array.
    • Functions are anonymous. They take parameters and return variables.
    • Predicate Takes An input type parameter and return boolean.
    • Function can take two type parameters input type And output type.
      • Second type parameter is return type.
    • Function calls apply to execute and Predicate calls test to execute.
    • Everything predicate can do function can do. But what function can do predicate cannot do.
      • Predicates can only return Boolean values. Functions can return any value.
    • Unit tests Will have no effect as far as lambda is concerned.
  • Method Reference
    • We use “::” For method reference in Java.
    • We have a functional interface, and there is a class method whose signature exactly matches the functional interface.
    • If there already exist a method with same signature, then we do not have to rewrite the method.
    • For example, we use “tostring()” method As reference from class. We also use New to create object as reference.
    • Reference means we are pointing, we are giving pointer to that method.
    • Reference can be made to static or non-static methods.
    • Using interface “disposed” within our class we can write destructor in Java class. Dispose is the destructor in Java class.
    • If we prioritise a thread in Java There is no guarantee that it will be prioritised. It all depends on JVM.
      • Set priority before we start our thread.
    • There is no guarantee that after writing destructor, garbage collector will run or not.
      • Finalise a method will not guarantee of GC run.
    • Converting, runnable to lambda.
      • It can be done by anonymous functions,Runnable Interface, Lambda, Method reference.
    • We should not use lot of static in web applications.
      • They are very dangerous
        • Web applications like spring, boot, batch, et cetera
        • Even for JSP and servlets
    • Applets are not supported by Modern JDK’s
    • When we start a thread From a thread It is called as spawning.
    • Child, thread Cannot be synchronised.
    • If we want a thread As demon thread Using setDemon() Property, it will run as background thread And response will not be displayed.
    • When using interface for method, reference to create object it just act as a mediator between program and class.
      • Program sends value to interface and interface calls the constructor.
    • It is used in factory patterns.
      • Returns the child class or implemented class Based on the parameters provided For example, we return interface with name database in abstract implementation.
      • Based on the parameters passed, we return the concerned implemented class Postgres,MySQL etc
      • Method references are best used in lambda’s.
      • When a class, which is inheriting in which the constructor is overloaded Both in parent and child. In the child constructor, we have to account for parent constructor parameters.
Util Streams
  • There are two types of streams in Java 
    • input/output streams
      • Types of input output stream
        • File input stream/File output stream
        • Buffered input stream/buffered output stream
        • Object output stream
      • These streams are designed for handling input and output operations, primarily involving external data sources or destination.
      • Input/ output streams are used for handling files.
      • They are used for handling source of data.
        • Source of data can be any Collection/File.
    • util streams.
      • Util streams are used to handle sync of data.
      • Sink of data is final destination.
      • In order to reach data in sink we need to commute it through a pipe from source.
      • These pipes are temporarily created in memory.
      • Streams provide these pipes which help data to move from source to destination.
  • Util streams are transient in nature that is temporary. They are not permanent once used they are gone permanently i.e. deleted from memory.
    • Transient means temporary only for time being.
  • To make a Stream persistent convert to a collection like Array List, Set et cetera.
  • Streams use operators to manipulate data.
  • If we try to re-use stream we get an exception.
  • There are two ways to convert anything to a stream.
  • We use supplier consumer/ consumer producer pattern on streams.
    • Consumers consumes data
    • Supplier is source like Collection or Resultset
  • Streams are in memory manipulator of data.
  • Operations on stream
    • Filter
    • Transform
    • Max
    • Min
    • Converting one stream to another stream
    • Converting it to another collection.
  • We can read stream via for each object which takes input as consumer interface.
    • A consumer has accept method.
  • Screen can only be read with consumers interface.
  • Consumers allow us to capture read data and perform operations on it.
  • Inside a stream, our data is converted into bits.
    • It speeds up processing.
  • Like streams we cannot reuse ResultSet in Java because it is a dataset curser, which is read only, forward only.
    • Streams are transient/ephemeral.
  • Streams are completely binary.
  • Create streams and use them immediately as they carry memory cost.
  • Transient objects are more effective than objects which stay in memory.
    • Stream objects are immediately garbage collected once processed.
    • Very effective way of handling data.
  • Virtual memory will never go down if we use streams
Data Structures
  • MAP is the most powerful, non-linear data structure.
    • When we are using map and related data structures, we have to use BiConsumer.
  • Linked list is the most powerful linear data structure.
    • Following structures can be prepared from Linked list.
      • Queue
      • Vector
      • Array List 
      • Set
      • Deck
  • Add comparator on SET Data structure and make it Tree Set.
  • Vector is synchronised array list.
    • Vector is thread safe array list.
    • Vectors are heavy and old, array list are fast and modern.
  • There is no queue class in Java.
    • Queue is an Interface.
  • Internally hash map also uses hash tables.
  • Hash map internally keeps two sets of data and maps so it is not organised as table internally.
    • Element from domain.
    • Element of range.
  • Hash table stores data as table. Hash tables are 16 times faster than relational databases.
    • Even JVM uses hash tables.
    • Object hash is printed when we print an object.
Data Types
  • The accuracy of float is up to 7 digits.
  • Double has 14 digits accuracy.
  • For financial applications we use BigInt, BigFloat, Big Double
    • These have more accuracy.
Try Catch Blocks
  • In void main if we are writing test code, it is better not to use to try catch blocks instead, use throws.
    • Only for custom exception use try/catch.
  • Try catch is ideal for web applications.
  • If we are using throws at method level, we will have to re throw wherever this method is called.
  • Exception in web services is used to determine faults and need to be presented to debug so there we need try catch.
File Handeling
  • In Java, -1 is the end of the file. Once the fileReader or the fileInputStream object reaches end of the file it returns -1.
JDBC
  • JDBC started off as more of C code with  Java.
  • It was initially slow. The slowness was due to interprocess communication(IPC). The C code worked slower.
  • Since version 3 and Version 4 every thing was written in Java.
  • Nowadays we also have private components in interface.
  • Generally, JDBC assumes we know the data type of column we are fetching. So we fetch using getInteger, getString, getFloat etc when we don't know we use getObject.
  • To know how many columns are there in a table using JDBC we use interface ResultSet MetaData.
  • IBatis is predecessor to Spring. It uses AOP. JDBC is compatible with most frameworks and databases and never fails.
  • Hibernate, ORM framework internally uses JDBC.
  • JPA writes queries in object oriented language so these JSQL/JPA/JPSQL queries are converted into select queries and running on top of framework.It does not work everywhere.
  • JPA queries doesn't support Postgres database directly.
  • Real-time systems/ Electronic systems don't need database. Rest all systems need database.
    • For data persistency we need database.
  • Streams are faster than JDBC as they don't require repeated connections and do in memory processing.
  • For JDBC connections, we can inject code in service the connection, but we should not write JDBC code in service as it will slow down the service.
  • In live databases where connection dropping is critical during connection pooling, we can fetch data once using SQL connection and process in memory using streams.
    • Such a situation is also very risky for transactional databases.
    • We don't have to open connections again and again while working with streams.
  • Data can also be processed in relational databases, but it is not recommended.
  • We can improve database performance by increasing the pool size, by increasing connection numbers, and by using load balancer.
    • These can be applicable on enterprise system, but not on local environments.
    • At maximum open eight connections only.
  • Most of the things we do in SQL can be done using streams.
  • While loading from properties file.
    • Create object of properties class.
    • Do properties.load(properties file) and use the property in your application.
  • Class.forName(Driver Name) is not required since JDBC4.
    • The name for database drivers is given using JNDI names.
    • JNDI is Java Naming directory interface.
    • It is a Java registry, where a driver is registered in that registry.
    • Java asks JNDI to load particular drivers from directory.
    • JNDI is Java's own registry.
  • For mysql driver name is "com.mysql.cj.jdbc.Driver"
    • cj is required only for version 8 and 9 of driver.
    • This name is given by the vendor of database.
  • Java asks JNDI to load particular driver from directory.
    • JNDI is Java's own registry
  • We don't create any objects for JDBC components like ConnectionStatement, ResultSet, DriverManager
  • Only the registered names are pulled out of the JNDI registry.
  • The registry is kept up-to-date when ever we start installing our database. It is updated automatically.
  • Even the connection string has a particular format
    • jdbc:mysql://localhost:3306/database.
  • Class.forName(driver) is used when we don't want to unload our driver before our program finishes execution.
    • We alert garbage collector for not touching our driver class. It will be unloaded eventually.
Static Block Code
  • To use static block code effectively, put it inside constructor.
    • In fact, if we use constructor, we don't have to use static.
  • In web applications, mostly we use constructors because in distributed scenarios, statics don't work effectively.
  • In normal applications, we can use statics.
  • In spring, it is better to create the object outside.
    • We create object in main which implements to interfaces, command line runner and spring application runner.
    • Use command line runner for static, initialisations and inject in application.
  • When we write a code in static method it acts as singleton. It executes only once.
  • When we do System.out.println we do not have to call toString() explicitly.
    • If we do it in any other framework such as Spring,Struts,JSF,MVC toString() needs to be called explicitly.
  • Singleton classes do not have performance as compared to static blocks.
    • Most compiler time is lost in creating additional constructors.
    • Static is factory style of creating Singleton.
  • Static blocks are only initialised once during the life span of a class.
  • Static methods are called using :: operator in Java. This was added after Java 1.9
Private Constructors
  • Private constructors are very helpful in inner classes.
    • These are used in builder pattern.
Generics
  • Generics are used to create classes, interfaces and methods that operate on various data types without requiring the exact type to be specified in advance.
    • T is used to represent Type
    • E is used to represent Elements
    • K is used to represent Key
    • N is used to represent Number
    • V is used to represent Value
  • From Java seven onwards, we don't have to mention type while initialising with new statement.
  • Genetics can be used using upper bounds
    • List<? extends Number>
    • Will accept all the classes which extend number.
Parallel Processing
  • Helps us to optimise hardware usage as our program executes on all cause of all processors on need basis.
  • It is also called as HPC(High Performance Cluster).
  • Each core is divided into one area of our HPC cluster.
  • Load balancer divides our request automatically amongst all of them.
  • Parallel stream in Java was added in 1.9
    • Parallel stream uses parallel processing.
    • Parallel stream returns unordered results.
Records
  • Model/Pojo classes are repetitive in nature.
  • There was too much of boiler plate code like toString, constructor, hash code.
  • JDBC centralised connectivity, but JDK didn't had any such feature.
  • JDK started having Records.
  • Records are thread safe.
  • Records are immutable in nature. We can't modify them.
  • Scala, Groovy are sub languages of Java.
    • Scala emphasis on the functional nature of the code.
    • There are no interfaces in Scala or groovy they have traits.
  • Never touch overloaded constructor of Records.
    • We can add additional constructor, static methods.
    • A record is a POJO but immutable POJO.
    • ToString is already implemented.
    • Constructor is already implemented.
    • Hash code is already implemented.
    • Equals method is already implemented.
  • OOPS is not enough for modern day programming.
  • Immutable classes can be modified. They cannot be overridden.
    • That is, Data can't be changed in same class.
  • Records are basically immutable classes
    • Best used for transactional data which changes fast.
  • Java is slow at processing data so the data may get changed in between for example, while persisting a database object overriding by another object all adding the same is very common scenario.
  • A record is basically a row in your database.
    • Database views cannot be parameterised.
    • Difference between table and view is view are completely read only.
    • Views are virtual tables, a sophisticated way of storing our Json.
    • Views cannot be modified. To modify the view we need to modify table view is composed of.
    • Views, are precompiled so they work faster than normal joins.
    • Stored procedure works the fastest.
    • We cannot do crud operations on view.
    • We have two engines in Mysql the default engine is InnoDb.
      • The difference between Engines is the accuracy with which they store numerical data.
      • It is known as collation order.
    • Mysql uses Transact SQL(TSQL). Also used by Sysbase, SQL Server and Mysql.
    • Superset of all SQL's is NC SQL. Every database must follow NC SQL.
    • Stored procedure is precompiled. All other SQL statements are compiled on spot. These are called as ad hoc queries.
    • A procedure is first compiled and result is stored in cache of the database
      • It has fastest execution.
      • It is used for writing business logic in backend.
      • Stored procedures are 4 times faster than adhoc queries.
      • For transactional queries we must use stored procedures.
    • In mysql we should not start stored procedure with sp.
      • If we are starting with sp don't use capital letters.
      • System stores procedures in mysql database "sys" start with "sp".
      • Mysql gets confused and starts looking for stored procedures at wrong place.
      • We call stored procedure in java using callable statement.
Queues
  • Blocking queue is useful for those working on messaging.
Dedicated Datatype Streams/Type Based Streams
  • Aggregation when done with dedicated data type stream is faster than when done on general streams.
  • There are type-based streams such as Intstream.
  • To convert an intstream back to regular stream we use "boxed()".
  • Intstream is dedicated to integers so it works faster than normal stream, can be used for Integers only.
  • DoubleStream handles float as well.There is no float stream.
  • We can print a range of numbers using Intstream we can calculate their sum.
  • SummaryStatistics() gives an overview of the stream statistics summary.
Concurrency vs Parallelism
  • Concurrency is parallelism with dependency.
  • In parallelism tasks are independent of each other.
  • In parallelism we run multiple tasks at the same time on different cores or processors.
  • Concurrency allows multiple tasks to make progress within overlapping time periods.
    • All the jobs run on same processor in concurrency.
    • Mutex, Blocks, Critical Sections were all part of concurrency in early years of Java, these are parts of multithreading.
    • They are not very effective and extremely slow.
    • Parallelism with these kind of scenarios faces blocks for example in Critical Section only one thread can enter.
    • After the lock is released on block then only next thread can enter.
    • Locking, Unlocking Blocking, Unblocking are time consuming activities.
  • Synchronisation is suitable only for existing code.
  • If its Greenfield/new code use concurrency.
Array Blocking Queue
  • Used for messaging, interprocess communication, thread communication, Asynchronous message passing.
  • As producer produces data, Consumer consumes.
  • Blocking indicates unless first value is received from queue, the second value and other values are blocked from being accessed.
    • Simulates mutex.
  • Heavily used in scenarios where there is a communication required between 2 different threads could be containers like docker.
Concurrent Hashmap
  • If we try to modify a Hashmap inside iterator we will get exception called as Concurrent Modification Exception.
    • This applies to all non-concurrent Linear and Non Linear Structures.
    • When we are reading we should not write, when we are writing we should not read.
  • Concurrent Hashmaps are thread safe.
  • While iterating we will see only values which were there once iterator was created we will not see new values.
    • We can add values while iterating
  • Concurrent Hash-maps are very well suited for multithreaded applications.
  • Map is very flexible to iterate.It does not remove values to show like Stacks and Queues.
Hashset and Linked Hashset
  • Hashset creates sets based on removing duplicates and giving unique values to each key. Saves key-value as pairs in memory.
    • Linked Hashset creates a linked list between these elements.
    • Treeset will sort these elements.
  • Add external jars to class path only do not use module path.
  • Iterator is readonly. If it notices any write operation it will throw an exception.That is why concurrent structures are needed.

Probabilistic List

  • Searching through is list is much faster than normal list be it binary search, bubble sort etc.
  • Skip list is another structure where operations are performed very fast.
Copy on write Array

  • With synchronised blocks performance is very bad.
  • Copy on Write Array List is a thread safe data structure.
    • When ever a new element is added a copy of structure is created and displayed to you.
    • Useful when we want to create a Thread safe array list.
    • Scenarios where we have time differences in communication with data structure i.e. difference in updating/reading data structures.
    •  There is delay in updating structure.
  • Vector is very slow but it is now getting enhanced with Vector API.
    • Java 21 has shown some enhancements but it is in beta phase.
  • Java 17 is LTS version i.e. Long Term Support Version.
    • We should always use LTS releases in production
    • Java 8,11,17,21 are stable for long term use.
  • There are 3 garbage collectors in Java.
  • Extension after Java 8 include Text Blocks,Switch Case Statements, Module System, Hiding of internal libraries of Java also known as Masking.
  • JVM internals are completely masked now a days i.e. they are not exposed.
  • All  the XML dependencies are removed in JDK 8 there is no XML namespace in JDK anymore.
  • Default Logger is removed in JDK
  • Optimisation is the last thing to be done on code.
  • Never compile old code in new Compiler.

Skip List

  • Arranges our elements in apartments.
  • We use concurrent navigable map to create SkipList in Java.
  • It is a probabilistic hash map as it has a probabilistic search.
    • It has a probability weight assigned to each floor which has nodes so it is fast.
  • Search for probability of an element on each floor if not skips floor.
  • SkipList is Thread safe.
  • SkipList is used for Load Balancers.
  • Very famous for search capabilities.
  • Logarithmic time is less as compared to other kinds of structures.
  • As the number of elements grow its capability increases geometrically.
  • Apache commons is a very good place to look for functionality that is not available in JDK.
    • If not available in apache commons look in Maven
JShell utility in Java
  • We can run code directly without compiling.
  • Nice place to do prototyping.
  • Shows the output of returned variable immediately.
  • Present in bin folder of JDK.
  • We can also create snippet of our code using - save /location/myfile
    • opens up the current file - edit /location/myfile
    • shows the imports in our file - /imports
    • shows history of commands - /history
  • JVM is in JRE and not in JDK.
  • We can use JConsole another tool in Java to monitor JVM.
    • It is also found in bin folder.
    • Used to check Heap memory usage.
    • Threads
    • Classes
    • CPU usage
  • VisualVM was a part till JDK 1.8
    • Download from website
    • Download plugin in IntelliJ integrate with program by providing path.
    • Shows CPU, Memory, Classes & Threads used
      • Can save heap dumps. 
    • Check classes which took maximum amount of memory.
  • Java flight recorder is a commercial product.
Virtual Threads
  • They are only assigned memory when they Are called. Else they stay in specialised area.
  • This area is called as stack chunk object.
  • Virtual threads were added in Java, 19.
  • Operating system is the owner of the threads
    • Java throws headless exception, if the operating system does not support threads.
    • Windows 95 didn't supported threads.
    • Headless means we are not allowed to create threads.
  • A virtual thread is assigned to a carrier thread which is also called as platform thread.
    • This assignment occurs only when we start at thread.
    • As it resides in heap memory like any other object. So they are more efficient than any other Thread Object.
    • When a virtual thread is not executing it resides in an area called as stack chunk object.
  • Advantages
    • Improve the application availability.
    • Improve the application throughput.
    • Improve area of memory consumption with respect to threads.
    • Improve code quality.
    • It is compatible with platform threads
  • They are different from Demon threads which run in background.
Asynchronous Programming
  • We used third-party libraries like reactive extensions in Java, for asynchronous programming.
  • Asynchronous programming was not common in Java.
  • Spring also has Rx it is called as reactive springs.
    • Instead of using threads we use events to monitor the process.
    • It is single threaded, but process is controlled by events
  • Java got this from version 17, 18, using Completable future.
    • Thread executes in future and not immediately.
    • It will wait for finishing up its execution and then it will print result.
    • A completable future is a thread which is going to be completed in future point of time.
    • Handle situations where we're not going to get response immediately but in sometime.
    • This is a best construct work in asynchronous programming.
    • We can execute to completeable futures one after the other. We can chain them, we can compose them.
    • Completeable future can't take parameter as it uses suppliers.
    • We can add a class and instantiate the same inside the future.
    • We can also make them handle exceptions.
    • They provide a flexible way to provide asynchronous non-blocking code in Java.
      • We can compose multiple asynchronous operations.
      • We can handle errors.
      • We can combine multiple completable futures in one.
Handling long text in Java
  • We use """ """ (three double quotes).
Default Package
  • If we create class in default package, they are not reusable.
Code Analysis
  • Sonar cube is a tool to perform static analysis of code.
  • E S Lint is also a very good code linter tool.
  • Another tool is PMD
Date Time API
  • Starting 1.7 Java introduced DateTime API.
  • Before this calendar class was used, which was very heavy and not thread safe.
    • It also captures local time.
  • From 1.7 onwards JODA DateTime API was merged in Java.
    • This was used as a separate library/standalone API earlier.
    • Date and Time or separated in this API.
  • We have classes which segregate date and time.
    • Local Date
    • Local Time
    • Local Date Time
    • Zone Id
Thread Scheduler in Java
  • Inside the JVM in one of the blocks out of four which is thread scheduler.
  • Inside thread scheduler Java uses a very powerful software called as Quad scheduler.
  • The code inside the quad scheduler is synchronised with atomic clocks.
  • Quad Scheduler is also available as standalone.
  • Atomic clock is most accurate clock in the world.
    • JVM uses atomic clock synchronisation when it works.
  • Internet date time server also uses atomic clocks.
Private methods in Interface
  • Java 9 we can write private methods in an interface. We can hide main functionality in interface.
    • They all called as defender methods.
    • Promotes Reusability of code.
Try with resources
  • Try with resources block is there since 1.6, but it is continuously being improved.
    • We don't require a finally block once try with resources block is used.
    • Try with Resources automatically closes with any resources opened in it, and garbage collects
    • Much needed in network connection and system resources.
    • Only classes which implement auto closable can be used in try but resources block.
      • It has mandatory close method.
File Server using Java
  • We can also create a file server using Java.
  • Since Java 18 using class SimpleFileServer.
HTTP Client
  • We use HttpClient or RestTemplate to get response from web services.
  • HttpClient uses HttpRequest and HttpResponse to send request and get a response respectively.
  • HttpClient was added to Java 18.
  • We can mock test our services.
Serialisation
  • We can serialise immutable types easily in Java, 18.
    • List.of() returns an immutable list.
Modules
  • When we want to share resources between projects in our system, it is better to expose them as modules.
  • If we don't want some classes/packages to be shared in Jar, we should use modules.
  • We create a module-info.java class where we define classes/packages to be shared.
    • Module let us share a Code conditionally.
Self Compilation
  • After Java 9, we don't need Javac. Directly,  java command runs the file.
  • We just need to compile once each time we modify it Auto compiles.

Optimisation Tools
  • jDeps is used to list the dependencies in your jar.
    • jdeps --list-deps *.jar.
    • It is a part of JDK
  • jDeprscan
    • tells us the classes that we can remove from our project so that it supports new release.
    • called as jDeprecation scanner (Java Depreciation Scanner)
    • jdeprscan --class-path *.jar -l
      • we can also specify specific release with --release.
      • jdeprscan --class-path *.jar -l --release 18
    • It is a part of JDK
  • GraphViz
    • Create a dot file of the jar file from jdeps tool
      • jdeps --recursive -dotoutput . file.jar
    • Not a part of JDK
    • We can visualise dependencies in our jar.
    • On the generated dot file run
      • dot -/png myproj.jar.dot -o mygraph.png
    • It is a dependency walker of our project.
  • Above tools are helpful while migration of code.
  • We can analyse Heap Dumps in Memory Analyser Tail by eclipse(eclipse MAT) to improve performance of Applications.
    • Use Visual VM to generate Heap Dumps with HPOF Headers.
    • Track Leak suspects report.
  • Another online Heap Analysis tool is Heap Hero to analyse the heaps using heap dump files.
  • We can use JCommand(JCmd) and JMAt to generate heap dumps.
  • MBeans and Diagnostics are another tool where Beans can be called from code.
  • There are 3 types of Heap
    • Unused Heap 
    • Shallow Heap
    • Heap where object is created and not deleted with Garbage Collector especially with Memory out of Bounds error.
Garbage Collectors
  • Types of Garbage Collectors
    • G1GC
    • ZGC
    • parallelGC
    • parallel full GC
    • Shenandoah
  • We may speed up our project by shifting between GC's in our project.
  • Shenandoah works better over the other Garbage Collectors. It is the fastest
    • It is not available in Oracle JVM's but in other JVM's
Online Java Compilers

No comments:

Post a Comment