Wednesday, 23 June 2021

On Cascade Delete

ON DELETE CASCADE

It specifies that the child data is deleted when the parent data is deleted.


When two entities(tables) are associated, one entity pointing to another using an FK. 

A Client has many Orders, then normally FK is kept in Order, and FK references the Client PK. 

The Client is called referenced, or father table; and Order references Client and is also called Children. 

If the referenced Client is deleted, On Delete Cascade means its children are removed by cascaded operations.  


NO ACTION

It is used in conjunction with ON DELETE or ON UPDATE. It means that no action is performed with the child data when the parent data is deleted or updated.


SET NULL

It is used in conjunction with ON DELETE or ON UPDATE. It means that the child data is set to NULL when the parent data is deleted or updated.


SET DEFAULT

It is used in conjunction with ON DELETE or ON UPDATE. It means that the child data is set to their default values when the parent data is deleted or updated.


Data Integrity Issue: 

when removing the father, Children will complain because of the violation of the data integrity. The Children depend on the father, it needs to remove the Children first then removing the father. 




Java 8 OffsetDateTime and JPA 4.2 suported


OffsetDateTime consists of DateTime and the offset from the UTC, for instance

 Offset DateTime: 2021-06-23T11:27:41.622253200+02:00

It includes the current local date and time, 9-digit nanosecond, and then followed by a time zone


Java 8 has introduced java.time.packages and the JDBC 4.2 API added support for the additional SQL types

  TIMESTAMP WITH TIME ZONE and TIME WITH TIME ZONE.

 

  @Column(name = "offset_time", columnDefinition = "TIME WITH TIME ZONE")

  private OffsetTime offsetTime;

  @Column(name = "offset_date_time", columnDefinition = "TIMESTAMP WITH TIME ZONE")

  private OffsetDateTime offsetDateTime;

  

  Before Java 8 and JPA 2.2, developers usually had to convert date/time types to UTC before persisting them.   JPA 2.2 now supports this feature out of the box by supporting the offset to UTC and by leveraging JDBC 4.2  support for the timezone.


JPA @Column attribute column definition  (Optional) The SQL fragment that is used when generating the DDL for the column.

 

Saturday, 12 June 2021

JDBC Connection Thread Safety

 

 The problem with many JDBC drivers is that only one thread can use a Connection at any one time --- otherwise, a thread could send a query while another one is receiving results, and this could cause severe confusion.

The PostgreSQL™ JDBC driver is thread-safe. Consequently, if your application uses multiple threads then you do not have to worry about complex algorithms to ensure that only one thread uses the database at a time.

If a thread attempts to use the connection while another one is using it, it will wait until the other thread has finished its current operation. If the operation is a regular SQL statement, then the operation consists of sending the statement and retrieving any ResultSet (in full). If it is a fast-path call (e.g., reading a block from a large object) then it consists of sending and retrieving the respective data.

This is fine for applications and applets but can cause a performance problem with servlets. If you have several threads performing queries then each but one will pause. To solve this, you are advised to create a pool of connections. Whenever a thread needs to use the database, it asks a manager class for an object. The manager hands a free connection to the thread and marks it as busy. If a free connection is not available, it opens one. Once the thread has finished using the connection, it returns it to the manager which can then either close it or adds it to the pool. The manager would also check that the connection is still alive and remove it from the pool if it is dead. The downside of a connection pool is that it increases the load on the server because a new session is created for each object. It is up to you and your applications' requirements.

Wednesday, 9 June 2021

SMTP Sever Listening Port

As sending an email in Java or C sharp, it needs to connect to an SMTP server to send out the email message. 

The  Modern secured SMTP server is listening on port 587.

Saturday, 29 May 2021

Anonymous Class

As the name implies, an anonymous inner class isn’t defined using an explicit name.

An anonymous inner class is created when you combine instance creation with inheriting a class or implementing an interface. Anonymous classes come in handy when you wish to override methods for only a particular instance. They save you from defining new classes.

The anonymous class might override none, few, or all methods of the inherited class. It must implement all methods of an implemented interface. The newly created object can be assigned to any type of variable—static variable, instance variable, local variable, method parameter, or returned from a method. Let’s start with an example of an anonymous inner class that extends a class.



Tuesday, 18 May 2021

Thread Pool

Thread pool is a solution to limit the number of threads in usage, and so as to avoid the lower performance and system crash due to resource exhaustion.  

A thread pool is a group of pre-instantiated, idle threads that stand ready to be given work. Using a thread pool gives a better performance than creating a new thread for each task. It uses existing thread first, only having no existing available, then creating a new thread.

ExecutorService extends Executor

ScheduleExecutorService extends ExecutorService

ExecutorService manages to submit tasks much better than Executor. It accepts both Runnable and Callable.

ScheduleExecutorService manages to submit tasks and run in planned time slices.


ExecutorService offer APIs 

'IsTerminated()': testing if all submitted tasks having been accomplished.

'IsShutDown()': testing if the executor is shut down. 

'shutDownNow' means that attempting to halt active running threads, and stop picking up tasks from the queue, and returning un-implemented tasks in a collection. 'shutDownNow' is more like shutting down at once.


'shutDown' means executing previously accepted tasks, but no more task accepted; if you do add one after it; it won't give a compiling error, but a run-time exception, i.e. java.util.concurrent.RejectedExecutionException

Through ExecutorSerive, the client may submit Runnable or callable to the thread pool.

Executor consists of a queue and a pool.

Pool types: fixed-sized, single thread, scheduled thread pool, cached thread pool

The 'Executors' is a factory, where a client achieve a specific type of thread pool.

       ExecutorService es = Executors.newCachedThreadPool();

        es.execute(new PrintChar(10, 'a'));
        es.execute(new PrintNum(10, 66));
        es.execute(new PrintNum(10, 20));
        es.shutdown();

Sunday, 2 May 2021

Microservice Start up Lifecycle

When a microservice starts up, it goes through several steps in its lifecycles, i.e. Assembly, BootStrapping, Discovery, and Monitoring.  

Service assembly: 

packing all the source code and all its dependencies, together with its runtime engine in a single installable artefact. 

It can eliminate the traditional Configuration drift problem, which is due to server configuration and source are managed by different admin team and development team respectively.  

It can quickly deploy the micro-service in response to a sudden influx of requests.  

Service bootstrapping: 

The key point for service bootstrapping is how to manage its configuration file. 

Distributed microservice instances often run into the same type of configuration requirements.  With a high number, and geographically dispersed services, becomes unfeasible to redeploy services to pick up new configuration data. Storing configuration externally solves this problem. 

The configuration store should close to the service, and with minimal latency.  The most important configuration store should always up running, otherwise, it would become a single point of failure. 

When a microservice instance comes up, it calls an ending point to read its configuration, which resides in a repository that may be a relation database, files under source control, or a key-value data store.

Changes to configuration management are typically handled through the build and deployment pipeline where changes of the configuration can be tagged with version information and deployed through the different environments.

When making a configuration change, services consuming it must be notified and refresh their copies. 

Service discovery

From a client perspective, microservices should be IP transparent; all service instances behind one microservice are considered as the same physical resource. Microservice normally maintain a short life cycle, and it has a unique but non-permanent IP address assigned to it. In this way, it achieves a high degree of scalability and availability. a microservice needs to register itself with the third-party agent, thus exposing itself by a logical name, rather than a permanent IP. 

Service monitor

Most service instances will expose a health check URL that will be called by the service discovery agent. If the call returns an HTTP error or doesn't respond in a timely manner, the service discovery agent can shut down the instance or just not route traffic to it. 

Service discovery agent monitors the health of a service instance. If the instance fails, the agent will remove it from a pool of available instances. 

Can Jackson Deserialize Java Time ZonedDateTime

Yes, but must include JSR310. Thus ZonedDateTime can be deserialized directly from JSON response to POJO field. <dependency> <g...