I try to do a testing for HashTable Sychronized behavior today.

As an Sychronized Object, HashTable already an Sychronized at put and get function. I wanna to know more about the iterator behaviors on multi-threading.

 package leetcode;

 import java.util.Hashtable;
import java.util.Iterator;
import java.util.Map.Entry; public class MultiThread {
static Hashtable<Integer, Integer> sharedTable = new Hashtable<Integer, Integer>();
static final class ThreadOne implements Runnable{
public ThreadOne(){ }
@Override
public void run() {
// TODO Auto-generated method stub
System.out.println("Thread One running: add key-value pair to sharedTable");
for(int i = 0; i < 20; i ++){
sharedTable.put(i, i);
System.out.println("Put " + i + " into sharedTable");
}
}
} static final class ThreadTwo implements Runnable{
public ThreadTwo(){ }
@Override
public void run(){
System.out.println("Thread Two running: iterate the hashtable");
Iterator it = sharedTable.entrySet().iterator();
while(it.hasNext()){
Entry<Integer, Integer> entry = (Entry<Integer, Integer>) it.next();
System.out.println("entry in sharedTable:" + entry.getKey() +" with value:" + entry.getValue());
}
}
} public static void main(String[] agrs){
ThreadOne t1 = new ThreadOne();
ThreadTwo t2 = new ThreadTwo();
System.out.println("Thread start...");
new Thread(t1).start();
new Thread(t2).start();
System.out.println("Thread all started.");
}
}

I make two thread.

ThreadOne do put to hashTable.

ThreadTwo use an iterator to traversal the hashTable.

However, the output is:

 Thread start...
Thread all started.
Thread Two running: iterate the hashtable
Thread One running: add key-value pair to sharedTable
Put 0 into sharedTable
Put 1 into sharedTable
Put 2 into sharedTable
Put 3 into sharedTable
Put 4 into sharedTable
Put 5 into sharedTable
Put 6 into sharedTable
Put 7 into sharedTable
Put 8 into sharedTable
Put 9 into sharedTable
Put 10 into sharedTable
Put 11 into sharedTable
Put 12 into sharedTable
Put 13 into sharedTable
Put 14 into sharedTable
Put 15 into sharedTable
Put 16 into sharedTable
Put 17 into sharedTable
Put 18 into sharedTable
Put 19 into sharedTable

Iterator is initated, however it.hasNext() return false and then exit.

This means that Iterator is broken by put function. It is not sychronized for thread.

So how to make it sychronized?

 package leetcode;

 import java.util.Hashtable;
import java.util.Iterator;
import java.util.Map.Entry; public class MultiThread {
static final class Shared{
private static Hashtable<Integer, Integer> sharedTable = new Hashtable<Integer, Integer>(); public Shared(){
sharedTable = new Hashtable<Integer, Integer>();
}
public synchronized static void put(Integer key, Integer val){
System.out.println("put (" + key + ":" + val + ")into sharedTable.");
sharedTable.put(key, val);
} public synchronized static Integer get(Integer key){
return sharedTable.get(key);
} public synchronized static Boolean containsKey(Integer key){
return sharedTable.containsKey(key);
} public synchronized static void traversal(){
System.out.println("traversal on the sharedTable...");
Iterator it = sharedTable.values().iterator();
while(it.hasNext()){
Integer val = (Integer)it.next();
System.out.println("sharedTable contains val: " + val);
}
System.out.println("Finish traversal.");
} }
static final class ThreadOne implements Runnable{
public ThreadOne(){ }
@Override
public void run() {
// TODO Auto-generated method stub
System.out.println("Thread One running: add key-value pair to sharedTable");
for(int i = 0; i < 20; i ++){
Shared.put(i, i);
}
}
} static final class ThreadTwo implements Runnable{
public ThreadTwo(){ }
@Override
public void run(){
System.out.println("Thread Two running: iterate the hashtable");
Shared.traversal();
}
} public static void main(String[] agrs) throws InterruptedException{
ThreadOne t1 = new ThreadOne();
ThreadTwo t2 = new ThreadTwo();
System.out.println("Thread start...");
new Thread(t1).start();
Thread.sleep(1);
new Thread(t2).start();
System.out.println("Thread all started.");
}
}

One way to solve is put sharedResources into an Bean. And for all getter / setter / traversal make them sychronized. All the customer/ producor have to call this class to use resources( this is the idea of broker, who is working between clinet and servers).

output:

 Thread start...
Thread One running: add key-value pair to sharedTable
put (0:0)into sharedTable.
put (1:1)into sharedTable.
put (2:2)into sharedTable.
put (3:3)into sharedTable.
Thread all started.
put (4:4)into sharedTable.
put (5:5)into sharedTable.
put (6:6)into sharedTable.
Thread Two running: iterate the hashtable
put (7:7)into sharedTable.
traversal on the sharedTable...
sharedTable contains val: 7
sharedTable contains val: 6
sharedTable contains val: 5
sharedTable contains val: 4
sharedTable contains val: 3
sharedTable contains val: 2
sharedTable contains val: 1
sharedTable contains val: 0
Finish traversal.
put (8:8)into sharedTable.
put (9:9)into sharedTable.
put (10:10)into sharedTable.
put (11:11)into sharedTable.
put (12:12)into sharedTable.
put (13:13)into sharedTable.
put (14:14)into sharedTable.
put (15:15)into sharedTable.
put (16:16)into sharedTable.
put (17:17)into sharedTable.
put (18:18)into sharedTable.
put (19:19)into sharedTable.

Or dont sychronized the whole function, only for the part that use the resource. In this way, actually we dont need an specific class to encapture the resources:

 package leetcode;

 import java.util.Hashtable;
import java.util.Iterator; public class MultiThread {
static final class ThreadOne implements Runnable{
public ThreadOne(){ }
@Override
public void run() {
// TODO Auto-generated method stub
System.out.println("Thread One running: add key-value pair to sharedTable");
for(int i = 0; i < 100; i ++){
synchronized(sharedTable){
System.out.println("put (" + i + ":" + i + ")into sharedTable.");
sharedTable.put(i, i);
}
}
}
} static final class ThreadTwo implements Runnable{
public ThreadTwo(){ }
@Override
public void run(){
System.out.println("Thread Two running: iterate the hashtable");
System.out.println("traversal on the sharedTable...");
synchronized(sharedTable){
Iterator it = sharedTable.values().iterator();
while(it.hasNext()){
Integer val = (Integer)it.next();
System.out.println("sharedTable contains val: " + val);
}
}
System.out.println("Finish traversal.");
}
} public static void main(String[] agrs) throws InterruptedException{
ThreadOne t1 = new ThreadOne();
ThreadTwo t2 = new ThreadTwo();
System.out.println("Thread start...");
new Thread(t1).start();
Thread.sleep(1);
new Thread(t2).start();
System.out.println("Thread all started.");
}
private static Hashtable<Integer, Integer> sharedTable = new Hashtable<Integer, Integer>();
}

multi thread for Java的更多相关文章

  1. Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/commons/logging/LogFactory

    学习架构探险,从零开始写Java Web框架时,在学习到springAOP时遇到一个异常: "C:\Program Files\Java\jdk1.7.0_40\bin\java" ...

  2. Exception in thread "main" java.lang.NoSuchMethodError: org.objectweb.asm.ClassWriter.<init>(I)V

    在学习CGlib动态代理时,遇到如下错误: Exception in thread "main" java.lang.NoSuchMethodError: org.objectwe ...

  3. GUI学习中错误Exception in thread "main" java.lang.NullPointerException

    运行时出现错误:Exception in thread "main" java.lang.NullPointerException 该问题多半是由于用到的某个对象只进行了声明,而没 ...

  4. 执行打的maven jar包时出现“Exception in thread "main" java.lang.SecurityException: Invalid signature file digest for Manifest main attributes”

    Exception in thread "main" java.lang.SecurityException: Invalid signature file digest for ...

  5. Exception in thread "main" java.lang.ExceptionInInitializerError

    Exception in thread "main" java.lang.ExceptionInInitializerErrorCaused by: java.util.Missi ...

  6. 编译运行java程序出现Exception in thread "main" java.lang.UnsupportedClassVersionError: M : Unsupported major.minor version 51.0

    用javac编译了一个M.java文件, 然后用java M执行,可是出现了下面这个错误. Exception in thread "main" java.lang.Unsuppo ...

  7. dom4j使用xpath报异常 Exception in thread "main" java.lang.NoClassDefFoundError: org/jaxen/NamespaceContext

    Exception in thread "main" java.lang.NoClassDefFoundError: org/jaxen/NamespaceContext      ...

  8. Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1

    场景:eclipse中编写java中用到数组 问题: 程序不报错但是运行过程中 终止,显示字样 “ Exception in thread "main" java.lang.Arr ...

  9. dbca:Exception in thread "main" java.lang.UnsatisfiedLinkError: get

    在64位的操作系统安装oracle10g 软件安装完成后,使用dbca建库的时候报下面的错: $ dbcaUnsatisfiedLinkError exception loading native l ...

随机推荐

  1. CF 1138 F. Cooperative Game

    F. Cooperative Game 链接 题意: 有10个玩家,开始所有玩家在home处,每次可以让一些玩家沿着边前进一步,要求在3(t+c)步以内,到达终点. 分析: 很有意思的一道题.我们构造 ...

  2. Linux新手常见问题

    yum与apt的区别 参考:https://blog.csdn.net/qq_26182553/article/details/79869666 ubuntu下su: Authentication f ...

  3. 开源项目CIIP(企业信息管理系统框架).2018.0904版更新介绍

    源码: https://github.com/tylike/CIIP https://gitee.com/ciip/CIIP 一,CIIP的目标是什么? 更加简单,快速的建立信息类管理系统.让实施人员 ...

  4. C#用Oracle.DataAccess中连接Oracle要注意版本问题!转)

    一般人,不包括全部平时在开发中使用的都是32位的PC机,所以安装的也是Oracle32位的客户端.但是一般服务器都是64位的,安装的也是 64位的Oracle客户端,如果要部署使用Oracle.Dat ...

  5. nginx解析漏洞,配置不当,目录遍历漏洞环境搭建、漏洞复现

    nginx解析漏洞,配置不当,目录遍历漏洞复现 1.Ubuntu14.04安装nginx-php5-fpm 安装了nginx,需要安装以下依赖 sudo apt-get install libpcre ...

  6. play-with-vim1~5

    1.移动 h,j,k,l分别对应左下上右 2.模式 vim有四种模式:普通模式,插入模式,可视模式,命令行模式 进入vim 默认为普通模式,光标为方块 输入i 进入插入模式,窗口左下角为insert ...

  7. Flash导出安卓端apk

    最近外甥女在学校做了一个演示视频,基于flash做的,希望小舅给她导出成可以运行在pc/android端的可执行程序.看了下过程还是蛮复杂的,还只能一天时间.重新照葫芦画瓢做一款是来不及了,由于以前基 ...

  8. OpenFastPath(1):快平面接口是否支持多ip

    1.配置环境 fp0接口上配置两个IP地址: fp0       Link encap:Ethernet  HWaddr 00:0c:29:30:38:db inet addr:192.168.56. ...

  9. OLAP和OLTP的区别

    OLAP(On-Line Analytical Processing)联机分析处理,也称为面向交易的处理过程,其基本特征是前台接收的用户数据可以立即传送到计算中心进行处理,并在很短的时间内给出处理结果 ...

  10. Go的CSP并发模型

    golang的goroutine机制:        一.go 内部有三个对象: P对象(processor) 代表上下文(或者可以认为是cpu),M(work thread)代表工作线程,G对象(g ...