同步(synchronized)对程序性能的影响!
2007-08-31 01:34
309 查看
在使用多线程时,可能会访问一些全局的数据,这时必然会使用同步机制来使程序按照一定顺序来执行,这样程序的性能也会下降。所以一定要慎用同步,正确用同步。看下面的程序
int curIndex = 0;
AuditQueueEntry aqe;
synchronized (localCriticalSection)
{
while (curIndex < theList.size())
{
aqe = (AuditQueueEntry) theList.get(curIndex);
if (aqe.getTrailId() == theTrailId)
{
theList.remove(curIndex);
} else
{
curIndex++;
}
}
}
localCriticalSection做为一个信号量来控制程序对类成员变量theList的访问,从而保证了theList在同一时间只有一个程序访问。运行程序,这个函数花费了将近4秒钟。同步是很耗时间的。
在java.util.Collections中提供了很多方法来保证集合(数组)的同步访问。
我们修改类成员变量theList的实例化方法:
theList = Collections.synchronizedList(new LinkedList());
再修改处理函数:
int curIndex = 0;
AuditQueueEntry aqe;
// synchronized (localCriticalSection) {
synchronized(theList)
{
while (curIndex < theList.size())
{
aqe = (AuditQueueEntry) theList.get(curIndex);
if (aqe.getTrailId() == theTrailId)
{
theList.remove(curIndex);
} else
{
curIndex++;
}
}
}
再运行,这个函数才花费将近一秒钟的时间!
在Collections中提供了很多这类的方法。
int curIndex = 0;
AuditQueueEntry aqe;
synchronized (localCriticalSection)
{
while (curIndex < theList.size())
{
aqe = (AuditQueueEntry) theList.get(curIndex);
if (aqe.getTrailId() == theTrailId)
{
theList.remove(curIndex);
} else
{
curIndex++;
}
}
}
localCriticalSection做为一个信号量来控制程序对类成员变量theList的访问,从而保证了theList在同一时间只有一个程序访问。运行程序,这个函数花费了将近4秒钟。同步是很耗时间的。
在java.util.Collections中提供了很多方法来保证集合(数组)的同步访问。
我们修改类成员变量theList的实例化方法:
theList = Collections.synchronizedList(new LinkedList());
再修改处理函数:
int curIndex = 0;
AuditQueueEntry aqe;
// synchronized (localCriticalSection) {
synchronized(theList)
{
while (curIndex < theList.size())
{
aqe = (AuditQueueEntry) theList.get(curIndex);
if (aqe.getTrailId() == theTrailId)
{
theList.remove(curIndex);
} else
{
curIndex++;
}
}
}
再运行,这个函数才花费将近一秒钟的时间!
在Collections中提供了很多这类的方法。
相关文章推荐
- volatile,Atomic ,synchronized性能和同步测试程序
- java代码中黄色警告是否会对程序编译和运行有性能上的影响
- 关于import中使用*号是否会影响程序性能
- SQL对程序性能的影响
- SQL对程序性能的影响
- 内存分配对多线程程序性能的影响
- 选择排序法 当数据量较小的时候,使用基本排序方案并不会显著影响程序性能。 选择排序是十分常用的基本排序方案之一。
- 影响ASP.NET程序性能的因素
- 各种同步方法性能比较(synchronized,ReentrantLock,Atomic)
- 程序中使用now()函数对性能的影响
- AIX 6.1 参数配置分析和建议-关闭影响性能的系统程序
- Java同步机制浅谈――synchronized对代码作何影响?
- Java同步机制浅谈 synchronized对代码作何影响?
- 警惕32位程序在MethodImplOptions.Synchronized在x64机器上的同步缺陷
- 深入剖析命名管道FIFO对程序性能的影响
- 程序性能优化之map影响
- Try-Catch真的会影响程序性能吗
- C#中使用try...catch...是否会影响程序性能
- Java同步机制浅谈――synchronized对代码作何影响?
- Try-Catch真的会影响程序性能吗