I'm designing a concurrent Java application that reads data from various medical devices available on the hospital Intranet.
I've read "Java concurrency in practice - Brian Goetz..." to understand how to do ... |
I am looking for a BoundedBlockingQueue that can take any other Queue and make it bounded and blocking.
I found akka.util.BoundedBlockingQueue which can do that, but the source code has some fixmes ... |
Can anyone tell me whether this class is threadsafe or not ?
class Foo {
private final Map<String,String> aMap;
public Foo() {
...
|
The following code snippet calculate prime factors of a given number:
public static LinkedList<Long> getPrimeFactors(Long number) {
LinkedList<Long> primeFactors = new LinkedList<Long>();
for (Long factor ...
|
I got a bunch of threads that perform calculations. They are "synchronized" using a CyclicBarrier. When any thread's run() method finishes, I want all other threads to exit as ... |
I have a queue that contains work items and I want to have multiple threads work in parallel on those items. When a work item is processed it may result in ... |
I'm learning Java concurrency and looking for interesting exercises and puzzles website (or other sources) to help me learn the API.
Thanks guys for the responses. I was more thinking that problems ... |
|
I want to implement a custom java barrier. I don't want to use the CyclicBarrier class.
So all threads meet at a common point. The threads only procceed if all ... |
I am creating a ScheduledExecutorService with the following code:
ScheduledExecutorService schedExe = Executors.newSingleThreadScheduledExecutor();
I am calling this thus:
ScheduledFuture<?> sf = schedExe.scheduleWithFixedDelay(new RequestScheduler(), 1, 1, TimeUnit.SECONDS);
The RequestScheduler() class, for testing purposes is a simple ... |
So, there is a concurrent hashmap in Java, the advantage of which is not to lock down the whole hash table, but only portions of it. I was wondering ... |
This question was asked two years ago, but the resources it mentions are either not very helpful (IMHO) or links are no longer valid.
There must be some good tutorials out ... |
I need to read a set of files and break it in to key-value pairs, and save these as a (key,list of values) for that key on disc, much like the ... |
I am interested in the lifecycle and concurrency semantics of (Rhino) Script Engine and associated classes. Specifically:
- Is
Bindings supposed to be thread safe?
- Should multiple threads be allowed to share a single ...
|
I'm in a typical situation where I have a group of worker actors that are being fed jobs from a queue. Worker failures can be either transient and due to ... |
So Java supports object level monitors.
So when we create an instance of a class basically we are creating different objects. Now, consider a scenario in which there is a shared ... |
Trying to make sense of how ConcurrentWeakKeyHashMap responds to memory condition/garbage collection.
With the code below in my JUnit test with maxNum == 6000,
the assert statements failed, with size ... |
Consider a third-party class like
class A {
private int value;
public int getValue() {
return value;
...
|
I am a Java newbie trying to learn network programming and concurrency, and I thought I'd try out writing a simple chat server where input from a client is echoed to ... |
For past year I have been working a lot on concurrency in Java and have build and worked on many concurrent packages. So in terms of development in the concurrent world, ... |
During the exam I had following question:
"What is a Java thread and how are multiple threads handled by a single
processor core?
[2 marks]
(a) Describe the two ways in which a class may ... |
How would I make a sort of console for my program without pausing my code? I have a loop, for example, that needs to stay running, but when I enter a ... |
This question relates to a very common problem that I haven't been able to find a conventional solution for.
Here is the setup:
- You have a number of consumers, each subscribing to ...
|
I stumbled across the source of AtomicInteger and realized that
new AtomicInteger(0).equals(new AtomicInteger(0))
equals false.
Why is this? Is it some "defensive" design choice related to concurrency issues? If so, what could go wrong ... |
I finished reading the first seven chapters of Java Concurrency in Practice. Can you give me any ideas of sample projects so that my ideas will become solidified ?
|
I want to implement a circular counter in Java.
The counter on each request should increment (atomically) and on reaching an upper limit should roll over to 0.
What would be the ... |
Given:
Executor executor = ...;
Phaser phaser = new Phaser(n);
for (int i=0; i<n; ++i)
{
Runnable task = new Runnable()
{
public void run()
{
...
|
I'm creating a reader application. The reader identifies based on the parameters which file to read, does some processing and returns the result to the caller.
I am trying to make this ... |
I'm working on a concurrency assignment that involves parallelizing a problem for performance. The problem involves a fair amount of blocking i/o so for my report I want to use and ... |
I have a HashMap and want to synchronize each row/entry separately in order to maximize concurrency, so in this way many threads can access the HashMap at the same time but ... |
I have a high volume application that reads in data from files, and then hits an internal API (local network) via a POST with X number of records from the current ... |
Where can I get the tool?
The links I searched from Google didn't point to the download page.
Also, the eclipse update site is not working.
|
I have a confusion. I read somewhere that Thread.yield() method causes the currently running thread to pause and give chance to remaining thread of "Same Priority".
Now always it is same priority ... |
I am making an application that will work much like a real time chat. A user will be constantly writing on lets say a text area and messages will be send ... |
Is there any good/great java example solutions on Reader Writer concurrency problem that you can recommend, or you can write and paste here?
I am particularly interested in the ... |
|
|
|
Think of it this way, If you have two blind cooks in the kitchen. One wants to make a chocolate cake, the other wants to make tuna fish casserole. But you only have one mixing bowl. Cake cook will break two eggs into the bowl, put a cup of sugar in, and then turn to get the flour. In the meantime, ... |
It depends where you put the code that starts the thread pool, and where you store the reference to that pool. If you use a static variable and static initializer, then the entire application is using the same thread pool. If it's an instance variable initialized in a constructor, then each instance has a different pool. If you use a local ... |
|
|
A - The output can never contain the value 10. B - The output can never contain the value 30. C - The output can never contain the value 297. D - The output can never contain the value 1020. E - The output can never contain the value 1130. They give 5 differents possibles answers, the correct is E ... ... |
If the constructor lets a "this" reference escape, that's a problem, true. However that doesn't happen in the Holder code above - and yet it's still possible for assertSanity() to fail. [Satya]: Could you please elaborate a bit more on this? Did you mean that another thread calls assertSanity() on an instance of 'Holder' while the original thread is still in ... |
Hi, I've got the following newbie question about concurrency control. I just need someone to confirm that my reasoning is correct for the following scenario. Local variables declared within methods are thread-safe and don't impose any problems when multiple threads accessing the same instance of an object. Now I've declared and instantiated a ValueListHandler object within a method which is a ... |
|
|
The concurrency utilities are actually the most important part of the Tiger multithreading support. In a previous posting I had a three-part strategy to access shared data from multiple threads: 1) Avoid the problem by using a thread-safe collection 2) Use synchronization (synchronized keyword or Lock/Condition) 3) Use volatile The concurrency utilities provide the support for the first option. For example, ... |
hi! i'm a java newbie and i've been tasked to create this web application. my question is what's good way / strategy to implement data concurrency? for data concurrency, my officemate suggested this design : if user A is editing a record in the table then that record should be locked from other users. A class, called UserAccessRightsManager, will supervise all ... |
During the course of learning the new API; I undestood that the new java.util.CopyOnWriteArrayList creates a new copy of the underlying array for writing thereby disposing off synchronization. My question is how does this affect memory management in a situation where there are many concurrent writes to be done; I guess it is going to create this many copies of the ... |
|
Hi Anselm - There's a big old API out there and we did our best to decide which parts of it would be best to explore in an "intro to Java and OO" book. The fact that we left it out doesn't imply that we think it's not important! Hmmm... I guess the short answer is, we left it out. - ... |
Hello everybody. I'm studying JDOM API now and such a question has appeared in my mind. Id JDOM API thread safe? For instance, if i use it in a web-application, to read some properties from and xml file (something like web.xml)...won't i have problems if 3-4 people try to access the file at the same time? What about the writing to ... |
Hello, Below is an example in Bruce Eckel's book Thinking in Java. Don't let the number of lines scare you away, it's actually pretty straightforward. For improved readability, you can just paste it in your IDE if you want to, it's a single file with no dependencies. I've added a few comments here and there for my (and your) convenience. What ... |
import java.io.*; import java.util.Arrays; class grades { public static void main(String[]args) throws java.io.IOException { //variable int i; String name; double x = 0, y, z; //input InputStreamReader isr = new InputStreamReader(System.in); BufferedReader br = new BufferedReader(isr); //declare array String names[]; //allocate array names = new String[4]; //master grades array String gradesmaster[]; //allocate master array gradesmaster= new String[4]; //declair 2 array double ... |
I'm trying to find clarification, not nitpick. I keep reading that java doesn't have "true" Monitors because 1) no explicit queues 2) compiler can't assure that all fields capable of being accessed by multiple threads are protected by monitors but I'm trying to nail down the dates for these statements and it is very hard to know which version they are ... |
Yes, the synchronized keyword is implemented to support the priority inheritance protocol, which is a way to avoid priority inversion which can lead to unbounded latency for high-priority threads due to shared locks with lower priority threads. Chapter 1 goes into the priority inversion problem, and there is an entire chapter on Synchronization in Java RTS. |
|
|
Goodmorning Java enthausiasts I am studying for my SJCA certificate, and I am looking for far better educational learning resources on Java Multithreading / Concurrency that the stuff from the Sun Microsystems website @ http://java.sun.com/docs/books/tutorial/essential/concurrency/index.html Most of the (online avialable) 'educational" material jump DEEP right into the matter, without covering the simple thread basics first with crystal clear examples + graphics ... |
Hi. I'm working my way through head first java. In chapter 15 they talk about using "synchronized" on a method and have an example in their book (copied in below). The example works perfectly on my linux machine but on my snow leopard machine running 1.6.0_20 java the synchronized keyword seems to be ignored. Anyone? Is there a setup issue I ... |
public class Cruiser implements Runnable { public static void main(String[] args) throws InterruptedException { Thread a = new Thread(new Cruiser()); a.start(); System.out.print("Begin"); a.join(); System.out.print("End"); } public void run() { System.out.print("Run"); } } A) Compilation fails. B) An exception is thrown at runtime. C) "BeginRunEnd" is printed. D) "BeginEndRun" is printed. E) "BeginEnd" is printed. The correct answer is C, but i ... |
Greetings Gentlemen! (and Ladies, if any found) Here is a set of questions which resulted from my on-going effort to study java concurrency. Please help if possible. 0) Imagine we have 2 banking accounts and we need to transfer money between them in a thread-safe way. i.e. accountA.money += transferSum; accountB.money -= transferSum; 2 requirements exist: 1. no one should be ... |
I've got a XML which is being accessed by two different java applications simultaneously. I need to ensure that concurrent access is not granted to the two applications, i.e one application can't read or write before the other has finished working with the XML. Upon completion of read/write operation, one application needs to have a mechanism to signal the other application ... |
in concurrency utilities we use "Semaphore" how the semaphore work?? we assign the values of permit in "Semaphore(value) constructor, how the permit work??? How the semaphore work in this code??? // An implementation of a producer and consumer // that use semaphores to control synchronization. import java.util.concurrent.Semaphore; class Q { int n; // Start with consumer semaphore unavailable. static Semaphore semCon ... |
Not it is not a replacement, but rather an extension of well known mechanisms such as wait/notify, intrinstic locks and so on. These utilities provide high-level abstractions (e.g. semaphores, latches, barriers) on the one hand and completely new concepts (e.g. Locks, Atomic objects) on the other hand. It makes no sense to explain you details of these packages because if you ... |
Hi Experts, I want a separate class that would manage thread creation.. also, Main class will take a parameter that is how many threads can run in parallel if I have 10 objects but 4 threads then 5th one should start only after one of the first 4 is complete.. and so on. Can anybody help me ..how to implement such ... |
This is one of those generic "looking for things to do" questions. I am currently reading Java Concurrency in Practice, and I am liking it, however; I am not sure of any good exercises to get some real practice. Does anyone know of any good exercises from moderate difficulty + to use for learning threading in a practical sense? Right now, ... |
I have two threads on a server that want to send the name of a username that has logged on to the client. Know they both have access to this username they send it over to their individual clients. on the clients side how can i implenent a method that continuously listens for contacts signing in?? What Thread Concurrency techinques should ... |
Surely this is going to encounter the same problem. I am now using a linked list called PageLinks with an iterator as so: ListIterator itPageLinks = PageLinks.listIterator (); while (itPageLinks.hasNext ()) { s = (String) itPageLinks.next (); t = valPage (s); if (PAGE_VAL_COUNT_ACHIEVED == PAGE_VAL_COUNT_NEEDED) // Can non-root page be checked for links. { getPageLinks (t); } PAGE_VAL_COUNT_ACHIEVED = 0; } ... |
Hi, thanks for replying (this post is obviously too long for anyone to even read it). Maybe it's just me, but I don't think the solution is "elegant" - it could be simpler. The problem is that I cannot think of any other way. Do you maybe have a suggestion? Or do you think I should just leave it at that? ... |
First of all synchronizing the run method is (and I don't mean to be mean, but) idiotic. Why have threads then? Second of all, a "synchronized method" synchronises on the instance in which it is called (i.e. synchronised(this)). Since you create two different instances of the class, the two instances do not interfere/synchronise with each other. |
I'm building an agent program with a number of classes that each require the user to input information at the command line (not with args, but using Scanner(System.in)). I've only just now realised that running two of these agents simultaneously will result in them both using the same input. Is there any way to allocate separate channels, or to allocate a ... |
|
|
jabajaba wrote: I can't even specify which line to start in the file. I really need to break these guys up into multiple threads so the parser can complete quicker You need to specify the problem more completely. First is each line a discrete component? Does it rely on nothing before or after it? If yes.... If you have a file ... |
|
Hello. I have a question regarding threads and Data structures working together. I have the following classes: Queue. Stack. Producer Implements Runnable: Places objects randomly in queue/stack in time intervals. Consumer Implements Runnable (got 5 consumers for example): Chooses to take objects from the Queue or the Stack by round robin method or whether they are empty and one of them ... |
This is the functionality. Now i have to perform these steps from two different threads in parallel with different parameters. If i call these steps from two different Threads, then how it works. How can i implement that functionality. So that , Two Different Threads call the same function ie,Func1(). How this function works with two Different Threads. Please explain with ... |
One comment on +jToohey+'s reply: you definitely want to throw a Thread.interrupt() in the setStopRequested(), otherwise you'll stay asleep. The tricky part is what thread you're interrupting: you have to store the thread at the start of run(). Alternatively (my preference), you could replace the sleep() with a wait(timeout), and use notifyAll() in setStopRequested(). |
|
class Waiting2 implements Runnable { 4. int state; 5. public synchronized void run() { 6. if (state++ < 3) { 7. System.out.print(" " + Thread.currentThread().getId()); 8. try { this.wait(); } catch (Exception e) { } 9. System.out.print(" " + Thread.currentThread().getId()); 10. } 11. else { 12. try { Thread.sleep(2000); } catch (Exception e) { } 13. notify(); 14. notifyAll(); 15. } ... |
If all your threads are doing is storing a value in a map, then why do you want to use multiple threads anyway? If the system can get it done without using multiple threads, then let it. Like you said, if the tasks take longer, it uses multiple threads, but if it doesn't need to, don't worry about it. |
Recenlty it hit some problem where some data are missing in the database. After i see the console log i found this log for example 1. the program send Vector contains of 3 messages. 2 for each item in the vector it will call some other method and finally insert into A(trans_id_m , etc ) values ( sequence , etc ) ... |
Do you mean you think you might have concurrency issues--accessing files at the same time, or whatever? I think either one will work. But, the method version makes more sense, because with the method, you aren't constructing new Objects (DeleteFile instances) for each recursion. Also, since you aren't accessing anything within the DeleteFile instance (no instance variables or methods), you could ... |
I have a situation similar to the following code where m_array and m_link must be guaranteed to be synchronized. Init will get called by different threads so what is the best way to avoid the deadlock? public class Foo { private final ReentrantLock m_lock = new ReentrantLock(); private final ArrayList m_array = new ArrayList(); private final LinkedList m_list = new LinkedList(); ... |
I read few articles about Java Threads but I am confused over one issue. If I spawn a new thread (say "user thread") from my Main thread in which conditions will the Main thread wait for the user thread to complete the execution to exit the system? My understanding was, once the user thread is spawned, Main thread will go ahead ... |