How to check if thread holds the monitor in IntelliJ? - java

While working on IntelliJ , I am unable to check that if the thread is holding the lock or not.
On eclipse GUI there is a lock like icon against the thread , telling us that it is holding that lock.
In below code snapshot, my thread is at notifyElementAdded() and holding the lock however, in a thread stack there is no such Icon or intimation from Intellij
So my question is how to check the same on IntelliJ GUI.

There is actually a boolean attribute to the Thread class in Java - Thread.holdsLock().
To get the name of the thread which holds the monitor you can use the code example below:
public static long getMonitorOwner(Object obj)
{
if (Thread.holdsLock(obj))
{
return Thread.currentThread().getId();
}
}

I don't think there is a similar functionality. But you can still check by getting the dump
You can click on Get Thread Dump in Debug window and then you can see the locked in the log to see that the thread is actually holding the lock

Create a custom variable in the Intellij debugging console using the plus button as shown in the image below.
Now every time you run the code in the debug mode, this variable will be re-calculated at your all debug points.
I created a variable- Thread.holdsLock(AwsS3ClientHelper.class) since I was acquiring a lock on the class itself. You can write any variable of your choice there. In your particular case, it will be Thread.holdsLock(observers).

This can be a potential feature request for IntelliJ to include this to their GUI product.
Programmatically, to verify this you can use the java.lang.Thread.holdsLock() method which returns true if and only if the current thread holds the monitor lock on the specified object
public static boolean holdsLock(Object obj)
Below snippet of run method for reference,
public void run() {
/* returns true if thread holds monitor lock */
// returns false
System.out.println("Holds Lock = " + Thread.holdsLock(this));
synchronized (this) {
// returns true
System.out.println("Holds Lock = " + Thread.holdsLock(this));
}
}

Related

System.out.println on my boolean made my program able to validate the boolean

My program is based on two threads that share a protocol object. Depending on a boolean in the shared protocol object I try to make the other thread wait before using the protocol.
Main:
GameProtocol protocol = new GameProtocol();
MyThreadedClass thread1 = new MyThreadedClass(protocol);
MyThreadedClass thread2 = new MyThreadedClass(protocol);
thread1.start()
thread2.start()
Thread class:
GameProtocol protocol;
private MyThreadedClass(GameProtocol protocol){
this.protocol = protocol
}
private GamePackage waitCheck(GamePackage gp){
if(!gp.isWaiting()) {
return protocol.update(gp);
}
while(protocol.waitForCategory) {
//System.out.println(protocol.waitForCategory);
}
return protocol.update(gp);
}
Protocol class:
boolean waitForCategory = false;
public synchronized GamePackage update(GamePackage gp){
if(gp.myTurnToPickCategory){
gp.setWaiting(false);
waitForCategory = true;
} else {
gp.setWaiting(true);
waitForCategory = false;
}
return gp;
}
Now my intention is to make one thread wait untill the other thread have used the update method a second time. But the second thread get stuck in the while loop even tho the boolean waitForCategory have been set to false. Once I added the line System.out.println(protocol.waitForCategory); however it just started to work, and if I remove it it stops working again. I can't seem to understand how a ´sout´ on the boolean make it work. If anyone understands this would it be possible to solve it in another way? as having a sout inside a loop like that will make it messy.
As others have already explained, the introduction of println() inserts synchronization into the picture, so your code gives the illusion that it works.
In order to solve this problem you have to make sure everything is properly synchronized. In other words, gp.isWaiting() must also be synchronized, and protocol.waitForCategory must be moved into a method and synchronized.
Alternatively, quit trying to work with synchronization and use asynchronous message passing via java.util.concurrent.BlockingQueue instead. Your code will perform better, you will not be running the danger of race conditions, and your code will also be testable. (Whereas with synchronization your code will never be testable, because there is no test that will catch a race condition.)

Java : one lock per method per object

I'm building a webcrawler and it has 2 main feature wich are both executed as threads :
-The fetcher (crawl a website and separate links from files store both of them into the database).
-The downloader (download files based on their url returned by the fetcher).
I've an object WebSite wich include everything I want to know about a website. Now I want to manipulate my database to change the status of a link from waiting to fetching then to fetched. The same goes for files from waiting to downloading then to downloaded.
To prevent a Fetcher to fetch a link that has been chosen by another fetcher I've done this function inside my WebSite object :
public synchronized String[] getNextLink(){
//Return the next link from database that has visited set to 0 then change it to -1 to say that it's in-use.
}
And I've done the same for my Downloaders with this function :
public synchronized String getNextFile(){
//Return the next file from database that has downloaded set to 0 then change it to -1 to say that it's downloading
}
Both method are inside my WebSite object since if 2 Fetchers are working with different websites they cannot Select the same row inside my database (same goes for downloaders). But both function can be called at the same time because Fetchers never select a file and Downloaders never select a link.
Now synchronized is using a single lock (per object) so both of my methods cannot be called at the same time. Is there another keyword to use one lock per method per object ? Or do I need to code it ?
Instead of applying the synchronized keyword to whole methods, which implicitly uses this as a lock-object, you can use two independent lock objects (and any object can be used as a lock-object in Java) within the methods. Each lock object will be independent of others:
private final Object fetcherMutex = new Object();
private final Object downloaderMutex = new Object();
public String[] getNextLink(){
synchronized (fetcherMutex) { /* ... */ }
}
public String[] getNextFile(){
synchronized (downloaderMutex) { /* ... */ }
}

Relationship between Threads and println() statements

I was trying to create a few scenarios to demonstrate visibility issues while sharing variable across threads. And I noticed that in almost all the cases I tested, if inside run() I added a System.out.println() statement in the same block of code where I am using the shared variable, the visibility issue is not producible. I will provide one example:
Configuration details - Oracle Java6 64bit, Eclipse Juno SR 2
1)WITH VISIBILITY ISSUE:
public class NoVisibility_Demonstration extends Thread {
boolean keepRunning = true;
public static void main(String[] args) throws InterruptedException {
NoVisibility_Demonstration t = new NoVisibility_Demonstration();
t.start();
Thread.sleep(1000);
t.keepRunning = false;
System.out.println("keepRunning is false");
}
public void run() {
int x = 1;
while (keepRunning)
{
//System.out.println("If you uncomment this line, the code will work without the visibility issue");
x++;
}
System.out.println("x:"+x);
}
}
OUTPUT: The thread keeps running infinitely
2) WITHOUT VISIBILITY ISSUE:
THE SAME CODE AS ABOVE, WITH THE UNCOMMENTED println() STATEMENT IN THE run()
OUTPUT:
...
If you uncomment this line, the code will work without the visibility issue
If you uncomment this line, the code will work without the visibility issue
If you uncomment this line, the code will work without the visibility issue
x:19391
keepRunning is false
Since I noticed similar behavior in all the examples I tried, I am wondering if there is any data integrity check by JVM before any I/O operation.
PrintWriter is synchronized
public void println(String x) {
synchronized(this) {
this.print(x);
this.newLine();
}
}
Two sequential calls of System.out.println() in main thread and in second thread create a synchronization order between two threads. That means that all actions (in your case it is variable update), that happened in main thread before releasing a monitor (exiting synchronized method) will be seen by the code, executed in second thread after it acquires a monitor (enter synchronized method).
In simple words, yes, calling System.out.println() makes this synchronization.
This behaviour is implementation specific. In OpenJDK, println's body is synchronized altough the API does not state that it is.

How to make an async listener do blocking?

I am writing a blackberry app that communicates with a simple Bluetooth peripheral using text based AT commands - similar to a modem... I can only get it working on the blackberry using an event listener. So the communication is now asynchronous.
However, since it is a simple device and I need to control concurrent access, I would prefer to just have a blocking call.
I have the following code which tries to convert the communications to blocking by using a wait/notify. But when I run it, notifyResults never runs until getStringValue completes. i.e. it will always timeout no matter what the delay.
The btCon object runs on a separate thread already.
I'm sure I am missing something obvious with threading. Could someone kindly point it out?
Thanks
I should also add the the notifyAll blows up with an IllegalMonitorStateException.
I previously tried it with a simple boolean flag and a wait loop. But the same problem existed. notifyResult never runs until after getStringValue completes.
public class BTCommand implements ResultListener{
String cmd;
private BluetoothClient btCon;
private String result;
public BTCommand (String cmd){
this.cmd=cmd;
btCon = BluetoothClient.getInstance();
btCon.addListener(this);
System.out.println("[BTCL] BTCommand init");
}
public String getStringValue(){
result = "TIMEOUT";
btCon.sendCommand(cmd);
System.out.println("[BTCL] BTCommand getStringValue sent and waiting");
synchronized (result){
try {
result.wait(5000);
} catch (InterruptedException e) {
System.out.println("[BTCL] BTCommand getStringValue interrupted");
}
}//sync
System.out.println("[BTCL] BTCommand getStringValue result="+result);
return result;
}
public void notifyResults(String cmd) {
if(cmd.equalsIgnoreCase(this.cmd)){
synchronized(result){
result = btCon.getHash(cmd);
System.out.println("[BTCL] BTCommand resultReady: "+cmd+"="+result);
result.notifyAll();
}//sync
}
}
}
Since both notifyResults and getStringValue have synchronized clauses on the same object, assuming getStringValues gets to the synchronized section first notifyResults will block at the start of the synchronized clause until getStringValues exits the synchronized area. If I understand, this is the behaviour you're seeing.
Nicholas' advice is probably good, but you may not find any of those implementations in BlackBerry APIs you're using. You may want to have a look at the produce-consumer pattern.
It may be more appropriate to use a Latch, Semaphore, or a Barrier, as recommended by Brian Goetz book Java Concurrency in Practice.
These classes will make it easier to write blocking methods, and will likely help to prevent bugs, especially if you are unfamiliar with wait() and notifyAll(). (I am not suggesting that YOU are unfamiliar, it is just a note for others...)
The code will work ok. If you will use final object instead of string variable. I'm surprised that you don't get NPE or IMSE.
Create field:
private final Object resultLock = new Object();
Change all synchronized sections to use it instead of string field result.
I don't like magic number 5 sec. I hope you treat null result as timeout in your application.

How to understand this CCAS locking machanizion used in AKKA?

I just came across a piece of code in akka.
https://codereview.scala-lang.org/fisheye/browse/~raw,r=25521/scala-svn/scala/trunk/test/files/presentation/akka/src/akka/util/LockUtil.scala
The core methods I am interested in is listed below.
/**
* A very simple lock that uses CCAS (Compare Compare-And-Swap)
* Does not keep track of the owner and isn't Reentrant, so don't nest and try to stick to the if*-methods
*/
class SimpleLock {
val acquired = new AtomicBoolean(false)
def ifPossible(perform: () => Unit): Boolean = {
if (tryLock()) {
try {
perform
} finally {
unlock()
}
true
} else false
}
def tryLock() = {
if (acquired.get) false
else acquired.compareAndSet(false, true)
}
def tryUnlock() = {
acquired.compareAndSet(true, false)
}
There are two related subquestions.
1) What's purpose of this class SimpleLock
2) Any hints or background knowledge about how it works?
I think since this code is written in both JAVA and scala, it leverages the AtomicBoolean class.
So I'd add java tag also.
Any advice is welcome! Not sure why someone vote this question close.
Related:
Can anyone interpret this C++ code (from OpenJDK6) into plain English?
Here is my understanding of the code. It used a acquired(AtomicBoolean) as a mutex. If any thread tries to acquire the lock , then it will set acquired to be true. then any other thread cannot acquired the lock due to they will get true from acquired and returned false until this acquired is set back to false by this thread.
Since acquired is not from a collection, it will not have ABA problem. So it can work.
Please correct me if I am wrong.

Categories

Resources