1.java基础
finally中对try或catch语句块的值修改,返回值是什么?
1.返回值不是finally中的值,而是原有的try或catch中未被改写的值,见如下代码:
@Test
public void testTryReturn() {
System.out.println(getInt());
}
public int getInt() {
int a;
try {
a = 10; // 1.赋值为10
return a; // 2.将返回值设置为10 4.返回10
} catch (Exception e) {
} finally {
a = 20; // 3.赋值为20
}
return a;
}
jdk1.8、jdk1.9的新特性
如何获取类的私有方法和私有属性
Class<Person> personClass = Person.class;
// 初始化对象
Person person = personClass.newInstance();
// 公共方法获取
Method m1 = personClass.getMethod("setAge",int.class);
// 通过setAge赋值
m1.invoke(person,3);
System.out.println(person);
// 私有方法获取
Method m2 = personClass.getDeclaredMethod("test");
m2.setAccessible(true);
m2.invoke(person);
// 私有成员变量获取
Field field = personClass.getDeclaredField("age");
field.setAccessible(true);
field.set(person,5);
System.out.println(person);
volatile关键字
1.保证此变量对所有的线程的可见性,这里的“可见性”,如本文开头所述,当一个线程修改了这个变量的值,volatile 保证了新值能立即同步到主内存,以及每次使用前立即从主内存刷新。但普通变量做不到这点,普通变量的值在线程间传递均需要通过主内存(详见:Java内存模型)来完成。
2.禁止指令重排序优化。有volatile修饰的变量,赋值后多执行了一个“load addl $0x0, (%esp)”操作,这个操作相当于一个内存屏障(指令重排序时不能把后面的指令重排序到内存屏障之前的位置),只有一个CPU访问内存时,并不需要内存屏障;(什么是指令重排序:是指CPU采用了允许将多条指令不按程序规定的顺序分开发送给各相应电路单元处理)。
3.但不能保证原子性,如a++;或a=a+1;其实要分成3步:1)读取volatile变量值到local; 2)增加变量的值;3)把local的值写回,让其它的线程可见。内存屏障设在最后,所以中间的操作并不能保证值是最新的,导致无法满足原子性问题
2.多线程
线程的几种状态
线程的状态分为:
1. 新建
2. 就绪
3. 运行
4. 阻塞
5. 消亡
sleep和wait的区别
sleep()方法和yield()方法都是Thread类的静态方法,都会使当前处于运行状态的线程放弃cpu,把运行机会
让给别的线程。两者的区别在于:
1. sleep()方法会给其他线程运行的机会,而不考虑其他线程的优先级,因此会给较低优先级的一个运行的机会;
2. yield()方法只会给相同优先级或者更高优先级的线程一个运行的机会
线程同步的方法和区别
线程锁有几种,可重入锁和Synchronized的区别
###同步方法
即有synchronized关键字修饰的方法。
由于java的每个对象都有一个内置锁,当用此关键字修饰方法时,
内置锁会保护整个方法。在调用该方法前,需要获得内置锁,否则就处于阻塞状态。
代码如:
public synchronized void save(){}
注: synchronized关键字也可以修饰静态方法,此时如果调用该静态方法,将会锁住整个类
###同步代码块
即有synchronized关键字修饰的语句块。
被该关键字修饰的语句块会自动被加上内置锁,从而实现同步
代码如:
synchronized(object){
}
注:同步是一种高开销的操作,因此应该尽量减少同步的内容。
通常没有必要同步整个方法,使用synchronized代码块同步关键代码即可。
###使用特殊域变量(volatile)实现线程同步
a.volatile关键字为域变量的访问提供了一种免锁机制,
b.使用volatile修饰域相当于告诉虚拟机该域可能会被其他线程更新,
c.因此每次使用该域就要重新计算,而不是使用寄存器中的值
d.volatile不会提供任何原子操作,它也不能用来修饰final类型的变量
###使用重入锁实现线程同步
在JavaSE5.0中新增了一个java.util.concurrent包来支持同步。
ReentrantLock类是可重入、互斥、实现了Lock接口的锁,
它与使用synchronized方法和快具有相同的基本行为和语义,并且扩展了其能力
ReenreantLock类的常用方法有:
ReentrantLock() : 创建一个ReentrantLock实例
lock() : 获得锁
unlock() : 释放锁
注:关于Lock对象和synchronized关键字的选择:
a.最好两个都不用,使用一种java.util.concurrent包提供的机制,
能够帮助用户处理所有与锁相关的代码。
b.如果synchronized关键字能满足用户的需求,就用synchronized,因为它能简化代码
c.如果需要更高级的功能,就用ReentrantLock类,此时要注意及时释放锁,否则会出现死锁,通常在 finally代码释放锁
###使用局部变量实现线程同步
如果使用ThreadLocal管理变量,则每一个使用该变量的线程都获得该变量的副本,
副本之间相互独立,这样每一个线程都可以随意修改自己的变量副本,而不会对其他线程产生影响。
ThreadLocal 类的常用方法
ThreadLocal() : 创建一个线程本地变量
get() : 返回此线程局部变量的当前线程副本中的值
initialValue() : 返回此线程局部变量的当前线程的"初始值"
set(T value) : 将此线程局部变量的当前线程副本中的值设置为value
注:ThreadLocal与同步机制
a.ThreadLocal与同步机制都是为了解决多线程中相同变量的访问冲突问题。
b.前者采用以”空间换时间”的方法,后者采用以”时间换空间”的方式
java并发包
ConcurrentHashMap
ConcurrentHashMap 和 java.util.HashTable 类很相似,但 ConcurrentHashMap 能够提供比 HashTable 更好的并发性能。在你从中读取对象的时候 ConcurrentHashMap 并不会把整个 Map 锁住。
此外,在你向其中写入对象的时候,ConcurrentHashMap 也不会锁住整个 Map。它的内部只是把 Map 中正在被写入的部分进行锁定。
ConcurrentLinkedQueue
ConcurrentLinkedQueue是Queue的一个安全实现.Queue中元素按FIFO原则进行排序.采用CAS操作,来保证元素的一致性。
LinkedBlockingQueue是一个线程安全的阻塞队列,它实现了BlockingQueue接口,BlockingQueue接口继承自java.util.Queue接口,并在这个接口的基础上增加了take和put方法,这两个方法正是队列操作的阻塞版本。
public class BlockingQueueTest {
public static void main(String[] args) {
BlockingQueue blockingQueue =new ArrayBlockingQueue(1000);
new Thread(new BlockingQueueTest().new Consumer(blockingQueue)).start();
new Thread(new BlockingQueueTest().new Producer(blockingQueue)).start();
}
class Consumer implements Runnable {
private BlockingQueue<String> blockingQueue;
public Consumer(BlockingQueue<String> blockingQueue) {
this.blockingQueue = blockingQueue;
}
@Override
public void run() {
try {
String take = blockingQueue.take();
System.out.println(take);
String take2 = blockingQueue.take();
System.out.println(take2);
String take4 = blockingQueue.take();
System.out.println(take4);
String take3 = blockingQueue.poll(10, TimeUnit.SECONDS);
System.out.println(take3);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
class Producer implements Runnable{
private BlockingQueue<String> blockingQueue;
public Producer(BlockingQueue blockingQueue) {
this.blockingQueue = blockingQueue;
}
@Override
public void run() {
try {
this.blockingQueue.put("1111");
Thread.sleep(1000);
this.blockingQueue.put("2222");
Thread.sleep(1000);
this.blockingQueue.put("3333");
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
CountDownLatch
CountDownLatch 以一个给定的数量初始化。countDown() 每被调用一次,这一数量就减一。通过调用 await() 方法之一,线程可以阻塞等待这一数量到达零。以下是一个简单示例。
Decrementer 三次调用 countDown() 之后,等待中的 Waiter 才会从 await() 调用中释放出来。
public class CountDownLatchTest {
public static void main(String[] args) {
CountDownLatch countDownLatch = new CountDownLatch(3);
new Thread(new CountDownLatchTest().new General(countDownLatch)).start();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
new Thread(new CountDownLatchTest().new Soldier(countDownLatch),"3号").start();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
new Thread(new CountDownLatchTest().new Soldier(countDownLatch),"1号").start();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
new Thread(new CountDownLatchTest().new Soldier(countDownLatch),"2号").start();
}
class General implements Runnable {
private CountDownLatch countDownLatch;
public General(CountDownLatch countDownLatch) {
this.countDownLatch = countDownLatch;
}
@Override
public void run() {
try {
countDownLatch.await();
System.out.println("将领发布命令!!!");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
class Soldier implements Runnable{
private CountDownLatch countDownLatch;
public Soldier(CountDownLatch countDownLatch) {
this.countDownLatch = countDownLatch;
}
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+"士兵准备完毕。 count:"+countDownLatch.getCount());
countDownLatch.countDown();
}
}
}
CyclicBarrier
java.util.concurrent.CyclicBarrier 类是一种同步机制,它能够对处理一些算法的线程实现同步。换句话讲,它就是一个所有线程必须等待的一个栅栏,直到所有线程都到达这里,然后所有线程才可以继续做其他事情。
public class TestCyclicBarrier {
public static void main(String[] args) {
Runnable surfInternet = new Runnable() {
@Override
public void run() {
System.out.println("满足条件,可以上网了!!!");
}
};
Runnable codding = new Runnable() {
@Override
public void run() {
System.out.println("满足条件,可以编程了!!!");
}
};
CyclicBarrier surfInternetCyclicBarrier = new CyclicBarrier(2, surfInternet);
CyclicBarrier coddingCyclicBarrier = new CyclicBarrier(2, codding);
// CyclicBarrier surfInternetCyclicBarrier = new CyclicBarrier(2);
// CyclicBarrier coddingCyclicBarrier = new CyclicBarrier(2);
new Thread(new TestCyclicBarrier.SuerfInternetCondition(surfInternetCyclicBarrier, coddingCyclicBarrier)).start();
new Thread(new TestCyclicBarrier.coddingCyclicCondition(surfInternetCyclicBarrier, coddingCyclicBarrier)).start();
}
static class SuerfInternetCondition implements Runnable {
private CyclicBarrier surfInternetCyclicBarrier;
private CyclicBarrier coddingCyclicBarrier;
public SuerfInternetCondition(CyclicBarrier surfInternetCyclicBarrier, CyclicBarrier coddingCyclicBarrier) {
this.surfInternetCyclicBarrier = surfInternetCyclicBarrier;
this.coddingCyclicBarrier = coddingCyclicBarrier;
}
@Override
public void run() {
try {
Thread.sleep(2000);
System.out.println("买了电脑");
surfInternetCyclicBarrier.await();
Thread.sleep(2000);
coddingCyclicBarrier.await();
System.out.println("学了编程");
} catch (Exception e) {
e.printStackTrace();
}
}
}
static class coddingCyclicCondition implements Runnable {
private CyclicBarrier surfInternetCyclicBarrier;
private CyclicBarrier coddingCyclicBarrier;
public coddingCyclicCondition(CyclicBarrier surfInternetCyclicBarrier, CyclicBarrier coddingCyclicBarrier) {
this.surfInternetCyclicBarrier = surfInternetCyclicBarrier;
this.coddingCyclicBarrier = coddingCyclicBarrier;
}
@Override
public void run() {
try {
surfInternetCyclicBarrier.await();
System.out.println("连了网线");
coddingCyclicBarrier.await();
System.out.println("装了IDE");
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
Semaphore
java.util.concurrent.Semaphore 类是一个计数信号量。这就意味着它具备两个主要方法:
acquire()
release()
计数信号量由一个指定数量的 “许可” 初始化。每调用一次 acquire(),一个许可会被调用线程取走。每调用一次 release(),一个许可会被返还给信号量。因此,在没有任何 release() 调用时,最多有 N 个线程能够通过 acquire() 方法,N 是该信号量初始化时的许可的指定数量。这些许可只是一个简单的计数器。这里没啥奇特的地方。
public class TestSemaphore {
public static void main(String[] args) {
// 公平
Semaphore semaphore = new Semaphore(3,true);
new Thread(new TestSemaphore().new SemaphoreRunable(semaphore),"1").start();
new Thread(new TestSemaphore().new SemaphoreRunable(semaphore),"2").start();
new Thread(new TestSemaphore().new SemaphoreRunable(semaphore),"3").start();
new Thread(new TestSemaphore().new SemaphoreRunable(semaphore),"4").start();
new Thread(new TestSemaphore().new SemaphoreRunable(semaphore),"5").start();
new Thread(new TestSemaphore().new SemaphoreRunable(semaphore),"6").start();
new Thread(new TestSemaphore().new SemaphoreRunable(semaphore),"7").start();
new Thread(new TestSemaphore().new SemaphoreRunable(semaphore),"8").start();
}
class SemaphoreRunable implements Runnable{
private Semaphore semaphore;
public SemaphoreRunable(Semaphore semaphore) {
this.semaphore = semaphore;
}
@Override
public void run() {
try {
semaphore.acquire();
Thread.sleep(2000);
System.out.println(Thread.currentThread().getName()+" 通过了");
semaphore.release();
semaphore.acquire();
Thread.sleep(2000);
System.out.println(Thread.currentThread().getName()+" 返回了");
semaphore.release();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
Exchange
java.util.concurrent.Exchanger 类表示一种两个线程可以进行互相交换对象的会和点。这种机制图示如下:
public class TestExchanger {
public static void main(String[] args) throws InterruptedException {
Exchanger exchanger = new Exchanger();
new Thread(new TestExchanger().new ExchangerRunable("A",exchanger),"A").start();
Thread.sleep(5000);
new Thread(new TestExchanger().new ExchangerRunable("B",exchanger),"B").start();
}
class ExchangerRunable implements Runnable {
private String exchangerObj;
private Exchanger exchanger;
public ExchangerRunable(String exchangerObj, Exchanger exchanger) {
this.exchangerObj = exchangerObj;
this.exchanger = exchanger;
}
@Override
public void run() {
String previous = exchangerObj;
try {
exchangerObj = (String) exchanger.exchange(exchangerObj);
System.out.println(Thread.currentThread().getName() + " previous:" + previous + " exchange end: " + exchangerObj);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
CountDownLatch 控制多线程执行完前,父线程阻塞
CyclicBarrier 控制多线程在某点同步
Semaphore 控制同时执行线程数
Exchanger 两个线程在某点交换数据
NIO底层实现
线程池的相关内容(参数)
任务提交的大概逻辑如下:
1)当线程池小于corePoolSize时,新提交任务将创建一个新线程执行任务,即使此时线程池中存在空闲线程;
2)当线程池达到corePoolSize时,新提交任务将被放入workQueue中,等待线程池中任务调度执行;
3)当workQueue已满,且maximumPoolSize > corePoolSize时,新提交任务会创建新线程执行任务;
4)当提交任务数超过maximumPoolSize时,新提交任务由RejectedExecutionHandler处理;
5)当线程池中超过corePoolSize线程,空闲时间达到keepAliveTime时,关闭空闲线程;
3.数据库和事务
乐观锁和悲观锁及间隙锁
一、悲观锁
- 排它锁,当事务在操作数据时把这部分数据进行锁定,直到操作完毕后再解锁,其他事务操作才可操作该部分数据。这将防止其他进程读取或修改表中的数据。
- 实现:大多数情况下依靠数据库的锁机制实现
- 一般使用 select …for update 对所选择的数据进行加锁处理,例如select * from account where name=”Max” for update, 这条sql 语句锁定了account 表中所有符合检索条件(name=”Max”)的记录。本次事务提交之前(事务提交时会释放事务过程中的锁),外界无法修改这些记录。
二、乐观锁
- 如果有人在你之前更新了,你的更新应当是被拒绝的,可以让用户重新操作。
- 实现:大多数基于数据版本(Version)记录机制实现
- 具体可通过给表加一个版本号或时间戳字段实现,当读取数据时,将version字段的值一同读出,数据每更新一次,对此version值加一。当我们提交更新的时候,判断当前版本信息与第一次取出来的版本值大小,如果数据库表当前版本号与第一次取出来的version值相等,则予以更新,否则认为是过期数据,拒绝更新,让用户重新操作。
事务的隔离问题和隔离级别
- 如果不考虑事务要被隔离起来,会导致以下问题
- 脏读:指一个事务读到了另外一个事务中未提交的数据
- 不可重复读:指一个事务读到了另外一个事务中已经提交的数据(update)
- 虚读:指一个事务读到了另外一个事务insert的数据
- 数据库有4种隔离级别:
- READ UNCOMMITTED:脏读、不可重复读、虚读都有可能发生
- READ COMMITTED:防止脏读。不可重复读、虚读都有可能发生
- REPEATABLE READ:防止脏读、不可能重复读。虚读有可能发生
- SERIALIZABLE:防止脏读、不可重复读、虚读的发生
嵌套事务的回滚机制
PROPAGATION_NESTED
外层事务失败时,会回滚内层事务所做的动作。而内层事务操作失败并不会引起外层事务的回滚。
事务的传播类型
事务传播类型 | 当前有事务 | 当前无事务 |
---|---|---|
PROPAGATION_REQUIRED | 用当前 | 创建新的 |
PROPAGATION_SUPPORTS | 用当前 | 不用事务 |
PROPAGATION_MANDATORY | 用当前 | 抛异常 |
PROPAGATION_REQUIRES_NEW | 挂起事务,创建新事务 | 创建新事物 |
PROPAGATION_NOT_SUPPORTED | 挂起事务 | 不创建 |
PROPAGATION_NEVER | 抛异常 | 不创建 |
PROPAGATION_NESTED | 嵌套事务 | 新建 |
PROPAGATION_NESTED
外层事务失败时,会回滚内层事务所做的动作。而内层事务操作失败并不会引起外层事务的回滚。
索引的使用规则,多个索引存在的情况;explain的作用
explain列的解释
-
table:显示这一行的数据是关于哪张表的
-
type:这是重要的列,显示连接使用了何种类型。从最好到最差的连接类型为const、eq_reg、ref、range、indexhe和all
-
possible_keys:显示可能应用在这张表中的索引。如果为空,没有可能的索引。可以为相关的域从where语句中选择一个合适的语句
-
key: 实际使用的索引。如果为null,则没有使用索引。很少的情况下,mysql会选择优化不足的索引。这种情况下,可以在select语句中使用use index(indexname)来强制使用一个索引或者用ignore index(indexname)来强制mysql忽略索引
-
key_len:使用的索引的长度。在不损失精确性的情况下,长度越短越好
-
ref:显示索引的哪一列被使用了,如果可能的话,是一个常数
-
rows:mysql认为必须检查的用来返回请求数据的行数
-
extra:关于mysql如何解析查询的额外信息。将在表4.3中讨论,但这里可以看到的坏的例子是using temporary和using filesort,意思mysql根本不能使用索引,结果是检索会很慢