synchronized

Java并发之Condition与Lock

萝らか妹 提交于 2019-12-03 15:58:18
java.util.concurrent.locks包为锁和等待条件提供一个框架的接口和类,它不同于内置同步和监视器。该框架允许更灵活地使用锁和条件,但以更难用的语法为代价。 Lock 接口支持那些语义不同(重入、公平等)的锁规则,可以在非阻塞式结构的上下文(包括 hand-over-hand 和锁重排算法)中使用这些规则。主要的实现是 ReentrantLock。 ReadWriteLock 接口以类似方式定义了一些读取者可以共享而写入者独占的锁。此包只提供了一个实现,即 ReentrantReadWriteLock,因为它适用于大部分的标准用法上下文。但程序员可以创建自己的、适用于非标准要求的实现。 Condition 接口描述了可能会与锁有关联的条件变量。这些变量在用法上与使用 Object.wait 访问的隐式监视器类似,但提供了更强大的功能。需要特别指出的是,单个 Lock 可能与多个 Condition 对象关联。为了避免兼容性问题,Condition 方法的名称与对应的 Object 版本中的不同。 以下是locks包的相关类图: 在之前我们同步一段代码或者对象时都是使用 synchronized关键字,使用的是Java语言的内置特性,然而 synchronized的特性也导致了很多场景下出现问题,比如: 在一段同步资源上,首先线程A获得了该资源的锁,并开始执行

Java Memory Model: reordering and concurrent locks

本小妞迷上赌 提交于 2019-12-03 14:06:07
The java meomry model mandates that synchronize blocks that synchronize on the same monitor enforce a before-after-realtion on the variables modified within those blocks. Example: // in thread A synchronized( lock ) { x = true; } // in thread B synchronized( lock ) { System.out.println( x ); } In this case it is garanteed that thread B will see x==true as long as thread A already passed that synchronized -block. Now I am in the process to rewrite lots of code to use the more flexible (and said to be faster) locks in java.util.concurrent , especially the ReentrantReadWriteLock . So the example

Java 实现线程安全的三种方式

穿精又带淫゛_ 提交于 2019-12-03 13:37:25
一个程序在运行起来的时候会转换成进程,通常含有多个线程。   通常情况下,一个进程中的比较耗时的操作(如长循环、文件上传下载、网络资源获取等),往往会采用多线程来解决。 比如显示生活中,银行取钱问题、火车票多个售票窗口的问题,通常会涉及到并发的问题,从而需要多线程的技术。   当进程中有多个并发线程进入一个重要数据的代码块时,在修改数据的过程中,很有可能引发线程安全问题,从而造成数据异常。例如,正常逻辑下,同一个编号的火车票只能售出一次,却由于线程安全问题而被多次售出,从而引起实际业务异常。 现在我们就以售票问题来演示线程安全的问题 1, 在不对多线程数据进行保护的情况下会引发的状况 public class ThreadUnSecurity { static int tickets = 10; class SellTickets implements Runnable{ @Override public void run() { // 未加同步时产生脏数据 while(tickets > 0) { System.out.println(Thread.currentThread().getName()+"--->售出第: "+tickets+" 票"); tickets--; try { Thread.sleep(1000); } catch

Java threads and synchronized blocks

筅森魡賤 提交于 2019-12-03 13:22:45
Suppose I'm executing a synchronized block of code inside some thread and within the synchronized block I call a method that spawns another thread to process a synchronized block of code that requires the same lock as the first method. So in pseudo Java code: public void someMethod() { synchronized(lock_obj) { // a whole bunch of stuff... // this is the last statement in the block (new Thread(someOtherMethod())).start(); } // some more code that doesn't require a lock } public void someOtherMethod() { // some setup code that doesn't require a lock // return the stuff we want to run in another

Which is the difference between AtomicReference and Synchronized?

痴心易碎 提交于 2019-12-03 12:09:24
Is there any difference between AtomicReference and Synchronized? E.G. public class Internet { AtomicReference<String> address; public String getAddress(){ return address.toString(); } public void setAddress(String address) { this.address.set(address); } } And I pass the class to some threads that try to use the class at the same time, is it the same thing if I use this: public class Internet { String address; public String getAddress(){ return address; } public void setAddress(String address) { this.address = address; } } And then in the thread use synchronized before access to the class?

jdk提供的线程协调API suspend/resume wait/notify park/unpark

做~自己de王妃 提交于 2019-12-03 11:57:54
线程通信(如 线程执行先后顺序,获取某个线程执行的结果等)有多种方式: 文件共享 线程1 --写入--> 文件 < --读取-- 线程2 网络共享 变量共享 线程1 --写入--> 主内存共享变量 < --读取-- 线程2 jdk提供的线程协调API suspend/resume wait/notify park/unpark。 线程协作 - JDK API 线程协作的典型场景:生产者-消费者 模型(线程阻塞、线程唤醒) 如:线程1去卖包子,没有包子,则不再执行,线程2生产包子,通知线程1继续执行 API - 被弃用 suspend/resume suspend挂起目标线程,resume恢复线程执行。 如下正常情况: 1 import java.util.concurrent.locks.LockSupport; 2 3 public class ThreadInteration { 4 public static Object baozidian =null; 5 public static void main(String[] args) throws InterruptedException { 6 new ThreadInteration().suspendResumeTest(); 7 } 8 /** 9 * 使用弃用的API suspend和resume

线程的相关技术总结

荒凉一梦 提交于 2019-12-03 10:46:43
--CountDownKatch CountDownLatch 内部维护了一个整数 n ,n(要大于等于0)在 当前线程 初始化 CountDownLatch 方法指定。当前线程调用 CountDownLatch 的 await() 方法阻塞当前线程,等待其他调用 CountDownLatch 对象的 CountDown() 方法的线程执行完毕。 其他线程调用该 CountDownLatch 的 CountDown() 方法,该方法会把 n-1 ,直到所有线程执行完成, n 等于 0 ,当前线程 就恢复执行 --CyclicBarrier CyclicBarrier 是一个同步辅助类,允许一组线程互相等待,直到到达某个公共屏障点(CommonBarrierPoint)。因为该 barrier 在释放等待线程后可以重用,所以称它为循环的 barrier 。 -- Semaphore Semaphore 直译为信号。实际上 Semaphore 可以看做是一个信号的集合。不同的线程能够从 Semaphore 中获取若干个信号量。当 Semaphore 对象持有的信号量不足时,尝试从 Semaphore 中获取信号的线程将会阻塞。直到其他线程将信号量释放以后,阻塞的线程会被唤醒,重新尝试获取信号量。 --说说 CountDownLatch 与 CyclicBarrier 区别

java.io.FileNotFoundException: The process cannot access the file because it is being used by another process)

匿名 (未验证) 提交于 2019-12-03 10:24:21
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试): 问题: I written a listener which listen to queue continuously, as message arrive it should write that message to file. @Override public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { String response = new String(body); String routingKey = envelope.getRoutingKey(); String contentType = properties.getContentType(); String correlationId = properties.getCorrelationId(); System.out.println("response "+ counter+ " :: "+ response); try { ResponseWriter.responseWrite(response,

Limiting concurrent access to a method

匿名 (未验证) 提交于 2019-12-03 10:09:14
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试): 问题: I have a problem with limiting concurrent access to a method. I have a method MyService that can be called from many places at many times. This method must return a String , that should be updated according to some rules. For this, I have an updatedString class. Before getting the String , it makes sure that the String is updated, if not, it updates it. Many threads could read the String at the same time but ONLY ONE should renew the String at the same time if it is out of date. public final class updatedString { private static final String

synchronized 与 lock 的区别

狂风中的少年 提交于 2019-12-03 09:59:58
synchronized 和 lock 的用法区别 synchronized(隐式锁):在需要同步的对象中加入此控制, synchronized 可以加在方法上,也可以加在特定代码块中,括号中表示需要锁的对象。 lock(显示锁):需要显示指定起始位置和终止位置。一般使用 ReentrantLock 类做为锁,多个线程中必须要使用一个 ReentrantLock 类做为对象才能保证锁的生效。且在加锁和解锁处需要通过 lock() 和 unlock() 显示指出。所以一般会在 finally 块中写 unlock() 以防死锁。 synchronized 和 lock 性能区别 synchronized 是托管给 JVM 执行的,而 lock 是 Java 写的控制锁的代码。在 JDK 1.5 中, synchronize 是性能低效的。因为这是一个重量级操作,需要调用操作接口,导致有可能加锁消耗的系统时间比加锁以外的操作还多。相比之下使用 Java 提供的 Lock 对象,性能更高一些。但是到了 JDK 1.6,发生了变化。 synchronize 在语义上很清晰,可以进行很多优化,有适应自旋,锁消除,锁粗化,轻量级锁,偏向锁等等。导致在 JDK 1.6 上 synchronize 的性能并不比 Lock 差。 synchronized 和 lock 机制区别