Lang-Java

个人笔记,方便自己查阅使用

Contents

  • Java Lang
    • Assignment, Reference
    • Data types & Structures & Related Interfaces
      • Array (Arrays.)
      • ArrayList
      • Character
      • Collection: java.util.Collection
        • List
          • Vector
        • Set
        • Queue
        • HashMap, HashTable -> Map接口
      • String
        • operator + (string concatenation)
        • reverse
        • String pool (String s=new String("abc")创建了几个对象?)
      • StringBuilder
        • concatenation
      • HashMap
      • Queue
        • BlockingQueue
        • PriorityQueue
      • TreeMap
    • Date & Locale
    • Exception
    • Garbage Collection
    • File I/O
    • Functions
      • sorting
    • Regex
      • Matching
      • String.replaceAll()
    • Structures-Lang
      • generic arguments
      • Loop
    • OOP
      • Class
        • Nested Class
        • Static Class
      • Objects
        • Cloning/ Copy (Shallow/Deep)
        • Scope
  • Topics==>Libs/Frameworks, etc.
    • Installation & Deployment Issues
    • Compilation&Packaging&Distribution
      • JIT (vs. conventional compiler, interpreter)
    • Concurrency
      • Nonblocking & CAS
      • Java Concurrency Tutorial
      • GuardedBlocks
      • BlockingQueue
      • ConcurrentHashMap
      • Lock
    • Database Access: JDBC
      • Graphics
    • Hadoop
    • HBase
    • Manager: Maven
    • Net
    • Http
      + java.net.HttpUrlConnection
    • Thread
      • Executor
      • Runnable Interface - Thread 继承
      • ThreadPoolExecutor & Executor Service
        • Executor service
          • future, callable, runnable
          • submit
          • shutdown
        • ThreadPoolExecutor
      • Future & FutureTask
      • JRuby's threadpooling
    • Time
    • Vert.x
    • WebServer - Tomcat
      • java ee
      • Servlet

Java Lang

Assignment, Reference

Java引用变量赋值

Box b1 = new Box();

Box b2 = b1;

System.out.println(b1==b2);//true

你可能认为b1和b2引用的是不同的对象,但实际b1和b2引用同样的对象。将b1赋值给b2并没有分配任何内存或对原对象做任何部分的拷贝。它们指向同一个对象,因此对变量b2的改变也将影响b1。

尽管b1和b2都引用同一个对象,但是他们之间没有任何其他的关系。例如,接下来对b1的赋值仅仅使b1脱离初始对象,而没有影响对象或影响b2。

Box b1 = new Box();

Box b2 = new Box();

b2 = b1;

// ...

b1 = null;

这里,b1被设置为空,但是b2仍然指向原来的对象。

当你将一个对象引用赋值给另一个对象引用时,你并没有创建该对象的一个拷贝,而是仅仅对该对象的引用的一个拷贝。

Data types & Structures

Array (Arrays.)

  • 如何高效地判断数组中是否包含某特定值
    • Arrays.asList(arr).contains(targetValue);
    • Set<String> set = new HashSet<String>(Arrays.asList(arr)); return set.contains(targetValue);
  • Java数组 Basics
    • 只要数组创建了,每一个索引被初始化为默认值。 (0对于整数,0.0对于浮点数)
    • int[] i = new int[10];
    • 负数索引在Java中是无效的,会抛出ArrayIndexOutOfBoundException
    • 数组一个固定长度 的数据结构,一旦声明,你不能改变数组的长度。
    • 不同类型的数组有不同的类型intArray.getClass()不同于floatArray.getClass()
    • create
      • int[] intArray;
      • int intArray[];
      • int[] intArray = new int[10];
      • int[] intArray = new int[]{1,2,3,4};
    • java基本类型数组初始化

(Arrays.)

  • This class contains various methods for manipulating arrays (such as sorting and searching). This class also contains a static factory that allows arrays to be viewed as lists.
  • DOC Arrays
    • asList()
    • equals(a, b)
    • fill()
    • sort()

ArrayList

Character

  • DOC
    • isLetterOrDigit(), isLetter(), isDigit()
    • digit(char ch, int radix)
      Returns the numeric value of the character ch in the specified radix.
    • equals()

Collection: java.util.Collection

  • java.util.Collection 接口是描述 Set 和 List 集合类型的根接口,其中定义了有关集合操作的普遍性方法(部分)
  • java.util.Collection 接口
  • Java集合类详解
    • 所有实现Collection接口的类都必须提供两个标准的构造函数:无参数的构造函数用于创建一个空的Collection,有一个 Collection参数的构造函数用于创建一个新的Collection,这个新的Collection与传入的Collection有相同的元素。后一个构造函数允许用户复制一个Collection。
    • 如何遍历Collection中的每一个元素?不论Collection的实际类型如何,它都支持一个iterator()的方法,该方法返回一个迭代子,使用该迭代子即可逐一访问Collection中每一个元素
      • Iterator it = collection.iterator(); // 获得一个迭代子     while(it.hasNext()) {       Object obj = it.next(); // 得到下一个元素     }

List

  • LinkedList实现了List接口,允许null元素。此外LinkedList提供额外的get,remove,insert方法在 LinkedList的首部或尾部。这些操作使LinkedList可被用作堆栈(stack),队列(queue)或双向队列(deque)。
  • ArrayList实现了可变大小的数组。它允许所有元素,包括null。ArrayList没有同步。
  • Vector非常类似ArrayList,但是Vector是同步的
  • Stack 类
      + Stack继承自Vector,实现一个后进先出的堆栈。Stack提供5个额外的方法使得Vector得以被当作堆栈使用。基本的push和pop 方法,还有peek方法得到栈顶的元素,empty方法测试堆栈是否为空,search方法检测一个元素在堆栈中的位置。Stack刚创建后是空栈。

Set

  • Set是一种不包含重复的元素的Collection,即任意的两个元素e1和e2都有e1.equals(e2)=false,Set最多有一个null元素。
  • Set的构造函数有一个约束条件,传入的Collection参数不能包含重复的元素。

Queue

Queue接口与List、Set同一级别,都是继承了Collection接口。

java中queue的使用

jenkov Java Collections - Queue

Since Queue is an interface you need to instantiate a concrete implementation of the interface in order to use it. You can choose between the following Queue implementations in the Java Collections API:

java.util.LinkedList
java.util.PriorityQueue

LinkedList is a pretty standard queue implementation.

Queue queueA = new LinkedList();
Queue queueB = new PriorityQueue();

Map

  • Map接口没有继承Collection接口,Map提供key到value的(1v1)映射。
  • Hashtable继承Map接口,实现一个key-value映射的哈希表。任何非空(non-null)的对象都可作为key或者value。
  • HashMap和Hashtable类似,不同之处在于HashMap是非同步的,并且允许null,即null value和null key。
    • 将HashMap视为Collection时(values()方法可返回Collection),其迭代子操作时间开销和HashMap 的容量成比例。

Summary

  • 涉及到堆栈,队列等操作,应该考虑用List,对于需要快速插入,删除元素,应该使用LinkedList,如果需要快速随机访问元素,应该使用ArrayList。
  • 如果程序在单线程环境中,或者访问仅仅在一个线程中进行,考虑非同步的类,其效率较高,如果多个线程可能同时操作一个类,应该使用同步的类。

String

  • String是不可变对象

  • String 是对象,所以比较值相等要用.equals()

  • How do I compare strings in Java?

    • == tests for reference equality (whether they are the same object).
    • .equals() tests for value equality (whether they are logically "equal").
  • operator + (string concatenation)

    • The result of string concatenation is a reference to a (new) String object that is the concatenation of the two operand strings. The characters of the left-hand operand precede the characters of the right-hand operand in the newly created string.
  • Reverse

String pool

  • String s=new String("abc")创建了几个对象?
    • 2 个
    • 在JAVA虚拟机(JVM)中存在着一个字符串池,其中保存着很多String对象,并且可以被共享使用,因此它提高了效率。由于String类是final的,它的值一经创建就不可改变,因此我们不用担心String对象共享而带来程序的混乱。字符串池由String类维护,我们可以调用intern()方法来访问字符串池。

StringBuilder

HashMap

  • HashMap Doc
  • HashMap Vs. ConcurrentHashMap Vs. SynchronizedMap – How a HashMap can be Synchronized in Java
    • You should use ConcurrentHashMap when you need very high concurrency in your project.
    • It is thread safe without synchronizing the whole map.
    • Reads can happen very fast while write is done with a lock.
    • There is no locking at the object level.
    • The locking is at a much finer granularity at a hashmap bucket level.
    • ConcurrentHashMap doesn’t throw a ConcurrentModificationException if one thread tries to modify it while another is iterating over it.
    • ConcurrentHashMap uses multitude of locks.

HashMap详细介绍(源码解析)和使用示例

  • HashMap 是一个散列表,它存储的内容是键值对(key-value)映射。

  • HashMap 继承于AbstractMap,实现了Map、Cloneable、java.io.Serializable接口。

  • HashMap 的实现不是同步的,这意味着它不是线程安全的。

  • HashMap 的实例有两个参数影响其性能:“初始容量” 和 “加载因子”。容量 是哈希表中桶的数量,初始容量 只是哈希表在创建时的容量。加载因子 是哈希表在其容量自动增加之前可以达到多满的一种尺度。当哈希表中的条目数超出了加载因子与当前容量的乘积时,则要对该哈希表进行 rehash 操作(即重建内部数据结构),从而哈希表将具有大约两倍的桶数。

  • 通常,默认加载因子是 0.75, 这是在时间和空间成本上寻求一种折衷。加载因子过高虽然减少了空间开销,但同时也增加了查询成本(在大多数 HashMap 类的操作中,包括 get 和 put 操作,都反映了这一点)。在设置初始容量时应该考虑到映射中所需的条目数及其加载因子,以便最大限度地减少 rehash 操作次数。如果初始容量大于最大条目数除以加载因子,则不会发生 rehash 操作。

  • Java中关于HashMap的使用和遍历

    • HashMap<String, String> hashMap = new HashMap<String, String>();

Queue

Blocking Queue

  • Java多线程(五)之BlockingQueue深入分析
  • Java中的阻塞队列
  • 阻塞队列(BlockingQueue)是一个支持两个附加操作的队列。
    • 两个附加的操作是:在队列为空时,获取元素的线程会等待队列变为非空。当队列满时,存储元素的线程会等待队列可用。
    • 阻塞队列常用于生产者和消费者的场景,生产者是往队列里添加元素的线程,消费者是从队列里拿元素的线程。阻塞队列就是生产者存放元素的容器,而消费者也只从容器里拿元素。

Priority Queue

  • java优先队列 PriorityQueue
  • 优先级队列是不同于先进先出队列的另一种队列。每次从队列中取出的是具有最高优先权的元素。
  • 如果不提供Comparator的话,优先队列中元素默认按自然顺序排列,也就是数字默认是小的在队列头,字符串则按字典序排列。

TreeMap

TreeMap详细介绍(源码解析)和使用示例

  • TreeMap 是一个有序的key-value集合,它是通过红黑树实现的。
  • TreeMap 继承于AbstractMap,所以它是一个Map,即一个key-value集合。
  • TreeMap 实现了NavigableMap接口,意味着它支持一系列的导航方法。比如返回有序的key集合。
  • TreeMap 实现了Cloneable接口,意味着它能被克隆。
  • TreeMap 实现了java.io.Serializable接口,意味着它支持序列化。

Date & Locale

SimpleDateFormat

  • DOC SDF
  • Example for parsing
  • Q: parse (Full) Month name???
    • You should choose a correct locale for a formatter. For example, if you want to parse dates in English:
    • SimpleDateFormat df=new SimpleDateFormat(pattern, Locale.US);
    • Or it will get errors if your locale is not US or UK
    • How to parse a date?

Garbage Colletion

  • 根据介绍Java的书籍的叙述,Java没有任何方式可以显式地删除一个对象(即Java没有提供任何办法让你能立即释放一个不使用的内存)。Java虚拟机有垃圾回收机制帮助管理内存,垃圾回收机制的原则是:如果一个内存地址没有被任何地方引用,则垃圾回收器会在运行的时候将它释放掉。所以如果你要释放一个对象所占用的内存的话,只有一个办法:将这个对象的所有引用置为空,然后等待垃圾回收器下一次运行时将它回收掉。
  • Java垃圾回收机制
  • GC广泛讨论->java垃圾回收机制

File I/O

Read

Write

  • How to write to file in Java – BufferedWriter
  • How to Write a File Line by Line in Java?
    • FileOutputStream
    • FileWriter
    • PrintWriter
    • OutputStreamWriter
  • PrintWriter offers some additional methods for formatting such as println and printf.
  • FileWriter throws IOException in case of any I/O failure.
  • PrintWriter methods do not throws IOException, instead they set a boolean flag which can be obtained using checkError().
  • PrintWriter automatically invokes flush after every byte of data is written. In case of FileWriter, caller has to take care of invoking flush.

Functions

Sorting

  • How to sort ArrayList in Java
    • ArrayList<String>: Collections.sort(arraylist) method. The output List will be sorted alphabetically.
    • ArrayList<Integer>: Collections.sort(arraylist) ascending
  • int[] arr : Arrays.sort(arr)
    • (Java.util.Arrays.sort(int[]))
    • using QuickSort:
      • Why Arrays.sort is quicksort algorithm, why not another sort algorithm?
      • Quicksort has O(n log n) average and O(n^2) worst case performance, that is the best "average case" a sort algorithm can be, there are other sort algorithms that have this performance, but quicksort tends to perform better than most.
      • wiki merge sort
      • In Java, the Arrays.sort() methods use merge sort or a tuned quicksort depending on the datatypes and for implementation efficiency switch to insertion sort when fewer than seven array elements are being sorted.[16] Python uses Timsort, another tuned hybrid of merge sort and insertion sort, that has become the standard sort algorithm in Java SE 7,[17] on the Android platform,[18] and in GNU Octave.

Regex

  • \p{Alpha} -->POSIX, check doc pattern

  • \W is the opposite of \w, \P for \p likewise.

  • 用String表示正则表达式时,需要转义,比如:

    String s2 = s.replaceAll("\W",""); // correct, you want to use \W to denote all non-word chars
    String s2 = s.replaceAll("\W",""); // incorrect, \W is wrong escaping

Matching

java.util.regex包主要包括以下三个类:

Pattern类:

pattern对象是一个正则表达式的编译表示。Pattern类没有公共构造方法。要创建一个Pattern对象,你必须首先调用其公共静态编译方法,它返回一个Pattern对象。该方法接受一个正则表达式作为它的第一个参数。
Matcher类:

Matcher对象是对输入字符串进行解释和匹配操作的引擎。与Pattern类一样,Matcher也没有公共构造方法。你需要调用Pattern对象的matcher方法来获得一个Matcher对象。
PatternSyntaxException:

PatternSyntaxException是一个非强制异常类,它表示一个正则表达式模式中的语法错误。
  • differences among greedy, reluctant, and possessive quantifiers in Java patterns?
  • doc: Pattern
  • Workflow1
    • Pattern p = Pattern.compile(regex)
    • Matcher m = p.matcher(str)
    • m.matches() will try to match the whole str against the pattern
      • m.find() Attempts to find the next subsequence of the input sequence that matches the pattern. So call we can continuously call m.find() until it returns false.
    • m.group(x) will give the match items resulted from former operations
    • when using m.matches(), m.group(0) will give us the entire string if matched.

String.replaceAll()

  1. in java: whenever you need regex in a function/method, you would give it a string,
    // the regex would look like the string after string escaped.
    // e.g.: String s2 = s.replaceAll("\W",""); // correct, you want to use \W to denote all non-word chars
    // String s2 = s.replaceAll("\W",""); // incorrect, \W is wrong escaping
    // http://www.vogella.com/tutorials/JavaRegularExpressions/article.html
    // http://www.runoob.com/java/java-regular-expressions.html
    //
  2. \W => [^A-Za-z0-9_] rather than wholy nonalphanumeric
  3. String does not have .reverse() while StringBuilder does
  4. String's replace(), replaceAll(), toLowerCase() and others do not change the original string

Structures-Lang

generic arguments

You can't use primitive types as generic arguments in Java. E.G:

Map<String, Integer> myMap = new HashMap<String, Integer>(); // correct
HashMap<String, int> // incorrect

Loop

Java 增强循环

for(声明语句 : 表达式)
{
//
}

for(int x : numbers )

OOP

Class

Nested Class

  • java嵌套类(Nested Classes)总结
  • 用Static修饰的Nested Classes,只能访问外部类的非static变量。
  • inner member classes(内部成员类) 可以访问外部类的所有实例属性,静态属性。因为内部成员类持有一个外部对象的引用,内部类的实例可以对外部类的实例属性进行修改。
    • Inner Classes 不能定义为static,不能有static方法和static初始化语句块。

Static Class

Objects

Cloning/ Copy (Shallow/Deep)

A shallow copy just copies the values of the references in the class. A deep copy copies the values.

  • A guide to object cloning in java

    • A clone is an exact copy of the original. In java, it essentially means the ability to create an object with similar state as the original object.
    • The clone() method provides this functionality.
  • Shallow Cloning (clone())

    • This is default implementation in java. In overridden clone method, if you are not cloning all the object types (not primitives), then you are making a shallow copy.
  • Deep cloning

    • It is the desired behavior in most the cases. We want a clone which is independent of original and making changes in clone should not affect original.
  • e.g. Difference Between Shallow Copy Vs Deep Copy In Java

  • Java Clone, Shallow Copy and Deep Copy

    • Object class provides a clone method and provides support for the shallow copy. It returns ‘Object’ as type and you need to explicitly cast back to your original object
    • When the copied object contains some other object its references are copied recursively in deep copy.
  • Faster Deep Copies of Java Objects

Scope

Topics ==> Libs/Frameworks

Installation & Deployment Issues

Mac

Compilation&Packaging&Distribution

javac -classpath hadoop-common-2.4.0-amzn-3.jar:hadoop-mapreduce-client-core-2.4.0-amzn-3.jar:hadoop-mapreduce-client-common-2.4.0-amzn-3.jar:hadoop-annotations-2.4.0.jar:commons-cli-1.2.jar:hbase-0.94.18.jar -d lm_classes LangModel.java

jar -cvf lm.jar -C lm_classes/ .

指定用以查找类或接口定义的源代码路径。与用户类路径一样,源路径项用分号 (;) 进行分隔,它们可以是目录、JAR 归档文件或 ZIP 归档文件。如果使用包,那么目录或归档文件中的本地路径名必须反映包名。

注意:通过类路径查找的类,如果找到了其源文件,则可能会自动被重新编译。

JIT (vs. conventional(AOT) compiler, interpreter)

  • jit: Java code -> bytecode
  • jit vs. interpreter
    • In the case of interpreters, the virtual machine executes a native JVM procedure corresponding to each instruction in byte code to produce the expected behaviour. But your code isn't actually compiled to native code, as with Jit compilers. The JVM emulates the expected behaviour for each instruction.
  • Understanding the differences: traditional interpreter, JIT compiler, JIT interpreter and AOT compiler
    • The terms Ahead-of-Time (AOT) and Just-in-Time (JIT) refer to when compilation takes place: the "time" referred to in those terms is "runtime", i.e. a JIT compiler compiles the program as it is running, an AOT compiler compiles the program before it is running.

Concurrency

volatile

  • 聊聊并发(一)——深入分析Volatile的实现原理
    • Volatile是轻量级的synchronized,它在多处理器开发中保证了共享变量的“可见性”。可见性的意思是当一个线程修改一个共享变量时,另外一个线程能读到这个修改的值。
    • Volatile变量修饰符如果使用恰当的话,它比synchronized的使用和执行成本会更低,因为它不会引起线程上下文的切换和调度。
    • 有volatile变量修饰的共享变量进行写操作的时候会多第二行汇编代码,通过查IA-32架构软件开发者手册可知,lock前缀的指令在多核处理器下会引发了两件事情。
      1. 将当前处理器缓存行的数据会写回到系统内存。
      2. 这个写回内存的操作会引起在其他CPU里缓存了该内存地址的数据无效。

Nonblocking & CAS

  • CAS Wiki
    • compare-and-swap (CAS) is an atomic instruction used in multithreading to achieve synchronization. It compares the contents of a memory location to a given value and, only if they are the same, modifies the contents of that memory location to a given new value. This is done as a single atomic operation.
  • Non-blocking linked list wiki
    • implement a linked list in shared memory using synchronization primitives
    • A non-blocking algorithm is lock-free if there is guaranteed system-wide progress, and wait-free if there is also guaranteed per-thread progress.
  • 非阻塞同步算法与CAS(Compare and Swap)无锁算法
    • 锁是用来做并发最简单的方式,当然其代价也是最高的。内核态的锁的时候需要操作系统进行一次上下文切换,加锁、释放锁会导致比较多的上下文切换和调度延时,等待锁的线程会被挂起直至锁释放。在上下文切换的时候,cpu之前缓存的指令和数据都将失效,对性能有很大的损失。
  • 乐观锁与悲观锁
    • 独占锁是一种悲观锁,synchronized就是一种独占锁,它假设最坏的情况,并且只有在确保其它线程不会造成干扰的情况下执行,会导致其它所有需要锁的线程挂起,等待持有锁的线程释放锁。
    • 而另一个更加有效的锁就是乐观锁。所谓乐观锁就是,每次不加锁而是假设没有冲突而去完成某项操作,如果因为冲突失败就重试,直到成功为止。
  • 与锁相比,volatile变量是一和更轻量级的同步机制,因为在使用这些变量时不会发生上下文切换和线程调度等操作,但是volatile变量也存在一些局限:不能用于构建原子的复合操作,因此当一个变量依赖旧值时就不能使用volatile变量。(参考:谈谈volatiile)
    • volatile只能保证变量对各个线程的可见性,但不能保证原子性。
  • CAS无锁算法
    • 要实现无锁(lock-free)的非阻塞算法有多种实现方法,其中CAS(比较与交换,Compare and swap)是一种有名的无锁算法。CAS, CPU指令,在大多数处理器架构,包括IA32、Space中采用的都是CAS指令,CAS的语义是“我认为V的值应该为A,如果是,那么将V的值更新为B,否则不修改并告诉V的值实际为多少”.
    • CAS是项乐观锁技术,当多个线程尝试使用CAS同时更新同一个变量时,只有其中一个线程能更新变量的值,而其它线程都失败,失败的线程并不会被挂起,而是被告知这次竞争中失败,并可以再次尝试
  • CAS(比较并交换)是CPU指令级的操作,只有一步原子操作,所以非常快。而且CAS避免了请求操作系统来裁定锁的问题,不用麻烦操作系统,直接在CPU内部就搞定了。但CAS就没有开销了吗?不!有cache miss的情况。

Java Concurrency Tutorial

Java Concurrency Tutorial

  • two basic strategies for using Thread objects to create a concurrent application.
    • To directly control thread creation and management, simply instantiate Thread each time the application needs to initiate an asynchronous task.
    • To abstract thread management from the rest of your application, pass the application's tasks to an executor.
  • Interrupt
    • A thread sends an interrupt by invoking interrupt() on the Thread object for the thread to be interrupted.
    • For the interrupt mechanism to work correctly, the interrupted thread must support its own interruption.
    • Interrupt可以是该程序的main中发出。
  • join
    • allows one thread to wait for the completion of another.

Synchronization (Synchronized)

Threads communicate primarily by sharing access to fields and the objects reference fields refer to. This form of communication is extremely efficient, but makes two kinds of errors possible: thread interference and memory consistency errors. The tool needed to prevent these errors is synchronization.

Synchronization can introduce CONTENTION.

  • Thread Interference
  • Memory Consistency
    • different threads have inconsistent views of what should be the same data.
    • happens-before relationship

The Java programming language provides two basic synchronization idioms: synchronized methods and synchronized statements.

  • Synchronized Methods

    • simply add the synchronized keyword to its declaration
    • --> no interleaving for 2 invocations of the same synchronized methods
    • --> when a synchronized method exits, it automatically establishes a happens-before relationship with any subsequent invocation of a synchronized method for the same object.
    • constructors cannot be synchronized — using the synchronized keyword with a constructor is a syntax error.
    • Synchronized methods enable a simple strategy for preventing thread interference and memory consistency errors: if an object is visible to more than one thread, all reads or writes to that object's variables are done through synchronized methods.
  • ? What happens when a static synchronized method is invoked?

  • ! the thread acquires the intrinsic lock for the Class object associated with the class. Thus access to class's static fields is controlled by a lock that's distinct from the lock for any instance of the class.

  • Intrinsic Locks and Synchronization

    • Synchronization is built around an internal entity known as the intrinsic lock or monitor lock.
    • Every object has an intrinsic lock associated with it.
    • 当线程调用同步方法时,它自动获得这个方法所在对象的内在锁,并且方法返回时释放锁,如果发生未捕获的异常,也会释放锁。
    • 当调用静态同步方法时,因为静态方法和类相关联,线程获得和这个类关联的Class对象的内在锁
  • Synchronized Statements

    • synchronized statements must specify the object that provides the intrinsic lock
    • needs to avoid synchronizing invocations of other objects' methods.
      • --> Liveness Problem
    • Reentrant Synchronization
      • Allowing a thread to acquire the same lock more than once enables reentrant synchronization.
      • without which it'll be very difficult to ensure that a thread in Java doesn't block itself.
  • synchronized锁住的是代码还是对象

    • synchronized锁住的是括号里的对象,而不是代码。对于非static的synchronized方法,锁的就是对象本身也就是this。
    • ?这也就是说,不同的thread,只要不寻求synchronized的相同对象,即可以同时执行。比如链表的并发。
  • Java的synchronized关键字:同步机制总结

Guarded Blocks

Blocking Queue

ConcurrentHashMap

Lock

Database Access: JDBC

Concepts:

  • TLDR:
    • java application -> jdbc api -> jdbc driver manager -> jdbc driver -> data source
    • Entities required: SQL database, database driver (a jar)
  • JDBC provides portable access to various databases
    • no need to develop different code for different dbs
  • JDBC Driver
    • provides connection to a DB
    • converts JDBC calls to a specific DB
    • implementations provided by DB vendor
  • JDBC Driver Manager (JDBC Driver Automatically Loaded to Classpath after JDBC 4.0)
  • Glossary& Notes

Connection Pools

  • JDBC Connection Pooling Best Practices

    • TLDR:
      • Creation: Expensive; mav
      • Garbage collection: Expensive;
      • --> Recycling the objects (conenctions): do not destroy it when used.
      • --> for short lifetime objects
    • Reasons to use:
      • Object pooling is effective for two simple reasons. First, the run time creation of new software objects is often more expensive in terms of performance and memory than the reuse of previously created objects. Second, garbage collection is an expensive process so when we reduce the number of objects to clean up we generally reduce the garbage collection load.
      • Database connections are often expensive to create because of the overhead of establishing a network connection and initializing a database connection session in the back end database
      • the database's ongoing management of all of its connection sessions can impose a major limiting factor on the scalability of your application.
  • OracleDoc: Configuring JDBC Connection Pools

c3p0

C3P0 is a library for augmenting traditional (DriverManager-based) JDBC drivers with JNDI-bindable DataSources, including DataSources that implement Connection and Statement Pooling, as described by the jdbc3 spec and jdbc2 std extension.

calls for mchange-commons-java

Usage

Graphics

Displaying graphics in swing

    import java.awt.*;  
    import javax.swing.JFrame;  
      
    public class DisplayGraphics extends Canvas{  
          
        public void paint(Graphics g) {  
            g.drawString("Hello",40,40);  
            setBackground(Color.WHITE);  
            g.fillRect(130, 30,100, 80);  
            g.drawOval(30,130,50, 60);  
            setForeground(Color.RED);  
            g.fillOval(130,130,50, 60);  
            g.drawArc(30, 200, 40,50,90,60);  
            g.fillArc(30, 130, 40,50,180,40);  
              
        }  
            public static void main(String[] args) {  
            DisplayGraphics m=new DisplayGraphics();  
            JFrame f=new JFrame();  
            f.add(m);  
            f.setSize(400,400);  
            //f.setLayout(null);  
            f.setVisible(true);  
        }  
      
    }  
image.png

graphics是Java提供的用于绘图和显示格式化文字的工具。绘图必须在一个窗口(容器)中进行

Container类是java.awt.Component类的子类,JComponent类又继承自Container类。因此,JComponent类是AWT和Swing的联系之一。
除了Swing顶层容器类(top level containers)以外,其余所有的Swing组件类都继承自JComponent类(例如JPanel),如前所述,JComponent类是Container类的子类,因此,所有的Swing组件都可作为容器使用。
Swing顶层容器类包括了JFrame、JDialog、JApplet、JWindow,它们为其他的Swing组件提供了绘制自身的场所。

graphics是一个抽象类,其实现大都是平台相关的,所以不容易自己创建一个graphics实例。一般graphics的实例会由依照你所在的桌面环境给出。Graphics类及其子类Graphics2D提供的只是一些基本绘图方法,比如画直线、曲线什么的。所以做一个图形组件的基本思路可以总结为以下过程:
选择适合的基本图形组件->继承它->重写paint等方法->在需要刷新图形的时候调用repaint等方法

Swing是一个高层的GUI系统,而不像AWT那样与运行平台技术更加靠近的系统。Swing的类继续关系比AWT要复杂的多,而且Swing类大多都经过了中间的转接类-JComponent。而我们常用的JFrame则另辟蹊径,从awt的window继续了下来。
这种结构关系决定了Swing的庞大与复杂性。很多初学者都难以理解Swing的模式和结构。
Swing 中的控件都是利用Java图形功能绘制出来的,而不是对应到平台的一个具体控件实现。我们所用的所有Swing控件都是直接或者间接用Graphics绘制出来的,这种实现方式最大的好处是很灵活,我们想要什么样的控件,就直接用Graphics绘制出来就是了。
Sun之所以用这种方式来实现,是为了在不牺牲移植性的基础上加入丰富的界面交互功能。

但是缺点也很明显:Swing的速度和效率是所有GUI(图形用户界面Graphical User Interface)系统中最慢的。

Graphics 类相当于一个画布,每个 Swing 组件都通过 Graphics 对象来绘制显示。

Hadoop

HBase

Manager: Maven

Tutorials

  • Maven生命周期详解
    • Maven强大的一个重要的原因是它有一个十分完善的生命周期模型(lifecycle),这个生命周期可以从两方面来理解,第一,顾名思义,运行Maven的每个步骤都由它来定义的,这种预定义的默认行为使得我们使用Maven变得简单,相比而言,Ant的每个步骤都要你手工去定义。第二,这个模型是一种标准,在不同的项目中,使用Maven的接口是一样的,这样就不用去仔细理解每个项目的构建了
    • Maven有三套相互独立的生命周期,请注意这里说的是“三套”,而且“相互独立”,初学者容易将Maven的生命周期看成一个整体,其实不然。这三套生命周期分别是:
    • Clean Lifecycle 在进行真正的构建之前进行一些清理工作。
    • Default Lifecycle 构建的核心部分,编译,测试,打包,部署等等。
    • Site Lifecycle 生成项目报告,站点,发布站点。
  • Jenkov: Maven Tutorial
  • Overview of Maven core concepts
  • Apache: Maven Getting Started Guide

Refs

Notes

  • Maven build lifecycle
    • Maven is run by phases, read this default Maven build lifecycle article for more detail. So, when the “package” phase is executed, all its above phases – “validate“, “compile” and “test“, including the current phase “package” will be executed orderly.
  • Maven uses Java when executing, there is a dependency!
    • The JRE does not contain a Java compiler. Only the SDK does.
  • Dependencies are external JAR files (Java libraries) that your project uses.
    • If the dependencies are not found in the local Maven repository, Maven downloads them from a central Maven repository and puts them in your local repository. The local repository is just a directory on your computer's hard disk.
  • Build plugins are used to insert extra goals into a build phase
  • POM Files: Project Object Model
    • The group ID does not have to be a Java package name, and does not need to use the . notation (dot notation) for separating words in the ID.
      • But, if you do, the project will be located in the Maven repository under a directory structure matching the group ID.
    • The artifact ID is used as name for a subdirectory under the group ID directory in the Maven repository.
    • External Dependencies
      • An external dependency in Maven is a dependency (JAR file) which is not located in a Maven repository (neiterh local, central or remote repository). It may be located somewhere on your local hard disk.

Net

  • InetAddress.getByName
    • Determines the IP address of a host, given the host's name.
    • The host name can either be a machine name, such as "java.sun.com", or a textual representation of its IP address. If a literal IP address is supplied, only the validity of the address format is checked.

Http

java.net.HttpUrlConnection

Threading

Executor

  • 【Java并发编程】之十九:并发新特性—Executor框架与线程池(含代码)
  • 内部使用了线程池机制, 在java.util.cocurrent 包下
  • Executor框架包括:线程池,Executor,Executors,ExecutorService,CompletionService,Future,Callable等。
  • Executor接口中之定义了一个方法execute(Runnable command),该方法接收一个Runable实例,它用来执行一个任务,任务即一个实现了Runnable接口的类。
    • 该Runable实例被创建后,运行它的run()方法
  • ExecutorService的生命周期包括三种状态:运行、关闭、终止。创建后便进入运行状态,当调用了shutdown()方法时,便进入关闭状态,此时意味着ExecutorService不再接受新的任务,但它还在执行已经提交了的任务,当素有已经提交了的任务执行完后,便到达终止状态。如果不调用shutdown()方法,ExecutorService会一直处在运行状态,不断接收新的任务,执行新的任务,服务器端一般不需要关闭它,保持一直运行即可。

ExecutorService的execute和submit方法

Runnable Interface/Thread 继承

  • Java 多线程编程 简介 Runnable接口或者继承Thread

    • 为了启动Runnable Thread,需要首先实例化一个Thread,并传入自己的Runnable Thread实例
    • invoke Thread.start in order to start the new thread
    • 参考JDK源代码可以看到,当传入一个Runnable target参数给Thread后,Thread的run()方法就会调用target.run()

    public void run() {
      if (target != null) {
       target.run();
      }
    }

    • 新线程创建之后,(在它的构造函数中,)你调用它的start()方法它才会运行。
  • 主程序(main所在)的class也可以实现Runnable接口,然后实现run()。当然,创建的线程的run(),是独立于主程序之外执行的一段程序。这跟进程的fork是完全不同的。

ThreadPoolExecutor & Executor Service

  • java中Executor、ExecutorService、ThreadPoolExecutor介绍
    • Executor: execute(Runnable)
    • ExecutorService: submit(Callable), shutdown()/shutdownNow()
      • 由于继承了Executor,所以也有execute(Runnable)
      • ORACLE DOC
      • ExecutorService提供了管理终止的方法,以及可为跟踪一个或多个异步任务执行状况而生成 Future 的方法。
      • 可以关闭 ExecutorService,这将导致其拒绝新任务。
      • 通过创建并返回一个可用于取消执行和/或等待完成的 Future,方法submit扩展了基本方法 Executor.execute(java.lang.Runnable)。
      • 方法 invokeAny 和 invokeAll 是批量执行的最常用形式,它们执行任务 collection,然后等待至少一个,
        或全部任务完成
      • Executors from java.util.concurrent
        • Executors.newFixedThreadPool() will generate a ExecutorService
    • ThreadPoolExecutor: execute(Runnable), submit(Callable), shutdown()/shutdownNow()
      • 实现ExecutorService接口
      • 线程池可以解决两个不同问题:由于减少了每个任务调用的开销,它们通常可以在执行大量异步任务时提供增强的性能,并且还可以提供绑定和管理资源(包括执行任务集时使用的线程)的方法。
      • 使用较为方便的 Executors 工厂方法 Executors.newCachedThreadPool()(无界线程池,可以进行自动线程回收)、Executors.newFixedThreadPool(int)(固定大小线程池)和 Executors.newSingleThreadExecutor()(单个后台线程)
      • 用例参考: 【Java并发编程】之十九:并发新特性—Executor框架与线程池(含代码)

Executor service

  • 参见上面Executor节
  • JAVA多线程实现的三种方式
    • 使用ExecutorService、Callable、Future实现有返回结果的多线程
    • 可返回值的任务必须实现Callable接口,类似的,无返回值的任务必须Runnable接口。执行Callable任务后,可以获取一个Future的对象,在该对象上调用get就可以获取到Callable任务返回的Object了,再结合线程池接口ExecutorService就可以实现传说中有返回结果的多线程了。
    • ExecutoreService提供了submit()方法,传递一个Callable,或Runnable,返回Future。
    • Future对象的get()方法,会阻塞直到计算完成。
    • shutdown(): 当线程池调用该方法时,线程池的状态则立刻变成SHUTDOWN状态。此时,则不能再往线程池中添加任何任务,否则将会抛出RejectedExecutionException异常。但是,此时线程池不会立刻退出,直到添加到线程池中的任务都已经处理完成,才会退出。
  • jenkov: ExecutorService. egs.

ThreadPoolExecutor

  • jenkov: ThreadPoolExecutor
    • ThreadPoolExecutor executes the given task (Callable or Runnable) using one of its internally pooled threads.
  • 用例参考: 线程池实例:使用Executors和ThreadPoolExecutor
  • ORACLE DOC
    • Core and maximum pool sizes
    • Queuing - BlockingQueue
    • Hook methods
  • Creation: ExecutorService threadPoolExecutor = new ThreadPoolExecutor( corePoolSize, maxPoolSize, keepAliveTime, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>() );
    • public ThreadPoolExecutor (int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit,BlockingQueue<Runnable> workQueue)
      • workQueue:任务执行前保存任务的队列,仅保存由execute方法提交的Runnable任务。

几种排队的策略:

  1. 直接提交。缓冲队列采用 SynchronousQueue,它将任务直接交给线程处理而不保持它们。如果不存在可用于立即运行任务的线程(即线程池中的线程都在工作),则试图把任务加入缓冲队列将会失败,因此会构造一个新的线程来处理新添加的任务,并将其加入到线程池中。直接提交通常要求无界 maximumPoolSizes(Integer.MAX_VALUE) 以避免拒绝新提交的任务。newCachedThreadPool采用的便是这种策略。
  2. 无界队列。使用无界队列(典型的便是采用预定义容量的 LinkedBlockingQueue,理论上是该缓冲队列可以对无限多的任务排队)将导致在所有 corePoolSize 线程都工作的情况下将新任务加入到缓冲队列中。这样,创建的线程就不会超过 corePoolSize,也因此,maximumPoolSize 的值也就无效了。当每个任务完全独立于其他任务,即任务执行互不影响时,适合于使用无界队列。newFixedThreadPool采用的便是这种策略。
  3. 有界队列。当使用有限的 maximumPoolSizes 时,有界队列(一般缓冲队列使用ArrayBlockingQueue,并制定队列的最大长度)有助于防止资源耗尽,但是可能较难调整和控制,队列大小和最大池大小需要相互折衷,需要设定合理的参数。

Future & FutureTask

  • Java并发编程:Callable、Future和FutureTask & 示例
    • Runnable: java.lang.Runnable,它是一个接口,在它里面只声明了一个run()方法:
    • Callable位于java.util.concurrent包下,它也是一个接口,在它里面也只声明了一个方法,只不过这个方法叫做call()
    • 在ExecutorService接口中声明了若干个submit方法的重载版本
      • submit(Runnable)
      • submit(Callable)
    • Future就是对于具体的Runnable或者Callable任务的执行结果进行取消、查询是否完成、获取结果。必要时可以通过get方法获取执行结果,该方法会阻塞直到任务返回结果。
    • FutureTask类实现了RunnableFuture接口, RunnableFuture继承了Runnable接口和Future接口,而FutureTask实现了RunnableFuture接口。所以它既可以作为Runnable被线程执行,又可以作为Future得到Callable的返回值。

JRuby's threadpooling

Time

Get Time

  • How to get current timestamp in java
    • Created the object of Date class. (java.util.Date)
    • Got the current timestamp in milliseconds by calling getTime() method of Date.
    • !!! The time would be the time at which the Date() is allocated.
    • Parse it using java.sql.Timestamp
      • new Timestamp(date.getTime())
    • ==> 2010-03-08 14:59:30.252

Delay

Vert.x

Notice:

Concurrency of Vert.x

SQL

Web Server - Tomcat

Java EE

  • Servlet calls for java ee.
  • A simple solution:
    • Download java EE, and in its lib, you will find javaee.jar
    • in eclipse, you can add this jar to the project
    • or when you compile, go with javac src/com/mkyong/ServletDemo1.java -classpath "C:\Program Files\Java\j2ee\lib\javaee.jar" -d classes

Servlet

Deployment: - Tomcat

  • In accordance with 'webapps/Root'
  • For Root app, you can simply put your servlet or jsp in Root
  • For Servlet not in 'webapps/Root', you access thru "http://xxx/YourServletFolderName/whatursettingsareinwebxml"
  • /webapps/ServletProjectName(AppName):
    • /WEB-INF
      • /web.xml
      • /classes
        • package directory as in your project
        • com
          • vr
            • HelloServlet.class
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,425评论 4 361
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,058评论 1 291
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,186评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,848评论 0 204
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,249评论 3 286
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,554评论 1 216
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,830评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,536评论 0 197
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,239评论 1 241
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,505评论 2 244
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,004评论 1 258
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,346评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 32,999评论 3 235
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,060评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,821评论 0 194
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,574评论 2 271
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,480评论 2 267

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,099评论 18 139
  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 8,569评论 0 23
  • 图文/刘小牙 当十年都唱了十几年的时候,当感动都烂大街的时候。 以前总觉得十年漫长,持久,且特别。而渐渐不知是故事...
    少女哪吒刘懒懒阅读 243评论 0 1
  • 之前把Apple Pay的文档全部翻译了一遍,最近也是接触到了真实的项目开发。发现开发的过程还是和官方文档中的介绍...
    李周阅读 4,731评论 2 5
  • 可能是因为今天评论了一条微博,有点想法想表达出来。微博说的是乐视董事长把苹果公司比成希特勒。说有了开放的系统...
    小白和小黑阅读 249评论 0 2