如题,看网上很多人都说这个类是线程安全的,但我看了jdk1.6 的源码,并没有发现这类的线程安全机制,这个类到底是不是安全的,如果是的话,安全机制如何实现的?
问题补充:/*
* Copyright 2001-2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* $Id: Hashtable.java,v 1.4 2004/02/16 22:55:54 minchau Exp $
*/
package com.sun.org.apache.xalan.internal.xsltc.runtime;
import java.util.Enumeration;
/**
* IMPORTANT NOTE:
* This code was taken from Sun's Java1.1 JDK java.util.HashTable.java
* All "synchronized" keywords and some methods we do not need have been
* all been removed.
*/
/**
* Object that wraps entries in the hash-table
* @author Morten Jorgensen
*/
class HashtableEntry {
int hash;
Object key;
Object value;
HashtableEntry next;
protected Object clone() {
HashtableEntry entry = new HashtableEntry();
entry.hash = hash;
entry.key = key;
entry.value = value;
entry.next = (next != null) ? (HashtableEntry)next.clone() : null;
return entry;
}
}
/**
* The main hash-table implementation
*/
public class Hashtable {
private transient HashtableEntry table[]; // hash-table entries
private transient int count; // number of entries
private int threshold; // current size of hash-tabke
private float loadFactor; // load factor
/**
* Constructs a new, empty hashtable with the specified initial
* capacity and the specified load factor.
*/
public Hashtable(int initialCapacity, float loadFactor) {
if (initialCapacity <= 0) initialCapacity = 11;
if (loadFactor <= 0.0) loadFactor = 0.75f;
this.loadFactor = loadFactor;
table = new HashtableEntry[initialCapacity];
threshold = (int)(initialCapacity * loadFactor);
}
/**
* Constructs a new, empty hashtable with the specified initial capacity
* and default load factor.
*/
public Hashtable(int initialCapacity) {
this(initialCapacity, 0.75f);
}
/**
* Constructs a new, empty hashtable with a default capacity and load
* factor.
*/
public Hashtable() {
this(101, 0.75f);
}
/**
* Returns the number of keys in this hashtable.
*/
public int size() {
return count;
}
/**
* Tests if this hashtable maps no keys to values.
*/
public boolean isEmpty() {
return count == 0;
}
/**
* Returns an enumeration of the keys in this hashtable.
*/
public Enumeration keys() {
return new HashtableEnumerator(table, true);
}
/**
* Returns an enumeration of the values in this hashtable.
* Use the Enumeration methods on the returned object to fetch the elements
* sequentially.
*/
public Enumeration elements() {
return new HashtableEnumerator(table, false);
}
/**
* Tests if some key maps into the specified value in this hashtable.
* This operation is more expensive than the <code>containsKey</code>
* method.
*/
public boolean contains(Object value) {
if (value == null) throw new NullPointerException();
int i;
HashtableEntry e;
HashtableEntry tab[] = table;
for (i = tab.length ; i-- > 0 ;) {
for (e = tab[i] ; e != null ; e = e.next) {
if (e.value.equals(value)) {
return true;
}
}
}
return false;
}
/**
* Tests if the specified object is a key in this hashtable.
*/
public boolean containsKey(Object key) {
HashtableEntry e;
HashtableEntry tab[] = table;
int hash = key.hashCode();
int index = (hash & 0x7FFFFFFF) % tab.length;
for (e = tab[index] ; e != null ; e = e.next)
if ((e.hash == hash) && e.key.equals(key))
return true;
return false;
}
/**
* Returns the value to which the specified key is mapped in this hashtable.
*/
public Object get(Object key) {
HashtableEntry e;
HashtableEntry tab[] = table;
int hash = key.hashCode();
int index = (hash & 0x7FFFFFFF) % tab.length;
for (e = tab[index] ; e != null ; e = e.next)
if ((e.hash == hash) && e.key.equals(key))
return e.value;
return null;
}
/**
* Rehashes the contents of the hashtable into a hashtable with a
* larger capacity. This method is called automatically when the
* number of keys in the hashtable exceeds this hashtable's capacity
* and load factor.
*/
protected void rehash() {
HashtableEntry e, old;
int i, index;
int oldCapacity = table.length;
HashtableEntry oldTable[] = table;
int newCapacity = oldCapacity * 2 + 1;
HashtableEntry newTable[] = new HashtableEntry[newCapacity];
threshold = (int)(newCapacity * loadFactor);
table = newTable;
for (i = oldCapacity ; i-- > 0 ;) {
for (old = oldTable[i] ; old != null ; ) {
e = old;
old = old.next;
index = (e.hash & 0x7FFFFFFF) % newCapacity;
e.next = newTable[index];
newTable[index] = e;
}
}
}
/**
* Maps the specified <code>key</code> to the specified
* <code>value</code> in this hashtable. Neither the key nor the
* value can be <code>null</code>.
* <p>
* The value can be retrieved by calling the <code>get</code> method
* with a key that is equal to the original key.
*/
public Object put(Object key, Object value) {
// Make sure the value is not null
if (value == null) throw new NullPointerException();
// Makes sure the key is not already in the hashtable.
HashtableEntry e;
HashtableEntry tab[] = table;
int hash = key.hashCode();
int index = (hash & 0x7FFFFFFF) % tab.length;
for (e = tab[index] ; e != null ; e = e.next) {
if ((e.hash == hash) && e.key.equals(key)) {
Object old = e.value;
e.value = value;
return old;
}
}
// Rehash the table if the threshold is exceeded
if (count >= threshold) {
rehash();
return put(key, value);
}
// Creates the new entry.
e = new HashtableEntry();
e.hash = hash;
e.key = key;
e.value = value;
e.next = tab[index];
tab[index] = e;
count++;
return null;
}
/**
* Removes the key (and its corresponding value) from this
* hashtable. This method does nothing if the key is not in the hashtable.
*/
public Object remove(Object key) {
HashtableEntry e, prev;
HashtableEntry tab[] = table;
int hash = key.hashCode();
int index = (hash & 0x7FFFFFFF) % tab.length;
for (e = tab[index], prev = null ; e != null ; prev = e, e = e.next) {
if ((e.hash == hash) && e.key.equals(key)) {
if (prev != null)
prev.next = e.next;
else
tab[index] = e.next;
count--;
return e.value;
}
}
return null;
}
/**
* Clears this hashtable so that it contains no keys.
*/
public void clear() {
HashtableEntry tab[] = table;
for (int index = tab.length; --index >= 0; )
tab[index] = null;
count = 0;
}
/**
* Returns a rather long string representation of this hashtable.
* Handy for debugging - leave it here!!!
*/
public String toString() {
int i;
int max = size() - 1;
StringBuffer buf = new StringBuffer();
Enumeration k = keys();
Enumeration e = elements();
buf.append("{");
for (i = 0; i <= max; i++) {
String s1 = k.nextElement().toString();
String s2 = e.nextElement().toString();
buf.append(s1 + "=" + s2);
if (i < max) buf.append(", ");
}
buf.append("}");
return buf.toString();
}
/**
* A hashtable enumerator class. This class should remain opaque
* to the client. It will use the Enumeration interface.
*/
class HashtableEnumerator implements Enumeration {
boolean keys;
int index;
HashtableEntry table[];
HashtableEntry entry;
HashtableEnumerator(HashtableEntry table[], boolean keys) {
this.table = table;
this.keys = keys;
this.index = table.length;
}
public boolean hasMoreElements() {
if (entry != null) {
return true;
}
while (index-- > 0) {
if ((entry = table[index]) != null) {
return true;
}
}
return false;
}
public Object nextElement() {
if (entry == null) {
while ((index-- > 0) && ((entry = table[index]) == null));
}
if (entry != null) {
HashtableEntry e = entry;
entry = e.next;
return keys ? e.key : e.value;
}
return null;
}
}
}
相关推荐
HashMap和HashTable的区别?但是如果想线程安全有想效率高?
3. 使用HashTable:虽然HashTable是线程安全的,但由于其所有操作都是同步的,所以在多线程并发访问时,性能较低。因此,在现代Java开发中,通常更倾向于使用ConcurrentHashMap。 4. 避免在多线程环境中直接使用...
在Java编程语言中,`Hashtable`是`Collections`框架的一部分,它是一个同步的键值对存储容器。...在实际开发中,`HashMap`通常是首选,因为它的性能更好,但`Hashtable`在需要线程安全的情况下仍然是一个不错的选择。
2. 使用线程安全的对象:使用线程安全的对象,如 Vector、Hashtable 等,而不是 ArrayList、HashMap 等。 3. 使用锁机制:使用锁机制,如 synchronized 关键字,可以锁定某个对象,以避免多个线程同时访问同一个对象...
在Java中,`HashTable`类是最早的同步容器类之一,它是线程安全的,意味着在多线程环境下可以安全地使用。然而,由于其所有的操作都是同步的,这在单线程环境中可能会导致性能下降。`HashTable`不支持空键和空值,且...
在Java编程中,集合框架是数据管理的核心部分。...此外,Java并发库(如`ConcurrentHashMap`、`CopyOnWriteArrayList`等)提供了更高效且线程安全的解决方案,可以在性能和线程安全之间找到更好的平衡。
在Java编程中,多线程和线程安全是核心概念,尤其在开发高效并发应用程序时。本项目"JAVA多线程与线程安全实践-基于Http协议的断点续传"探讨了如何在Java中实现多线程以及如何确保线程安全,特别是在处理HTTP协议的...
1. 线程安全:HashMap不是线程安全的,而HashTable是线程安全的。 2. 性能:HashMap的性能比HashTable好,因为HashMap使用数组和链表来存储键值对,而HashTable使用链表来存储键值对。 3. null键:HashMap允许存放...
Java 中有多种集合类,如 Vector、ArrayList、LinkedList、HashTable、HashMap、HashSet 等,这些集合类在多线程环境中的安全性各不相同。 Vector 和 ArrayList Vector 和 ArrayList 都是 Java 中常用的集合类,...
线程安全的集合对象,如Vector、HashTable和StringBuffer,相比于非线程安全的ArrayList、LinkedList、HashMap、HashSet、TreeMap和TreeSet、StringBuilder等,提供了额外的线程安全保障,但可能会牺牲一定的性能。...
在Java编程中,线程安全性和不安全性是并发编程中非常关键的概念。线程安全意味着在多线程环境中,一个类或方法可以被正确地访问和修改,而不会导致数据不一致或错误。线程不安全则表示在多线程环境下,如果不采取...
Java集合框架中有一些线程安全的类,如Vector、HashTable、ConcurrentHashMap等,它们内部实现了同步机制,可以在多线程环境中直接使用,避免了手动同步的复杂性。 十、线程局部变量 ThreadLocal为每个线程都创建了...
在Java编程语言中,`Hashtable`是`Dictionary`类的一个具体实现,它是早期Java版本中的一个线程安全的键值对存储容器。`Hashtable`遵循了一些基本的映射概念,如存储键值对、根据键查找值以及添加、删除键值对等。...
- **线程安全的代价**:由于Hashtable是线程安全的,它的内部实现使用了synchronized关键字,这可能导致在多线程环境下的性能问题。 - **无泛型支持**:Hashtable属于旧版集合框架,不支持泛型,这意味着在使用时...
其次,当涉及到线程安全问题时,Hashtable的方法是同步的,这会使得它在处理多线程操作时更加安全,因此,当需要在多线程环境中共享数据时,Hashtable提供了一种简单而可靠的方式。然而,这一同步也使得Hashtable在...
总之,`Hashtable`是Java早期实现的键值对存储容器,虽然现在有了更现代的替代品,但它仍然是理解Java集合框架历史和线程安全存储的重要组成部分。在某些特定场景下,如需要线程安全且不兼容Java 8或以上版本的代码...
在Java编程中,`Hashtable`是一个古老的容器类,属于`java.util`包,它提供了存储键值对(key-value pairs)的功能。...在选择使用`Hashtable`还是`HashMap`时,应考虑是否需要线程安全以及对性能的需求。
Java中的线程安全性是并发编程中的关键概念,它关乎到多线程环境下程序的稳定性和正确性。线程安全的类意味着在多个线程并行访问时,它们的行为仍然是正确和一致的,无需额外的同步措施。然而,线程安全并不简单地...