1. Synchronize inside the method, or the block of codes using the method in run()/call()?
  2. SynchronizeMap and HashTable, difference, efficiency, usage?
  3. Lock, reentrantLock and synchronized difference? In the assignment?


Multithread vs. parallel computing:

In java, all thread are in JVM, there is only one process. If the JVM is closed, then all threads will be closed. Thread is “small” process

Asynchronized: if there are two threads, and they share memory (share variable), it is not safe using multithreading, we may not get the value we want to get.

Dead-lock: both threads are waiting for each other

Three ways to implement multithreading:

  1. extend Thread class, (cannot extend other classes)
  2. implement Runnable (always use this one, can implement other interfaces)  implement run()
    Runnable userRequest = new UserRequest();
    Thread userRequestThread = new Thread(userRequest);
  3. implement Callable (has return value, can implement other interfaces) implement call()
    Callable response = new Response();
    ExecutorService executor = Executors.newFixedThreadPool(10);   // threads already created in the memory
    Future<Integer> future = executor.submit(response);
    System.out.println(future.get());   // do not release, JVM takes care

The Callable interface is similar to Runnable, in that both are designed for classes whose instances are potentially executed by another thread. A Runnable, however, does not return a result and cannot throw a checked exception.

Thread pool

  1. A maximum of 10 (or whatever number you desire) threads will be active processing tasks.
  2. If more than 10 tasks are submitted then they are held in a queue until threads become available.
  3. If a thread terminates due to failure during execution and prior to shutdown, a new thread is created to take its place.
  4. The threads exist till the pool is shutdown.

How to solve the asynchronized problem:

  1. use synchronized (lock)
Object lock = new Object();   // pass any object into synchronized, create a separate lock, best practice
private void increment() {
    synchronized (lock) {
        // at one time, there is only one threading working on this block of this codes. performance bottleneck


It only locks on write,  write after waiting for other operations. So it is slow, and it is not doing real multithread. performance bottleneck

put synchronized on the function name, then it will be locked to the whole class,  not efficient

2.  Reentrant lock

ReentrantLock lock = new ReentrantLock();

for(int i = 0; i< 1000000; i++) {
    lock.tryLock();  //dead lock, waiting for each other, both are false; see whether it is already locked or dead
    // locked, if it is, does not lock
    lock.unlock();  // same as synchronized block, we can have more control
return count;
  • lock在获取锁的过程可以被中断
  • lock可以尝试获取锁,如果锁被其他线程持有,则返回 false,不会使当前线程休眠
  • lock在尝试获取锁的时候,传入一个时间参数,如果在这个时间范围内,没有获得锁,那么就是终止请求
  • synchronized 会自动释放锁,lock 则不会自动释放锁

Asynchronized & synchronized collections:

Asynchronized(not locked, not safe): hashmap

首先如果多个线程同时使用put方法添加元素,而且假设正好存在两个 put 的 key 发生了碰撞(根据 hash 值计算的 bucket 一样),那么根据 HashMap 的实现,这两个 key 会添加到数组的同一个位置,这样最终就会发生其中一个线程的 put 的数据被覆盖。第二就是如果多个线程同时检测到元素个数超过数组大小* loadFactor ,这样就会发生多个线程同时对 Node 数组进行扩容,都在重新计算元素位置以及复制数据,但是最终只有一个线程扩容后的数组会赋给 table,也就是说其他线程的都会丢失,并且各自线程 put 的数据也丢失。

Synchronized(locked, not efficient): hashtable, synchronized map

Synchronized map guarantees that each atomic operation you want to run on the map will be synchronized. Running two (or more) operations on the map however, must be synchronized in a block. You must synchronize two or more method calls on the synchronizedMap object only in a case you have to rely on results of previous method call(s) in the subsequent method call in the sequence of method calls on the synchronizedMap object.

concurrenthashmap(efficient): ConcurrentHashMap synchronizes or locks on the certain portion of the Map . To optimize the performance of ConcurrentHashMap , Map is divided into different partitions depending upon the Concurrency level . So that we do not need to synchronize the whole Map Object.


Reflection makes it possible to inspect classes, interfaces, fields, annotations and methods at runtime, without knowing the names of the classes, methods etc.



single responsibility principle

open to extension(more functionality), close to modification (not supposed to change the original codes)

Liskov: interface, create instance of different subclasses implementing the same interface (automatically implemented)

Interface segregation

Dependency inversion principle?? Spring

Servlet and Filter

Web application architecture: MVC model(server) viewer controller(database) tomcat archetecture

point to the application in other paths:the output path, not the input! /WEB-INF/classes

path: the url: /javaee, reloadable = true, deployOnStartUp = true



2.servlet: map url to java class, extends HttpServlet, start from init()

different http request: get(get content from url), post

3.filter: before servlet, *: everything, implement Filter, doFilter, usage?? 分隔system features and business features (ip, authentification, permission)  (jquery)

A filter is typically used to perform a particular piece of functionality either before or after the primary functionality of a web application is performed. As an example, if a request is made for a particular resource such as a servletW and a filter is used, the filter code may execute and then pass the user on to the servlet. As a further example, the filter might determine that the user does not have permissions to access a particular servlet, and it might send the user to an error page rather than to the requested resource

session info

Spring Boot

administrator or not, have or does not have the permission

inside templates: cannot access from browser, safe

index is not safe

ajax: do not need to refresh, html(text), text loaded by Content? seperate front end and back end. cannot be crawled by google



HTML: each html tag is a dom object, div

Spring bundle (load file by Spring)

MV(view, front end)C, there are three layers on the backend (controller, business(direct call, or other functionalities), dao(data access object)) business layer cannot reach front end

anotation:repository(managed by spring container), autowired(inverson of control: does not include the dependency of the class implementing the interface, only has dependency of the interface, Spring will take care of the dependency, we can implement other classes from the interface if we have new requests, we can use autowired(qua…) to specify which subclass we are using), service(for controller, we can autowire as well)

exception handling: dao is the bottom layer, so we just throw the errors to controller (top layer), and deal with the exception in controller (upper level), because the exceptions int lower level can be cascaded everywhere, which makes the log hard to read

try resource: close the file without using try catch finally, do not need to close. closed automatically

username, password, email to a file (csv/text)

roles:administractors, users. CRUD the file: find: retrieve the list of users (tradelist); remove:on html, check box for each row, check one box, delete box, batch work, delete several rows at the same time; modify: ajax a check for each line, jump to another page or… then change

HTML(static content), JS(dynamic content)


  1. create an html for signup, in home, link the hyperlink to signUp.html in home.html, because signUp.html is in templates, the user cannot reach it. GET DATA FROM THE USER/BROWSER
  2. in MvcConfig, map the signUp url to “signup”
  3. button in signUp.html, action = /register
  4. create a controller, map to register, parameter form
  5. in the subclass of dao, create the user; in the subclass of business level, call to create a user
  6. in spring web authentication configuration, let the “signup”,”register” bypass, every one can reach this page (front end)
  7. search duplicate username
  8. put role in controller, because we can only know the role of a page in controller
  9. admin.html, cannot bypass the login page, because only the admin has the rights to modify other users, so we need to make sure the person logging in is admin

During usage: home-login-controller


rest: representational state, it is a standard

HTTP methods GET: read; PUT: save or update; POST: create, in the request body, cannot be seen in the url; DELETE

POST: @RequestBody

without ajax we can only GET

thymeleaf: template, dynamic in html, same as velocity

plainController: fixed return value (ModelAndView), if we don’t use template engine

Data Base

relational data base

ACID: atomicity(do not allow half transaction); consistency; isolation(multi-threading has the same results as one thread running); durability(does not lose data during power loss)

inner join: 先where, 后join

, group by: 先看最后的column,再依次向前

data base normalization!!!!!!!!!

  1. single value, single identity
  2. no dependency on columns

一对多:用少的引多的,多的id 座位foreign key



statement: SQL injection

prepared statement:传入值而不是sql的一部分语句


succeed or fail,每条语句是“与”的关系; container自带,改变db,多于一条sql






Spring data ORM

Unit Test

not in controller and DAO

mockito framework, supplementary of Junit


Java message service, producer-consumer problem

异步 通用传输协议

queue (FIFO): 一条消息只能被消费一次, topic:所有系统都可以消费某一条消息

load balance, loosely coupled


Service-oriented architecture,不同系统协同工作,



generic, enumerate, java8 new features (lambda, interface default ), filter

log: error, debug, info

primitative data types cannot by null (boolean, int, long…)

write file in append mode

Leave a Reply

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

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

Google photo

You are commenting using your Google 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