Wednesday, 23 June 2021

Optimistic Lock, Concurrent timestamp

Optimistic concurrency control (OCC) is a concurrency control method applied to transactional systems such as relational database management systems and software transactional memory. OCC assumes that multiple transactions can frequently complete without interfering with each other. While running, transactions use data resources without acquiring locks on those resources. Before committing, each transaction verifies that no other transaction has modified the data it has read. If the check reveals conflicting modifications, the committing transaction rolls back and can be restarted.[1] Optimistic concurrency control was first proposed by H. T. Kung and John T. Robinson.[2]

Setting a time-stamp in a table as a column to store the entry recorded moment; in a transaction, the values are read along with the timestamp, and after operations on these values, at the moment write back newly modified values, the transaction needs to compare the previous timestamp with the current ones recorded at the Current-timestamp cell, if they are the same, then the data is consistent until now; otherwise, the transaction needs to roll back and repeating the previous the process. 



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();

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...