0

Go offers both unbuffered and buffered channels for communication among goroutines (threads). It is straightforward to implement buffered channels as bounded buffers in Java.

Go's unbuffered channels require one goroutine to be sending when the other goroutine is receiving. Can anyone explain to me how to implement that in Java?

Ellen Spertus
  • 6,576
  • 9
  • 50
  • 101
  • I think you mean SynchronousQueue which passes from one thread to another without buffering. Generally you are better off starting with Parallel Streams to use multiple threads if you can in Java 8. – Peter Lawrey Apr 24 '17 at 19:29
  • 1
    @PeterLawrey Thanks. My interest is academic. I don't want to use the queue -- I want to understand how it's implemented. Now that you've given me the right terminology, I'll look it up. – Ellen Spertus Apr 24 '17 at 19:37
  • You should be able to read it's source. Note: a synchronous queue is pretty simple as it doesn't store anything. – Peter Lawrey Apr 24 '17 at 19:40
  • @PeterLawrey I know you already have plenty of reputation, but would you like to give the answer? http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/util/concurrent/SynchronousQueue.java – Ellen Spertus Apr 24 '17 at 19:50

2 Answers2

1

In Java you can use a SynchronousQueue, the source for Java 8 is here

http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8u40-b25/java/util/concurrent/SynchronousQueue.java?av=f

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
0

I suggest you also look into the JCSP library. There are further details of JCSP in this answer.

Java does not have anything that is equivalent to Goroutines, alas. (Once, there were 'Green Threads' long ago, but they were abandoned). So if you use threads instead, you will endure a heavy memory footprint as soon as the number of threads starts getting interesting (e.g. more than ten thousand). Every Java thread requires an operating system thread and a large stack space.

Community
  • 1
  • 1
Rick-777
  • 9,714
  • 5
  • 34
  • 50