在Java中增加锁的数量的最佳方法是什么? [英] What is the best way to increase number of locks in Java?

查看:377
本文介绍了在Java中增加锁的数量的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此问题基于在整数上同步会导致NullPointerException 并源自此问题在整数值上同步



我想知道什么是增加Java锁的最佳方法。除此之外,在中实现ConcurrentHashMap ie基于Fixed数组并通过计算键的哈希值来引用数组的索引



以下是预期。
如果一个对象的 doMoreThing()正在进行,那么我不应该为 doAnotherThing()

  public void doSomething(int i){
doAnotherThing(i); //一些检查这里基于它将调用
// doMoreThing
doMoreThing(i);
}


解决方案

Object 在Java中有一个关联的锁。如果你想要一个新的锁,你可以创建一个新的对象。引用的问题并不清楚为什么你想增加锁的数量,或者你的意思。



我认为我看到你的目标:有效地,你想在 int 同步 c> doSomething 正在传递。有两种相对简单的方法来做你所做的事情:



a是真的重要的是几个线程能够调用 doSomething 不同 int 同时使用?如果没有,您可以在同步(this)



b) int 不是 Object 。如果你改变 doSomething 取一个 Integer ,并且改变任何调用 doSomething (和任何调用等等)也使用 Integer ,您可以在 Integer 。在这里确保每个调用者都使用相同的 Integer 对象很重要 - 可以有多个 Integer 具有相同的 int 值,但在不同的整数上同步将不能提供您要找的保护。


This question is based on Synchronizing on an Integer results in NullPointerException and originated from this question Synchronizing on an Integer value

I wanted to know what is the best way to increase number of locks in Java. Other than which is implemented in ConcurrentHashMap i.e. Based on Fixed array and by calculating hash of key to refer index of array?

Below is what is expected. If doMoreThing() for one object is in process then I should not do doAnotherThing() for the same object if it called from different thread.

public void doSomething(int i) {
    doAnotherThing(i);// some checks here based on it it will call to
                        // doMoreThing
    doMoreThing(i);
}

解决方案

Every Object in Java has an associated lock. If you want a new lock, you can create a new Object. The referenced question doesn't make it clear why you're trying to increase the number of locks, or what you mean by that. Maybe you can provide more details.

Update following changed question

I think I see what you're aiming at: effectively, you want a synchronized block on the int that doSomething is getting passed. There are two relatively simple ways to do what you're after:

a) Is it really important that several threads be able to call doSomething simultaneously with different ints? If not, you could just place both calls within a synchronized(this)

b) ints are not Objects. If you change doSomething to take an Integer and also change whatever's calling doSomething (and whatever's calling that, and so forth) to also use Integers, you can synchronize on the Integer. It's important here to make sure that every caller will be using the same Integer object - it's possible to have multiple Integers that have the same int value, but synchronizing on different Integers won't provide the protection you're looking for.

这篇关于在Java中增加锁的数量的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆