Java review-basic4
1. HashMap vs HashTable vs ConcurrentHashMap
1). Thread -Safe : ConcurrentHashMap is thread-safe that is the code can be accessed by single thread at a time. while HashMap is not thread-safe.
2). Synchronization Method: HashMap can be synchronized by using synchronizedMap(HashMap) method. By using this method we get a HashMap object which is equivalent to the HashTable object. So every modification is performed on Map is locked on Map object. 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.
3). Null Key: ConcurrentHashMap does not allow NULL values . So the key can not be null in ConcurrentHashMap While In HashMap there can only be one null key .
4). Performance: In multiple threaded environment HashMap is usually faster than ConcurrentHashMap. As only single thread can access the certain portion of the Map and thus reducing the performance. While in HashMap any number of threads can access the code at the same time. Please write in comments in case if you have any doubts.
个人理解:这一题主要是问HashMap,HashTable还有ConcurrentHashMap的区别在以下几点:
1. 线程安全,HashTable和ConcurrentHashMap是线程安全的,同时只能有一个线程访问。
2. 可以加入synchronize方法来保证HashMap的线程安全,concurrentHashMap可以根据不同的级别来分为不同的partitions,不需要同时访问,可以提高效率
3. ConcurrentHashMap not allow any null in it, hashmap only for null as key.
4. HashMap faster in multiple enviroment because it can acess many threads at same time.
2.Synchronous vs asynchronous
Synchronized means "connected", or "dependent" in some way. In other words two synchronous tasks must be aware of one another, and one must execute in some way that is dependent on the other. In most cases that means that one cannot start until the other has completed. Asynchronous means they are totally independent and neither one must consider the other in any way, either in initiation or in execution.
As an aside, I should mention that technically, the concept of synchronous vs. asynchronous really does not have anything to do with threads. Although, in general, it would be unusual to find asynchronous tasks running on the same thread, it is possible, (see below for e.g.) and it is common to find two or more tasks executing synchronously on separate threads... No, the concept of synchronous/asynchronous has to do solely with whether or not a second or subsequent task can be initiated before the other task has completed, or whether it must wait. That is all. What thread (or threads), or processes, or CPUs, or indeed, what hardware, the task[s] are executed on is not relevant. Indeed, to make this point I have edited the graphics to show this
个人理解:关于多线程,单线程中的同步异步,上面图解释的很清楚:
同步意味着线程之间相互有影响,一个结束了才能去执行另外一个,而异步是相对独立的,自己执行自己的,相互之间不影响。
3.thread contention:
Essentially thread contention is a condition where one thread is waiting for a lock/object that is currently being held by another thread. Therefore, this waiting thread cannot use that object until the other thread has unlocked that particular object.
一个线程等待一个被另外线程锁住的资源
4. race conditions/debug them
A race condition occurs when two or more threads can access shared data and they try to change it at the same time. Because the thread scheduling algorithm can swap between threads at any time, you don't know the order in which the threads will attempt to access the shared data. Therefore, the result of the change in data is dependent on the thread scheduling algorithm, i.e. both threads are "racing" to access/change the data. In order to prevent race conditions from occurring, you would typically put a lock around the shared data to ensure only one thread can access the data at a time.
race conidtions:
两个线程同时申请一个资源,并且同时试图改变,解决方法是在shared resource上面加锁。
5. deadlocks
A deadlock is when two or more threads are blocked waiting to obtain locks that some of the other threads in the deadlock are holding. Deadlock can occur when multiple threads need the same locks, at the same time, but obtain them in different order. For instance, if thread 1 locks A, and tries to lock B, and thread 2 has already locked B, and tries to lock A, a deadlock arises. Thread 1 can never get B, and thread 2 can never get A. In addition, neither of them will ever know. They will remain blocked on each their object, A and B, forever. This situation is a deadlock.
个人理解:死锁是很常见的问题,当两个或者更多的线程为了获得同一个已经被占有的资源,然而资源被另外一个线程hold住了,然而这个资源也想要或者被先前的两个资源hold住的资源,就会发生死锁。
6. how to prevent deadlocks
1)Lock Ordering
Deadlock occurs when multiple threads need the same locks but obtain them in different order.
2)Lock Timeout
Another deadlock prevention mechanism is to put a timeout on lock attempts meaning a thread trying to obtain a lock will only try for so long before giving up. If a thread does not succeed in taking all necessary locks within the given timeout, it will backup, free all locks taken, wait for a random amount of time and then retry. The random amount of time waited serves to give other threads trying to take the same locks a chance to take all locks, and thus let the application continue running without locking.
3)Deadlock Detection
A better option is to determine or assign a priority of the threads so that only one (or a few) thread backs up. The rest of the threads continue taking the locks they need as if no deadlock had occurred. If the priority assigned to the threads is fixed, the same threads will always be given higher priority. To avoid this you may assign the priority randomly whenever a deadlock is detected.
个人理解:解决死锁的办法如下,1.设置锁的顺序,就是设置优先级
2. 设置timeOut 到时间直接释放
7. Thread confinement
Thread confinement is the practice of ensuring that data is only accessible from one thread. Such data is called thread-local as it is local, or specific, to a single thread. Thread-local data is thread-safe, as only one thread can get at the data, which eliminates the risk of races. And because races are nonexistent, thread-local data doesn't need locking. Thus thread confinement is a practice that makes your code safer (by eliminating a huge source of programming error) and more scalable (by eliminating locking). Most languages don't have mechanisms to enforce thread confinement; it is a higher-level programming pattern and not a language or OS feature. Functionality such as thread local storage (TLS) makes thread confinement easier, but the programmer must still work to ensure references to the data does not escape the owning thread.
个人理解:Thread confinement which is data only occupied by local thread, no race conidtion and thread safe, so it doesn't need to lock.
8. cache coherence
When multiple processors with separate caches share a common memory, it is necessary to keep the caches in a state of coherence by ensuring that any shared operand that is changed in any cache is changed throughout the entire system.
This is done in either of two ways: through a directory-based or a snooping system.
In a directory-based system, the data being shared is placed in a common directory that maintains the coherence between caches. The directory acts as a filter through which the processor must ask permission to load an entry from the primary memory to its cache. When an entry is changed the directory either updates or invalidates the other caches with that entry.
In a snooping system, all caches on the bus monitor (or snoop) the bus to determine if they have a copy of the block of data that is requested on the bus. Every cache has a copy of the sharing status of every block of physical memory it has. Cache misses and memory traffic due to shared data blocks limit the performance of parallel computing in multiprocessor computers or systems. Cache coherence aims to solve the problems associated with sharing data
个人理解:
cache coherence意思是在同一内存中有不同的缓存,一个缓存改变了,整个系统的其他部分也需要一起进行改变。
期中有两种方式:
1.在一个目录权限下的一个缓存进行了修改,其他的同样也会进行修改。
2. 另外一种是snooping,其意义为在总线上一个发生了改变,另外相同状态的也会进行改变。
9.False Sharing:
Memory is stored within the cache system in units know as cache lines. Cache lines are a power of 2 of contiguous bytes which are typically 32-256 in size. The most common cache line size is 64 bytes. False sharing is a term which applies when threads unwittingly impact the performance of each other while modifying independent variables sharing the same cache line. Write contention on cache lines is the single most limiting factor on achieving scalability for parallel threads of execution in an SMP system. I’ve heard false sharing described as the silent performance killer because it is far from obvious when looking at code.
To achieve linear scalability with number of threads, we must ensure no two threads write to the same variable or cache line. Two threads writing to the same variable can be tracked down at a code level. To be able to know if independent variables share the same cache line we need to know the memory layout, or we can get a tool to tell us. Intel VTune is such a profiling tool. In this article I’ll explain how memory is laid out for Java objects and how we can pad out our cache lines to avoid false sharing.
在多处理器,多线程情况下,如果两个线程分别运行在不同的CPU上,而其中某个线程修改了cache line中的元素,由于cache一致性的原因,另一个线程的cache line被宣告无效,在下一次访问时会出现一次cache line miss,哪怕该线程根本无效改动的这个元素,因此出现了False Sharing问题
Java review-basic4的更多相关文章
- Java Review (一、Java开发环境)
@ 目录 Java程序运行机制 高级语言运行机制 编译型语言 解释型语言 Java运行机制和JVM 编写 编译 运行 Java开发工具包 JDK JRE JDK.JRE与JVM HelloWord 编 ...
- java:Review(Oracle-HTML-CSS)
20170708_review: 1.oracle: 对表的操作: 使用命令行建立一张表:create table 表名 (列名 列名的类型 primarty key, ....); alter ta ...
- [Java 教程 01] Hello,Java!
前言 从事编程已经有一段时间了,突然发现,Java作为我的第一编程语言,自己似乎对她并有一个系统的思想.当下Java依旧保持着超高的热度,新特性也不断出现,从当初学习的java6版本到最近刚出的jav ...
- Java Algorithm Problems
Java Algorithm Problems 程序员的一天 从开始这个Github已经有将近两年时间, 很高兴这个repo可以帮到有需要的人. 我一直认为, 知识本身是无价的, 因此每逢闲暇, 我就 ...
- [Java 教程 00] 计算机基础
前言 我想,来到这的朋友肯定是想学习JAVA或者想要进入IT这个行业的.考虑到大家的基础可能不一样,有些人可能还是用着新买的电脑,为了让大家在后续的学习中更加顺畅.在学习一门全新的计算机语言之前,我需 ...
- [Java 教程 04] Java基础语法
在上一篇文章中我们已经运行了个简单的java程序,但是没有给大家讲解代码部分的内容与含义.学习,我们要做到知其然而知其所以然,所以本篇文章我们就来讲解java程序的基本语法,学完这篇文章你再回头看上篇 ...
- [Java 教程 03] 我的第一个Java程序
现在,大家应该都已经安装好jdk环境了吧!是不是已经跃跃欲试,按耐不住心中的小激动了?那我们现在就来写我们java学习生涯中的第一个java程序. 文件相关设置 为了方便后面大家的学习呢?有一点大家还 ...
- [Java 教程 02] 开发环境搭建
在上一篇文章对Java做了一个简单介绍之后,我想大家都已经对她有一个初步的认识了吧!那踏入正式学习使用Java之前,我们有一步是不得不做的,它是什么呢?没有错,就是我们本篇文章的标题所说,搭建Java ...
- Java时间格式字符串与Date的相互转化
目录 将Date转化为格式化字符串 时间格式字符串转化为Date @ 将Date转化为格式化字符串 将Date转化为格式化字符串是利用SimpleDateFormat类继承自 java.text.Da ...
- 一些常见JAVA问题
原文:https://blog.csdn.net/weiyongxuan/article/details/45920765 一.Java的异常的基类是java.lang.Throwable 二.守护线 ...
随机推荐
- 0815NOIP模拟测试赛后总结
立个flag:今天一定改完最少两道题然后认认真真写题解. 8/16 upd:果然flag不要立太狠…… 赛时状态: 赛后的老师:这套题我就没想让你上100分. 120分的天皇大神撇了撇嘴. 众人:…… ...
- WebService Exceptions
一. Exception in thread "main" java.lang.ExceptionInInitializerError at com.sun.xml.interna ...
- HTML 项目符号
无序符号 <ul> <li> </li> <li> </li> <li> </li> </ul> 属性 ...
- C# GDI+编程(二)
常用的绘图函数 DrawArc绘制一个弧形 示例:graphics.DrawArc(pen,,,,,,) 倒数第二个参数,表示起始度数,最后一个参数是弧形的跨越度数.比如起始度数是90,跨越度数是12 ...
- Spring Boot使用Swagger2
1.添加Swagger2依赖 <dependency> <groupId>io.springfox</groupId> <artifactId>spri ...
- 解决Navicat 报错:1130-host is not allowed MySQL不允许从远程访问的方法
ERROR 1130: Host '192.168.1.3' is not allowed to connect to thisMySQL server 解决方法: 1. 改表法.可能是你的帐号不允许 ...
- 去掉IE提示:在此页上的ActiveX控件和本页上的其他部分的交互可能不安全。你想允许这种交互吗?
由于项目需求,需要用到OCX控件.而在IE浏览器中加载OCX控件会有如下提示: 这是因为OCX控件有一个ID,而这个ID注册后IE不认为该OCX控件是安全的.所以,必须把这个控件注册为安全控件. 假设 ...
- JZOJ100048 【NOIP2017提高A组模拟7.14】紧急撤离
题目 题目大意 给你一个01矩阵,每次询问从一个点是否可以走到另一个点. 每次走只能往右或者往下. 思考历程 这题啊,我想的时候真的是脑洞大开-- 首先,我一眼看下去,既然要询问是否联通,那么能不能求 ...
- pyinstaller 打包python3.6文件成exe 运行
1.安装pyinstaller 切换到安装目录下script 运行 如我的目录:F:\Program Files\Python36\Scripts pip install pyinstaller ...
- Django项目:CRM(客户关系管理系统)--74--64PerfectCRM实现CRM课程排名详情
#urls.py """PerfectCRM URL Configuration The `urlpatterns` list routes URLs to views. ...