MultipleThread 1 « concurrency « Java Thread Q&A

Home
Java Thread Q&A
1.concurrency
2.Development
3.Exception
4.Notify
5.Operation
6.Socket
7.State
8.synchronize
9.Thread Safe
10.ThreadPool
Java Thread Q&A » concurrency » MultipleThread 1 

1. Wait until any of Future is done    stackoverflow.com

I have few asynchronous tasks running and I need to wait until at least one of them is finished (in the future probably I'll need to wait util M out of ...

2. How to implement simple threading in Java    stackoverflow.com

I'm looking for the simplest, most straightforward way to implement the following:

  • The main program instantiates worker threads to do a task.
  • Only n tasks can be running at once.
  • When n is reached, no ...

3. How can I wrap a method so that I can kill its execution if it exceeds a specified timeout?    stackoverflow.com

I have a method that I would like to call. However, I'm looking for a clean, simple way to kill it or force it to return if it is taking ...

4. comparison of code performance, threaded versus non-threaded    stackoverflow.com

I have some thread-related questions, assuming the following code. Please ignore the possible inefficiency of the code, I'm only interested in the thread part.

//code without thread use
public static int getNextPrime(int ...

5. When would you call java's thread.run() instead of thread.start()?    stackoverflow.com

... the question says it all I believe!

6. What is the most frequent concurrency issue you've encountered in Java?    stackoverflow.com

This is a poll of sorts about common concurrency problems in Java. An example might be the classic deadlock or race condition or perhaps EDT threading bugs in Swing. ...

7. Is it possible to wait for methods that aren't in Threads to finish in Java?    stackoverflow.com

I have an object which does some computation, then for each iteraction I want to draw what happens. While the drawing is happening, I want it to wait. This is what I ...

8. Alternative for volatiles with cheapest performance hit    stackoverflow.com

I want to implement the usual cooperative mechanism for canceling a thread. However the java memory model was only fixed in JDK5 while I'm in a pre-JDK5 environment. I understand, this means that ...

9. Attach UncaughtExceptionHandler to a TimerTask    stackoverflow.com

Is it possible to attach an UncaughtExceptionHandler to a TimerTask? (Other than by calling Thread.setDefaultUncaughtExceptionHandler()) Cheers Rich

10. Using Object.wait(millisec) to simulate sleep    stackoverflow.com

Here's a snippet of code that I saw in some code I'm maintaining.

Object lock = new Object();

synchronized( lock ) 
{
   try
   {
      ...

11. Looking for Modern Java Threading / Concurrent programming Book    stackoverflow.com

I'm looking for a modern java threading book. I've quite enjoyed reading Taming Java Threads by Allen Holub, but it's a little old now. That was 8 years ago. I want ...

12. Any suggestions for a program or small project to learn about concurrency in Java?    stackoverflow.com

I'm aiming to learn about concurrency in Java. Currently my state of knowledge is poor. I'm pretty sure I know what "volatile" means. I sort of know what ...

13. What is the reasoning behind the double call to WeakHashMap.put( .. )?    stackoverflow.com

This blog post demonstrates a way to implement a mutex per string id idiom. The String ids used are to represent HttpSession ids.

  1. Why do we need to wrap a ...

14. Restore of data replicated with erasure-coding    stackoverflow.com

I need your help on the design of the restore-procedure in a backup system I'm building. The prerequisites are the following:

  • A restore can be made of one or several files.
  • A ...

15. Why is swallowing InterruptedException ok for subclasses of Thread?    stackoverflow.com

In Brian Goetz's article on how to handle InterruptedException, one paragraph stands out:

The one time it's acceptable to swallow an interrupt is when you know the thread ...

16. Make it pretty: processing an array concurrently    stackoverflow.com

I want to convert this linear loop into a concurrent one:

for(Item item : ItemList) {
    processItem(item);
}
Is this really the shortest way to do this?
class Worker implements Runnable {
 ...

17. Where can I find some good examples to learn the basics of threading?    stackoverflow.com

I am at the end of my first year doing computer science and want to mess around with something basic. I want to use threads so I can learn. What are some ...

18. Converse of java FileDescriptor .sync() for *reading* files    stackoverflow.com

Reading the javadoc on FileDesciptor's .sync() method, it is apparent that sync() is primarily concerned with committing any modified buffers back to the underlying storage. I.e., making sure that anything that ...

19. Why was the method java.lang.Thread.join() named like that?    stackoverflow.com

Does anybody know why the method join() member of a java.lang.Thread was named like that? Its javadoc is:

Waits for this thread to die.
When join is called on some thread ...

20. Will using multiple threads with a RandomAccessFile help performance?    stackoverflow.com

I am working on a (database-ish) project, where data is stored in a flat file. For reading/writing I'm using the RandomAccessFile class. Will I gain anything from multithreading, and giving each ...

21. completionservice: how to kill all threads and return result through 5 seconds?    stackoverflow.com

I have some problem with CompletionService. My task: to parse parallely for about 300 html pages, i need to wait for all the results only for 5 seconds, then - return ...

22. Looking for a framework that handles cancellation of HTTP Callables    stackoverflow.com

I will be making multiple HTTP calls concurrently and want to allow the user to selectively cancel certain tasks if they take too long. A typical scenario: 1 task pulls twitter ...

23. What's Java's equivalent of .Net's Interlocked class?    stackoverflow.com

How do I modify an int atomically and thread-safely in Java? Atomically increment, test & set, etc...?

24. How do I optimize for multi-core and multi-CPU computers in Java?    stackoverflow.com

I'm writing a Java program which uses a lot of CPU because of the nature of what it does. However, lots of it can run in parallel. When I run ...

25. Best ways to handle maximum execution time for threads (in Java)    stackoverflow.com

So, I'm curious. How do you handle setting maximum execution time for threads? When running in a thread pool? I have several techniques but, I'm never quite satisfied with them. So, I ...

26. Does AtomicBoolean not have a negate() method?    stackoverflow.com

Does java.util.concurrent.atomic.AtomicBoolean not have a method that can atomically negate/invert the value? Can I do it another way? Am I missing something?

27. What are the differences between these two ways of starting threads?    stackoverflow.com

If I have a class that implements the Runnable interface, what are the differences between these statements in the main method?

MyThread t1 = new MyThread();
t1.start();
and
MyThread t2 = new MyThread();
new Thread(t2).start();

28. Java Queue implementations, which one?    stackoverflow.com

From javadoc:

  • A ConcurrentLinkedQueue is an appropriate choice when many threads will share access to a common collection. This queue does not permit null elements.
  • ArrayBlockingQueue is a classic "bounded buffer", in which ...

29. How can I atomically "enqueue if free space OR dequeue then enqueue" for a Java queue / list?    stackoverflow.com

I've got a requirement for a list in Java with a fixed capacity but which always allows threads to add items to the start. If it's full it should remove ...

30. Analysing Thread behaviour in Java    stackoverflow.com

I need to draw a graph of write accesses of two concurrently running threads. What is the best way to write a timestamp value pair of these accesses to an array, ...

31. Need a queue that can support multiple readers    stackoverflow.com

I need a queue that can be processed by multiple readers. The readers will dequeue an element and send it to a REST service. What's important to note are:

  • Each reader should be dequeueing ...

32. LinkedBlockingQueue vs ConcurrentLinkedQueue    stackoverflow.com

My question relates to this question asked earlier. In situations where I am using a queue for communication between producer and consumer threads would people generally recommend using LinkedBlockingQueue ...

33. Can I invoke XMPPConnection.sendPacket from concurrent threads?    stackoverflow.com

Motivation I want extra eyes to confirm that I am able to call this method XMPPConnection.sendPacket( Packet ) concurrently. For my current code, I am invoking a List of Callables (max 3) ...

34. Java multithreading reading a single large file    stackoverflow.com

What is an efficient way for a Java multithreaded application where many threads have to read the exact same file (> 1GB in size) and expose it as an input stream? ...

35. How to design a system that queues requests & processes them in batches?    stackoverflow.com

I have at my disposal a REST service that accepts a JSON array of image urls, and will return scaled thumbnails. Problem I want to batch up image URLs sent by concurrent ...

36. Flexible CountDownLatch?    stackoverflow.com

I have encountered a problem twice now whereby a producer thread produces N work items, submits them to an ExecutorService and then needs to wait until all N items have been ...

37. bug thread handling in java    stackoverflow.com

public class Test extends Thread{
    public void hello(String s){
     System.out.println(s);
    }
    public void run(){
     ...

38. java.util.concurrent vs. Boost Threads library    stackoverflow.com

How does the Boost Thread libraries compare against the java.util.concurrent libraries? Performance is critical and so I would prefer to stay with C++ (although Java is a lot faster these days). Given ...

39. Java: How to use Thread.join    stackoverflow.com

I'm new to threads. How can I get t.join to work, whereby the thread calling it waits until t is done executing? This code would just freeze the program, because the ...

40. setContextClassLoader slows down drastically when called concurrently    stackoverflow.com

I have pin pointed a bottle neck in my application, it seems to me that it boils down to a call to Thread::setContextClassLoader. Basically I was forced to mess around ...

41. concurrent handling of java.nio.channels.Selector    stackoverflow.com

i'm working with java.nio.channels.Selector and i'd like to create a separate thread for each selectedKey that is ready for read/write/accept but i want to make sure that the same socket is ...

42. Strategies for concurrent pipelines in Java    stackoverflow.com

Consider the following shell script:

gzip -dc in.gz | sed -e 's/@/_at_/g' | gzip -c > out.gz 
This has three processes working in parallel to decompress a stream, modify it, and re-compress ...

43. java.util.concurrent : calculating primes    stackoverflow.com

I'm new to the package java.util.concurrent. I've created the following program testing if a number is a prime using a multi and a monothreaded strategy.

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;


public class IsPrime
 ...

44. How to deal with Concurrency before you start coding    stackoverflow.com

I'm midway through programming a Java program, and I'm at the stage where I'm debugging far more concurrency issues than I'd like to be dealing with. I have to ask: how do ...

45. Return values from Java Threads    stackoverflow.com

I have a Java Thread like the following:

   public class MyThread extends Thread {
        MyService service;
       ...

46. How to learn about Threads, Especially in Java    stackoverflow.com

I have always been kind of confused by threads, and my class right now makes heavy use of them. We are using java.util.concurrent but I don't even really get the basics. ...

47. Run java thread at specific times    stackoverflow.com

I have a web application that synchronizes with a central database four times per hour. The process usually takes 2 minutes. I would like to run this process as ...

48. How do I get the java.concurrency.CyclicBarrier to work as expected    stackoverflow.com

I am writing code that will spawn two thread and then wait for them to sync up using the CyclicBarrier class. Problem is that the cyclic barrier isn't working as expected ...

49. Multi:Threading - Is this the right approach?    stackoverflow.com

Experts - I need some advice in the following scenario. I have a configuration file with a list of tasks. Each task can have zero, one or more dependencies. I wanted to ...

50. Why do threads spontaneously awake from wait()?    stackoverflow.com

I was wondering why threads spontaneously awake from wait() in java.
Is it a design decision? Is it a compromise? EDIT: (from Java Concurrency in Practice, p. 300)

wait is even allowed ...

51. What is your development checklist for Java low-latency application?    stackoverflow.com

I would like to create comprehensive checklist for Java low latency application. Can you add your checklist here? Here is my list
1. Make your objects immutable
2. Try to reduce synchronized method
3. Locking ...

52. java -> System.gc(); Does this call opens a new Thread or not?    stackoverflow.com

For example I such a code ... get some memory and lose all the pointers to that memory so that System.gc(); can collect it. call System.gc(); do some other tasks;


Here does the "do some other ...

53. What is the difference between Thread.start() and Thread.run()?    stackoverflow.com

Why do we call the start() method, which in turn calls the run() method?
Can't we directly make a call to run()? Please give an example where there is a ...

54. Java - Multithreading !    stackoverflow.com

What does phrase "synchronization with main memory" mean?

55. Suggest a open source project which heavily uses java concurrency utilities?    stackoverflow.com

I have done good amount of Java programming, but yet to master Threading & Concurrency. I would like to become an expert programmer in threading & concurrency. I have also ...

56. How to maintain a pool of names?    stackoverflow.com

I need to maintain a list of userids (proxy accounts) which will be dished out to multithreaded clients. Basically the clients will use the userids to perform actions; but for this ...

57. Is there a JVM aimed at debugging concurrent software?    stackoverflow.com

I've used Concurrent Pascal, a tool which helps debug concurrent algorithms because when it runs your code, it randomizes which thread to swap to at every possible step, trying out as ...

58. Keeping track of threads when creating them recursively    stackoverflow.com

I'm currently working on some code for a course. I can't post the code but I'm permitted to talk about some high level concepts that I'm struggling with and receive input ...

59. Is it a good idea to start a thread from its own constructor?    stackoverflow.com

Can we call thread_object.start() from within a constructor of this same object? Is this approach a good idea ?

60. Multhreading in Java    stackoverflow.com

I'm working with core java and IBM Websphere MQ 6.0. We have a standalone module say DBcomponent that hits the database and fetches a resultset based on the runtime query. The ...

61. What is the JVM Scheduling algorithm?    stackoverflow.com

I am really curious about how does the JVM work with threads ! In my searches in internet, I found some material about RTSJ, but I don't know if it's the right ...

62. Can I query DOM Document with xpath expression from multiple threads safely?    stackoverflow.com

I plan to use dom4j DOM Document as a static cache in an application where multiples threads can query the document. Taking into the account that the document itself will never ...

63. How to end a thread in java?    stackoverflow.com

I have 2 pools of threads

ioThreads = (ThreadPoolExecutor)Executors.newCachedThreadPool();

cpuThreads = (ThreadPoolExecutor)Executors.newFixedThreadPool(numCpus);
I have a simple web crawler that I want to create an iothread, pass it a url, it will then fetch ...

64. Please suggest good book/website to for Threads and Concurrency?    stackoverflow.com

I have gone through Head First Java and some other sites but I couldn't find complete stuff related to Threads and additional concurrency packages at one place. Please suggest a book/website which ...

65. Why does java.util.concurrent.ArrayBlockingQueue use 'while' loops instead of 'if' around calls to await()?    stackoverflow.com

I have been playing with my own version of this, using 'if', and all seems to be working fine. Of course this will break down horribly if signalAll() is used ...

66. Why doesn't this thread example work? It all wait()'s    stackoverflow.com

The code below is to emulate a robotics simulator I'm working with. I'm not entirely sure why this doesn't work - I'm not very familiar with threads and even though I've ...

67. ThreadFactory usage in Java    stackoverflow.com

Can someone briefly explain on HOW and WHEN to use a ThreadFactory? An example with and without using ThreadFactory might be really helpful to understand the differences. Thanks!

69. How to give name to a callable Thread?    stackoverflow.com

I am executing a Callable Object using ExecutorService thread pool. I want to give a name to this thread. To be more specific, in older version I did this -

Thread thread = ...

70. A concurrent issue among threads    stackoverflow.com

Suppose I have a instance variable that has original value:

Integer mMyInt = 1;
There are two threads. The first changes mMyInt by calling:
void setInt() {
    mMyInt = 2;
}
The second thread ...

71. Multiple threads vs single thread    stackoverflow.com

I am working on a server client application right now (just for learning purposes), and am trying to get information to make a design decision regarding threads in this application. Currently i ...

72. Java: Is `while (true) { ... }` loop in a thread bad? What's the alternative?    stackoverflow.com

Is while (true) { ... } loop in threads bad? What's the alternative? Update; what I'm trying to to... I have ~10,000 threads, each consuming messages from their private queues. I have one ...

73. Make asynchronous queries synchronous    stackoverflow.com

I have an underlying asynchronous out-of-order query/response system that I want to make synchronous. Queries and responses can be mapped by marking the queries with unique IDs that in turn will ...

74. Java : threaded serial port read with Java.util.concurrent thread access    stackoverflow.com

I'm trying to write a Java serial device driver and want to use the (new to me) java.util.concurrent package. I have one method which sends a packet then waits for ...

75. Are 64 bit assignments in Java atomic on a 32 bit machine?    stackoverflow.com

If I have code like this -

long x;
x  = 0xFFFFFFFFL;

If i run this code on a 32 bit machine is it guaranteed to be atomic or is it possible that ...

76. concurrent programming in java    stackoverflow.com

I have 2 threads running in paralel. The run function of the threads is as follows

public void run(){
    Runtime rt = Runtime.getRuntime();
    Process s;
  ...

77. getting inconsistent/wrong output in the program Multi -Threading java    stackoverflow.com

/*
This should always produce 0 as output since all three methods increment(), decrement(), value()  are thread safe(synchronized).  but it is returning 1
*/

class Counter implements Runnable {
    ...

78. Memory Consistency Errors vs Thread interference    stackoverflow.com

What is the difference between memory consistency errors and thread interference? How does the use of synchronization to avoid them differ or not? Please illustrate with an example. I couldn't get this ...

79. Cannot get my head around concurrency in java, tried reading from the recommended books    stackoverflow.com

OK I am not only new to concurrency in java but am also fairly new to java programming. I tried understanding concurrency from The java tutorials, tried reading Concurrency in ...

80. What's going on in this program, and, more importantly, why?    stackoverflow.com

Please help me understand this program's execution and what concepts apply here in the larger sense? An illustration which explains thread(s)/stack(s) creations and destruction would be helpful.

class Joining {

  ...

81. Terminate unresponsive thread    stackoverflow.com

I have built a java application and have a thread thats doing something in the background when a button was pressed. The problem is, that thread might lock up, perhaps due ...

82. Do java threads get deleted when they finish    stackoverflow.com

Say I spawn a thread every couple seconds using the method below and every thread takes about a second to complete. Do the finished threads get deleted?

new Thread (new myRunnableClass()).start();

83. Making threads wait    stackoverflow.com

I have a bit of a problem. I have a java application and when it starts it needs to make around six maybe seven threads that just wait for some sort ...

84. How would I make a thread join on another thread but only wait for n seconds of CPU time?    stackoverflow.com

otherThread.join( time ) appears to wait time in real milliseconds. I want to wait time in actual CPU time so that I can get consistent behavior within my application. I've done ...

85. Breakdown of Threads used by a JApplet    stackoverflow.com

I've been spending a great deal of time trying to understand this. I created a JApplet that used Thread.sleep() in a loop to animate the applet. But when I ...

86. How do I get JUnit to be consistent when timing out?    stackoverflow.com

JUnit @Tests have the useful ability to specify a timeout argument so that a poorly written program gets killed automatically if it takes longer than timeout seconds. The problem is this ...

87. Java: How to wait for fileChanged to execute?    stackoverflow.com

I'd like to have my thread (the main/EDT) wait until changes to a file occur and then wait. DefaultFileMonitor extends Runnable and hence runs in a thread of its own. Here ...

88. Close a socket when all pending messages have been sent    stackoverflow.com

I have this method to write messages to a socket:

public void sendMessage(byte[] msgB) {
    try {
        synchronized (writeLock) {
   ...

89. Which is more efficient and why?    stackoverflow.com

Out of the below two synchronization strategy, which one is optimized (as in processing and generated byte code) and also the scenario in which one should use one of them.

public synchronized ...

90. java.util.concurrent , examples, tutorial and code    stackoverflow.com

I've been ask to build a multithreaded java application using the java.util.concurrent. I'm not familiar with this library, but have a good understanding of problems with multi-threaded code. I'm looking for tutorial ...

91. Which way is the best to run a thread in java?    stackoverflow.com

Possible Duplicate:
Java: “implements Runnable” vs. “extends Thread”
Should I use Runnable interface or extends from Thread class? Is there any advantage on one and another? Thanks ...

92. Why is Java Future.get(timeout) Not Reliable?    stackoverflow.com

Future.get(timeout) does not reliably throw the TimeoutException after the given timeout. Is this normal behavior or can I do something to make this more reliable? This test fails on my machine. ...

93. Java Threads: Figure out which threads are still running    stackoverflow.com

For debugging purposes, I want to figure out which threads of my program are still running. There's seems to be one or more threads that accidentally were not interrupted. Some sort ...

94. Make simultaneous web requests in Java    stackoverflow.com

Could someone point me to snippet for making parallel web-requests? I need to make 6 web requests and concatenate the HTML result. Is there a quick way to accomplish this or do ...

95. Good book for beginning concurrency/multithreading/parallelization?    stackoverflow.com

What is a good book for learning the basics of concurrency? I've never programmed in a multithreaded environment, so it should assume no prior experience in writing multithreaded programs whatsoever. Should ...

96. Create table class as a singleton    stackoverflow.com

I got a class that I use as a table. This class got an array of 16 row classes. These row classes all have 6 double variables. The values of these rows are set ...

97. Java Concurrency using Limited Threads    stackoverflow.com

Greetings Overflowers,

  • The data structure is an acyclic tree of arbitrary number of nodes.
  • Shallower nodes are dependent on the results of deeper nodes.
  • The final result can simply be calculated by traversing the tree recursively.
  • If I had ...

98. How would you check which thread is executing code in Java?    stackoverflow.com

I have a multi-threaded Java program with a bunch of rules around threading: For example, code in class A should only be called from the UI thread; 3 ...

99. Shuffling array in multiple threads    stackoverflow.com

I have an array of size N. I want to shuffle its elements in 2 threads (or more). Each thread should work with it's own part of the array. Lets say, the ...

100. Threaded implementation of Quick Sort - ConcurrentQSort    stackoverflow.com

Below is implementation of QuickSort by using interface, I need some tips how I can implement by using threading/concurrency. i. Write one of the sort() methods so that it provides an implementation that ...

java2s.com  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.