Weblogic Stuck Thread - ArrayList - java

We have JSF2.1 app deployed in weblogic10.3.4 ,in one of our backing bean ,when we try to assign the reference ArrayList to a List instance ,weblogic ends up in Struck thread ,during peak traffic to our application.
java.util.ArrayList.indexOf(ArrayList.java:210)
java.util.ArrayList.contains(ArrayList.java:199)
Any one has faced this issue before.

It is not entirely clear what you mean, so I'm going to assume that you mean a "stuck thread", and that the thread is stuck in the sense that it is continually executing at that point.
I can think of three plausible causes.
The object that is being searched for has a buggy equals(Object) method that in some circumstances goes into an infinite loop.
There are two (or more) threads accessing and/or updating the list roughly simultaneously, and you are not synchronizing properly. If you don't synchronize properly, there is a risk that the threads will see inconsistent views of the data structure, and that that will cause it behave in a way that seems impossible.
You've somehow set up a pathological situation that is causing one thread to be both reading and updating the list in the (incorrect) belief that it has two distinct lists.
My bet is that it is the second problem, since "heisenbugs" like that are more likely to occur when your server is under heavy load.
Finally, it is possible that the thread is not in an infinite loop, but is just taking a long time to do something. And it is possible that the loop involves other code, but each time you look at it is at that point.

Related

In parallel processing, is there the concept of "uninterruptible block"? If not, why not?

Summary
From my studies, I don't remember that a concept such "uninterruptible block" exists, and I did not find it either with a quick Google search.
Expected answer
yes, it does exist, and the proper term for that is ... (in this case, it would be nice, if someone could explain me, why it does not exist in Java)
no, it does not exist, because ...
Definition
By "uninterruptible block", I mean a section of code, in a multi-threading context, which, once starts execution, cannot be interrupted by other threads. I.e., the CPU (or the JVM), won't run any other thread at all, until the "atomic block" is left.
Note, that this is not the same as a section marked by lock/mutex/... etc., because such section can not be interrupted only by other threads, which acquire the same lock or mutex. But other threads can still interrupt it.
EDIT, in response to comments It would be fine also, if it affected only the threads of the current process.
RE. multiple cores: I would say, yes, also the other cores should stop, and we accept the performance hit (or, if it is exclusive only for the current process, then the other cores could still run threads of other processes).
Background
First of all, it is clear, that, at least in Java, this concept does not exist:
Atomic as in uninterruptible: once the block starts, it can't be interrupted, even by task switching.
...
[this] cannot be guaranteed in Java - it doesn't provide access to the
"critical sections" primitives required for uninterruptibility.
However, it would have come in handy in the following case: a system sends a request and receives response A. After receiving the response, it has max. 3 seconds to send request B. Now, if multiple threads are running, doing this, then it can happen, that after receiving response A, the thread is interrupted, and one or more threads run, before the original thread has the chance to send out request B, and thus misses the 3 seconds deadline. The more threads are running, the bigger the risk that this happens. By marking the "receive A to send B" section "uninterruptible", this could be avoided.
Note, that locking this section would not solve the issue. (It would not prevent the JVM, from e.g. processing 10 new threads at the "send request A" phase, right after our thread received response A.)
EDIT: Re. global mutex. That would also not solve the issue. Basically, I want the threads to make Request A's (and some other stuff) simultaneously, but I want them to stop, when another thread received Response A, and is going to make Request B.
Now, I know, that this would not be a 100% solution either, because those threads that don't get scheduled right after receiving response A still could miss the deadline. But, at least, those who do, would for sure send out the second request in time.
Some further speculation
The classic concurrency problem a++ could be simply solved by uninterruptible { a++; }, without the need for locks (which can cause dead-lock, and, in any case, would probably be more expensive in terms of performance, than simply executing the three instructions required by a++, with a simple flag, that they must not be interrupted).
EDIT RE. CAS: of course, that's another solution too. However, it involves retrying, until the write succeeds, and it is also slightly more complex to use (at least in Java, we have to use AtomicXXX, instead of the primitive types for that).
I know, of course, that this could be easily abused, by marking large blocks of code as uninterruptible, but that is true for many concurrency primitives as well. (What's more, I also know, that my original use case would be also kind of an "abuse", since I'd be doing I/O in an uninterruptible block, still it would have been worth at least a try, if such concept did exist in Java.)

Java in memory data storage thread safety

I'm making a real time multiplayer game server in Java. I'm storing all data for matches in memory in a HashMap with "match" objects. Each match object contains information about the game and game state for all players (anywhere from 2-5 in one match). The server will pass the same match object for each user's connection to the server.
What I'm a little concerned about is making this thread safe. Connections could be made to different threads in the server, all of which need to access the same match.
The problem with that is there would be a lot of variables/lists in the object, all of which would need to be synchronized. Some of them may need to be used to perform calculations that affect each other, meaning I would need nested synchronized blocks, which I don't want.
Is synchronized blocks for every variable in the match object my only solution, or can I do something else?
I know SQLite has an in memory mode, but the problem I found was this:
Quote from their website:
SQLite supports an unlimited number of simultaneous readers, but it will only allow one writer at any instant in time. For many situations, this is not a problem. Writer queue up. Each application does its database work quickly and moves on, and no lock lasts for more than a few dozen milliseconds. But there are some applications that require more concurrency, and those applications may need to seek a different solution
A few dozen milliseconds? That's a long time. Would that be fast enough, or is there another in memory database that would be suited for real time games?
Your architecture is off in this case. You want a set of data to be modified and updated by several threads at once, which might be possible, but is extremely difficult to get right and fast at the same time.
It would be much easier if you change the architecture like follows:
There is one thread that has exclusive access to a single match object. A thread could handle multiple match objects, but a single match object will only be handled/guarded by a single thread. Now if any external effect wants to change any values, it needs to make a "change request", but cannot change it immediately on it's own. And once the change has been implemented and the values updated, the thread guarding the match object will send out an update to the clients.
So lets say a player scores a goal, then the client thread calls a function
void clientScoredGoal(Client client) {
actionQueue.put(new GoalScoredEvent(client));
}
Where actionQueue is i.E. a BlockingQueue.
The thread handling the match objects is listening on this queue via actionQueue.take() and reacts as soon as a new action has been found. It will then apply the change, updated internal values if neccessary, and then distributes an update package (a "change request" to clients if you want).
Also in general synchronized should be considered bad practice in Java. There are certain situations where it is a good way to handle synchronization, but in like 99% of all cases using features from the Concurrent package will be by far the better solution. Notice the complete lack of synchronized in the example code above, yet it is perfectly thread-safe.
the question is very generic. It is difficult to give specific advice.
I'm making a real time multiplayer game server in Java. I'm storing all data for matches in memory in a HashMap with "match" objects.
If you want to store "match" objects in a Map and then have multiple threads requesting/adding/removing objects from the map, then you have to use a "ConcurrentHashMap".
What I'm a little concerned about is making this thread safe. Connections could be made to different threads in the server, all of which need to access the same match.
The safest and easiest way to have multithreading is to make each "match" an immutable object, then there is no need to synchronize.
If "match" information is mutable and accessed simultaneously by many threads, then you will have to synchronize. But in this case, the "mutable state" is contained within a "match", so only the class "match" will need to use synchronization.
I would need nested synchronized blocks, which I don't want.
I haven't ever seen the need to have nested synchronized blocks. perhaps you should refactor your solution before you try to make it thread safe.
Is synchronized blocks for every variable in the match object my only solution, or can I do something else? I know SQLite has an in memory mode
If you have objects with mutable state that are accessed by multiple threads, then you need to make them thread safe. there is no other way (notice that I didn't say that "synchronized blocks" is the only option. there are different ways to achieve thread safety). Using an in memory database is not the solution to your thread safety problem.
The advantage of using an in memory database is in speeding up the access to information (as you don't have to access a regular database with information stored in an HDD), but with the penalty that now your application needs more RAM.
By the way, even faster than using an in memory database would be to keep all the information that you need within objects in your program (which has the same limitation of requiring more RAM).

Performance issues in Main thread even with AsyncTasks

My Main thread seems to be pretty bad with performance. Transitioning between activities results in significant delays. I have pushed all of Web/Bitmap/File work into AsyncTasks and yet this is still happening. I have been doing my head in trying to figure out what is causing the slow-downs.
My question is - If the Main thread uses a class (say ImageDownloader) that creates its own little AsyncTasks (say ImageDownloadTask), will Main wait for ImageDownloader to finish it's AsyncTasks (hence delays?)
I would love to post code, but it's a very large project. If there is anything specific I should look for, please let me know and I'll be sure to share.
If you haven't already done so, I recommend you enable strict mode and look for activity on the main thread that way.
Check your onCreates and onResumes for anything that might run for more than an instant. This includes network calls, database calls, loops that may have a lot of iterations, and even reading from locally stored files (SharedPreferences read from an xml). Also try to benchmark how long your onCreate executes the setContentView method -- I believe nested LinearLayouts cause significant performance hits especially in complex UI structures. Acquiring a location with the LocationProvider, when not done properly, will also cause severe performance issues.
You may think you are fine with passing off long-running threads on an asynctask, but you also need to check that prior to starting these tasks, the data you need to start them may take a while to acquire.

java application multi-threading design and optimization

I designed a java application. A friend suggested using multi-threading, he claims that running my application as several threads will decrease the run time significantly.
In my main class, I carry several operations that are out of our scope to fill global static variables and hash maps to be used across the whole life time of the process. Then I run the core of the application on the entries of an array list.
for(int customerID : customers){
ConsumerPrinter consumerPrinter = new ConsumerPrinter();
consumerPrinter.runPE(docsPath,outputPath,customerID);
System.out.println("Customer with CustomerID:"+customerID+" Done");
}
for each iteration of this loop XMLs of the given customer is fetched from the machine, parsed and calculations are taken on the parsed data. Later, processed results are written in a text file (Fetched and written data can reach up to several Giga bytes at most and 50 MBs on average). More than one iteration can write on the same file.
Should I make this piece of code multi-threaded so each group of customers are taken in an independent thread?
How can I know the most optimal number of threads to run?
What are the best practices to take into consideration when implementing multi-threading?
Should I make this piece of code multi-threaded so each group of customers are taken
in an independent thread?
Yes multi-threading will save your processing time. While iterating on your list you can spawn new thread each iteration and do customer processing in it. But you need to do proper synchronization meaning if two customers processing requires operation on same resource you must synchronize that operation to avoid possible race condition or memory inconsistency issues.
How can I know the most optimal number of threads to run?
You cannot really without actually analyzing the processing time for n customers with different number of threads. It will depend on number of cores your processor has, and what is the actually processing that is taking place for each customer.
What are the best practices to take into consideration when implementing multi-threading?
First and foremost criteria is you must have multiple cores and your OS must support multi-threading. Almost every system does that in present times but is a good criteria to look into. Secondly you must analyze all the possible scenarios that may led to race condition. All the resource that you know will be shared among multiple threads must be thread-safe. Also you must also look out for possible chances of memory inconsistency issues(declare your variable as volatile). Finally there are something that you cannot predict or analyze until you actually run test cases like deadlocks(Need to analyze Thread dump) or memory leaks(Need to analyze Heap dump).
The idea of multi thread is to make some heavy process into another, lets say..., "block of memory".
Any UI updates have to be done on the main/default thread, like print messenges or inflate a view for example. You can ask the app to draw a bitmap, donwload images from the internet or a heavy validation/loop block to run them on a separate thread, imagine that you are creating a second short life app to handle those tasks for you.
Remember, you can ask the app to download/draw a image on another thread, but you have to print this image on the screen on the main thread.
This is common used to load a large bitmap on a separated thread, make math calculations to resize this large image and then, on the main thread, inflate/print/paint/show the smaller version of that image to te user.
In your case, I don't know how heavy runPE() method is, I don't know what it does, you could try to create another thread for him, but the rest should be on the main thread, it is the main process of your UI.
You could optmize your loop by placing the "ConsumerPrinter consumerPrinter = new ConsumerPrinter();" before the "for(...)", since it does not change dinamically, you can remove it inside the loop to avoid the creating of the same object each time the loop restarts : )
While straight java multi-threading can be used (java.util.concurrent) as other answers have discussed, consider also alternate programming approaches to multi-threading, such as the actor model. The actor model still uses threads underneath, but much complexity is handled by the actor framework rather than directly by you the programmer. In addition, there is less (or no) need to reason about synchronizing on shared state between threads because of the way programs using the actor model are created.
See Which Actor model library/framework for Java? for a discussion of popular actor model libraries.

Can JAI.create() be used in multiple threads?

I'm building a program based on the open source software JPiv, that is used to do digital image correlation and strain analysis. The algorithm in JPiv is, unfortunately, very slow, so I've been trying to use multithreading to decrease the time taken to analyse an image set. The algorithm uses JAI for something, not quite sure what as I've never used it before. When I run it, on the second 'pass', I get a OutOfMemory exception on at least one of the threads, and occasionally get other errors, seemingly at random, but usually IllegalArgument exceptions - sometimes from JAI, sometimes from standard Java libraries. The exceptions get thrown by different libraries at different points in the program, which makes it hard to debug - especially as they don't always give traceback messages in the console, for some reason.
I think the error is in the use of the JAI.create() method, and the way that the different threads access the corr[c] variable to use the above method. Is it possible to use JAI.create() in the way I'm trying to do so?
The code is quite lengthy, so I've put it on Pastebin here: http://pastebin.com/EX92YjXA
Below is a bit of pseudo-code to get a general sense of what I'm attempting.
public doPivEvaluation{
corr = new BufferedImage
start threads
send corr array to threads
loop until threads have finished
do stuff with corr}
public class threads{
on start{
do the analysis using tmpCorr
pb = new ParameterBlock()
pb.removeSources();
pb.removeParameters();
pb.addSource(PivEvaluation.corr[c]);
pb.addSource(tmpCorr);
PivEvaluation.corr[c] = JAI.create("add",pb,null).getAsBufferedImage();
end threads}
Uh, yeah, so maybe not the best pseudo-code ever, but yeah. The position in corr, c, is different for each thread (and refers to a set of pixels, so could be up to 5000 depending on the size of the image, split between the different threads), and corr has been declared volatile, so in theory there should be no overriding of data. Likewise, in theory, if JAI.create() only acts on that position, there should be no problem either. The problem arises because I don't understand how .create() actually works... I know the whole thing works in a single thread, because I've not changed anything of the actual algorithm, only moved it into multiple threads.
Also, apologies for any bad coding practices that may be in the code, I'm relatively new to Java still, so I'm more just muddling along. If I try something and it fixes a problem, I'm likely to go with it even it means multiple variable declarations or whatever other inefficiencies I've made. This is the first problem I've encountered I haven't been able to fix by guesswork and Google.

Categories

Resources