Java ThreadFactory with Queue - java

I am trying to write and read from ArrayBlockingQueue via threads. I have thread factory and worker threads but for some reason I cannot read the data that I pass to to worker threads, within the worker threads. Any idea? Thanks.
public class CommunicationThreadFactory implements ThreadFactory {
#Override
public Thread newThread(Runnable runnable){
Thread thread=new Thread(runnable);
return thread;
}
}
public class ThreadEx implements Runnable {
private byte[] pack;
private final BlockingQueue writeBlockingQueue;
public Writer(BlockingQueue writeBlockingQueue, byte[] pack) {
this.writeBlockingQueue = writeBlockingQueue;
this.pack = pack;
}
#Override
public void run() {
TimeUnit.SECONDS.sleep(1);//Even this line block it wont process below this line. Even after time out.
writeBlockingQueue.put(pack);//Tried even with disabling put and takes from queue. still did not work
System.out.println("In Thread "+Thread.currentThread().getName() +" got "+ this.pack.length);// This line does not even produce output.
writeBlockingQueue.take();
}
}
public static void main(String[] args) throws UnsupportedEncodingException {
ExecutorService connectionThreadPool = Executors.newFixedThreadPool(15,new
CommunicationThreadFactory());
BlockingQueue<byte[]> blockingQueue = new ArrayBlockingQueue<>(10, true);
byte[] packet = new byte[]{0x63, 0x41, 0x35, 0x19};
for (int i = 0; i < 10; i++) {
connectionThreadPool.execute(new ThreadEx());
}
}

Your code does not compile. After correcting some synax errors, it works fine.
import java.io.UnsupportedEncodingException;
import java.util.concurrent.*;
class CommunicationThreadFactory implements ThreadFactory {
#Override
public Thread newThread(Runnable runnable) {
Thread thread = new Thread(runnable);
return thread;
}
}
public class ThreadEx implements Runnable {
private byte[] pack;
private final BlockingQueue writeBlockingQueue;
public ThreadEx(BlockingQueue writeBlockingQueue, byte[] pack) {
this.writeBlockingQueue = writeBlockingQueue;
this.pack = pack;
}
#Override
public void run() {
try {
TimeUnit.SECONDS.sleep(1);
writeBlockingQueue.put(pack);
// This line does not even produce output.
System.out.println("In Thread " + Thread.currentThread().getName() + " got "
+ this.pack.length);
writeBlockingQueue.take();
} catch (Exception e) {
}
}
public static void main(String[] args) throws UnsupportedEncodingException {
ExecutorService connectionThreadPool = Executors.newFixedThreadPool(15, new
CommunicationThreadFactory());
BlockingQueue<byte[]> blockingQueue = new ArrayBlockingQueue<>(10, true);
byte[] packet = new byte[]{0x63, 0x41, 0x35, 0x19};
for (int i = 0; i < 10; i++) {
connectionThreadPool.execute(new ThreadEx(blockingQueue, packet));
}
}
}

Related

how to use agrona.OneToOneRingBuffer

I just want to test agrona.OneToOneRingBuffer. i have one Producer to produce message,one Consumer to consume.But My consumer class has no output because countdownlatch doesn't zero out.
public class Producer implements Runnable{
private final RingBuffer buffer;
public Producer(RingBuffer buffer) {
this.buffer = buffer;
}
#Override
public void run() {
for(int i=0;i<Config.SIZE;i++){
String s = String.format("i am %s",i);
System.out.println( "name -> " + s);
UnsafeBuffer unsafeBuffer = new UnsafeBuffer(s.getBytes());
unsafeBuffer.wrap(s.getBytes());
buffer.write(1, unsafeBuffer, 0, s.length());
}
}
}
public class Consumer implements Runnable {
private final RingBuffer buffer;
public Consumer(RingBuffer buffer) {
this.buffer = buffer;
}
#Override
public void run() {
long start = System.currentTimeMillis();
CountDownLatch countDownLatch = new CountDownLatch(Config.SIZE);
while (countDownLatch.getCount() > 0) {
buffer.read((msgTypeId, srcBuffer, index, length) -> {
byte[] message = new byte[length];
srcBuffer.getBytes(index, message);
System.out.println("Consumer <- " + new String(message));
countDownLatch.countDown();
});
}
long end = System.currentTimeMillis();
System.out.println("cost time " + (end - start));
}
}
public class App {
private static final OneToOneRingBuffer BUFFER = new OneToOneRingBuffer(new UnsafeBuffer(
ByteBuffer.allocate(1024 + RingBufferDescriptor.TRAILER_LENGTH)));
public static void main(String[] args) throws Exception {
ExecutorService executor = Executors.newCachedThreadPool();
executor.execute(new Producer(BUFFER));
executor.execute(new Consumer(BUFFER));
Thread.currentThread().join();
}
}
The Config.SIZE just set to 100_000 and when it was 10_000 ,the programe runs well.
Is the OneToOneRingBuffer class a thread-unsafe class?

why newsinglethreadexcutor blocks currentthread?

I am trying to understand why newsinglethreadexecutor with callable futures' get() method blocks the binderthread which its initialized in. How can I make them run together?
public class main {
public static void main(String[] args) {
final process prc = new process();
prc.run();
System.out.println("main thread" + Thread.currentThread().getName());
}
};
,,
import java.util.concurrent.*;
public class process {
ExecutorService es = Executors.newSingleThreadExecutor();
public void run() {
Future fut = es.submit(new Callable<String>() {
public String call() throws Exception {
for (byte b : new byte[]{1,2,3,4,4}){
System.out.println(b+Thread.currentThread().getName());
Thread.sleep(2000);
}
return "aa";
}
});
try {
// System.out.println(fut.get(1900L, TimeUnit.MILLISECONDS));
System.out.println(fut.get());
}catch (Exception a){}
}
}

Interrupt a thread from another thread in java?

I have to create a program that simulate a bomb... The user has 5 seconds to digit the right code, if he can't, the bomb explodes.
class Codice implements Runnable{
String code;
#Override
public void run() {
code = JOptionPane.showInputDialog("Inserire codice disinnesco:");
if(code.equals(Bomba.check)) {
Bomba.s = "true";
JOptionPane.showMessageDialog(null, "Bomba disinnescata");
}
System.out.println(Bomba.s);
}
}
class Esplosione implements Runnable{
#Override
public void run() {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
if(!Bomba.s.equals("true")) {
JOptionPane.showMessageDialog(null, "BOOM!");
}
}
}
public class Bomba {
static String s = "false";
static String check = "123456";
public static void main(String[] args) throws IOException {
Codice c = new Codice();
Esplosione ex = new Esplosione();
Thread t1 = new Thread(c);
Thread t2 = new Thread(ex);
t1.start();
t2.start();
}
}
With this code i can insert the code, and if it's right the bomb doesn't explodes and the program finish. If 5 seconds passes, the message "boom" appears but the first thread doeasn't stop... How can i do?
There are many ways to coordinate between threads; interrupting is one way. Here is an example using Thread.interrupt. It dispenses with your state variable s, which becomes unnecessary:
import javax.swing.*;
import java.io.*;
class Codice implements Runnable {
String code;
Thread other;
Codice(Thread other) {
this.other = other;
}
#Override
public void run() {
code = JOptionPane.showInputDialog("Inserire codice disinnesco:");
if(code.equals(Bomba.check)) {
other.interrupt();
JOptionPane.showMessageDialog(null, "Bomba disinnescata");
}
}
}
class Esplosione implements Runnable {
#Override
public void run() {
try {
Thread.sleep(5000);
JOptionPane.showMessageDialog(null, "BOOM!");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public class Bomba {
static String check = "123456";
public static void main(String[] args) throws IOException {
Esplosione ex = new Esplosione();
Thread t2 = new Thread(ex);
Codice c = new Codice(t2);
Thread t1 = new Thread(c);
t1.start();
t2.start();
}
}

How to implement runnable with java

I am trying to create a program that will carry on running automatically without me having to do anything. I am a bit confused on how to implement runnable in java so I can create a thread that will go to sleep for a certain period of time and then run the re-run the program after the sleep period is over.
public class work {
public static void main(String[] args) throws IOException, InterruptedException {
work test = new work();
test.information();
}
private ConfigurationBuilder OAuthBuilder() {
ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setOAuthConsumerKey("dy1Vcv3iGYTqFif6m4oYpGBhq");
cb.setOAuthConsumerSecret("wKKJ1XOPZbxX0hywDycDcZf40qxfHvkDXYdINWYXGUH04qU0ha");
cb.setOAuthAccessToken("4850486261-49Eqv5mogjooJr8lm86hB20QRUpxeHq5iIzBLks");
cb.setOAuthAccessTokenSecret("QLeIKTTxJOwpSX4zEasREtGcXcqr0mY8wk5hRZKYrH5pd");
return cb;
}
public void information() throws IOException, InterruptedException {
ConfigurationBuilder cb = OAuthBuilder();
Twitter twitter = new TwitterFactory(cb.build()).getInstance();
try {
User user = twitter.showUser("ec12327");
Query query = new Query("gym fanatic");
query.setCount(100);
query.lang("en");
String rawJSON =null ;
String statusfile = null;
int i=0;
try {
QueryResult result = twitter.search(query);
for(int z = 0;z<5;z++){
for( Status status : result.getTweets()){
System.out.println("#" + status.getUser().getScreenName() + ":" + status.getText());
rawJSON = TwitterObjectFactory.getRawJSON(status);
statusfile = "results" + z +".txt";
storeJSON(rawJSON, statusfile);
i++;
}
}
System.out.println(i);
}
catch(TwitterException e) {
System.out.println("Get timeline: " + e + " Status code: " + e.getStatusCode());
if(e.getErrorCode() == 88){
Thread.sleep(900);
information();
}
}
} catch (TwitterException e) {
if (e.getErrorCode() == 88) {
System.err.println("Rate Limit exceeded!!!!!!");
Thread.sleep(90);
information();
try {
long time = e.getRateLimitStatus().getSecondsUntilReset();
if (time > 0)
Thread.sleep(900000);
information();
} catch (InterruptedException e1) {
e1.printStackTrace();
}
}
}
}
private static void storeJSON(String rawJSON, String fileName) throws IOException {
FileWriter fileWriter = null;
try
{
fileWriter = new FileWriter(fileName, true);
fileWriter.write(rawJSON);
fileWriter.write("\n");
}
catch(IOException ioe)
{
System.err.println("IOException: " + ioe.getMessage());
} finally {
if(fileWriter!=null) {
fileWriter.close();
}
}
}
}
You have severable options to implement a thread in Java.
Implementing Runnable
When a class implements the Runnable interface, he has to override the run() method. This runnable can be passed to the constructor of a Thread. This thread can then be executed using the start() method. If you'd like to have this thread run forever and sleep, you could do something like the following:
public class HelloRunnable implements Runnable {
public void run() {
while(true){
Thread.sleep(1000);
System.out.println("Hello from a thread!");
}
}
public static void main(String args[]) {
(new Thread(new HelloRunnable())).start();
}
}
Extending Thread
Thread itself also has a run() method. When extending thread, you can override the Thread's run() method and provide your own implementation. Then you'd have to instantiate your own custom thread, and start it in the same way. Again, like the previous you could do this:
public class HelloThread extends Thread {
public void run() {
while(true){
Thread.sleep(1000);
System.out.println("Hello from a thread!");
}
}
public static void main(String args[]) {
(new HelloThread()).start();
}
}
Source: Oracle documentation
Building on the previous answer, you need to either extend Thread or implement Runnable on your Work class. Extending Thread is probably easier.
public class work extends Thread {
public void run() {
// your app will run forever, consider a break mechanism
while(true) {
// sleep for a while, otherwise you'll max your CPU
Thread.sleep( 1000 );
this.information();
}
}
public static void main(String[] args) throws IOException, InterruptedException {
work test = new work();
test.start();
}
// ... rest of your class
}
public static void main(String[] args){
Thread thread = new Thread(runnable); // create new thread instance
thread.start(); // start thread
}
public static Runnable runnable = new Runnable(){
#Override
public void run(){
final int DELAY = 500;
while(true){
try{
// Code goes here;
Thread.sleep(DELAY)
} catch(Exception e){
e.printStackTrace();
}
}
}
}

Tracking Executing Threads

I am trying to figure out how I can track all the threads that my application is spawning. Initially, I thought I had it figured out using a CyclicBarrier, however I am seeing threads executing after my await call.
Below is the working pseudo code:
public class ThreadTesterRunner {
public static void main(String[] args) throws InterruptedException {
final CyclicBarrier cb = new CyclicBarrier(1);
ThreadRunner tr = new ThreadRunner(cb);
Thread t = new Thread(tr, "Thread Runner");
t.start();
boolean process = true;
// wait until all threads process, then print reports
while (process){
if(tr.getIsFinished()){
System.out.println("Print metrics");
process = false;
}
Thread.sleep(1000);
}
}
}
class ThreadRunner implements Runnable {
static int timeOutTime = 2;
private ExecutorService executorService = Executors.newFixedThreadPool(10);
private final CyclicBarrier barrier;
private boolean isFinished=false;
public ThreadRunner(CyclicBarrier cb) {
this.barrier = cb;
}
public void run(){
try {
boolean stillLoop = true; int i = 0;
while (stillLoop){
int size;
Future<Integer> future = null;
try {
future = executorService.submit(new Reader()); // sleeps
size = future.get();
} catch (InterruptedException | ExecutionException ex) {
// handle Errs
}
if(i == 3){
stillLoop = false;
this.barrier.await();
this.isFinished=true;
}
//System.out.println("i = "+i+" Size is: "+size+"\r");
i++;
}
} catch (InterruptedException | BrokenBarrierException e1) {
e1.printStackTrace();
}
}
public boolean getIsFinished(){
return this.isFinished;
}
}
class Reader implements Callable {
private ExecutorService executorService = Executors.newFixedThreadPool(1);
#Override
public Object call() throws Exception {
System.out.println("Reading...");
Thread.sleep(2000);
executorService.submit(new Writer());
return 1000;
}
}
class Writer implements Callable {
#Override
public Void call() throws Exception {
Thread.sleep(4000);
System.out.println("Wrote");
return null;
}
}
Can anyone suggest a way to ONLY print "print metrics" after all threads have run?
It doesn't seem like you're doing anything to coordinate with your Reader and Writer threads, which are the ones you want to wait for. If you pass your synchronization barrier through to those threads so that they can register and signal when they are done, it works just fine.
Here's a version rewritten to do so, using a Phaser instead of a CyclicBarrier. Note that each Reader and Writer registers itself upon construction, and notifies the synchronization barrier when it is done executing:
public class ThreadTesterRunner {
public static void main(String[] args) throws InterruptedException {
final Phaser cb = new Phaser();
ThreadRunner tr = new ThreadRunner(cb);
Thread t = new Thread(tr, "Thread Runner");
t.start();
boolean process = true;
// wait until all threads process, then print reports
while (process){
if(tr.getIsFinished()){
System.out.println("Print metrics");
process = false;
}
//else {
// System.out.println("Waiting: registered=" + cb.getRegisteredParties() + ", arrived=" + cb.getArrivedParties() + ", unarrived=" + cb.getUnarrivedParties());
//}
Thread.sleep(1000);
}
}
}
class ThreadRunner implements Runnable {
static int timeOutTime = 2;
private ExecutorService executorService = Executors.newFixedThreadPool(10);
private final Phaser barrier;
private boolean isFinished=false;
public ThreadRunner(Phaser phaser) {
this.barrier = phaser;
}
public void run(){
try {
boolean stillLoop = true; int i = 0;
while (stillLoop){
int size;
Future<Integer> future = null;
try {
future = executorService.submit(new Reader(this.barrier)); // sleeps
size = future.get();
} catch (InterruptedException | ExecutionException ex) {
// handle Errs
}
if(i == 3){
stillLoop = false;
this.barrier.awaitAdvance(0);
this.isFinished=true;
}
//System.out.println("i = "+i+" Size is: "+size+"\r");
i++;
}
} catch (Exception e1) {
e1.printStackTrace();
}
}
public boolean getIsFinished(){
return this.isFinished;
}
}
class Reader implements Callable {
private Phaser barrier;
private ExecutorService executorService = Executors.newFixedThreadPool(1);
public Reader(Phaser phase) {
phase.register();
this.barrier = phase;
}
#Override
public Object call() throws Exception {
System.out.println("Reading...");
Thread.sleep(2000);
executorService.submit(new Writer(this.barrier));
this.barrier.arrive();
return 1000;
}
}
class Writer implements Callable {
private Phaser barrier;
public Writer(Phaser phase) {
phase.register();
this.barrier = phase;
}
#Override
public Void call() throws Exception {
Thread.sleep(4000);
System.out.println("Wrote");
this.barrier.arrive();
return null;
}
}
From what I can see you aren't waiting for the Writer to finish in the Reader. Is that the problem you are seeing?
You are also accessing isFinished from more than one thread without synchronization (which however, merely may delay the termination of the loop in this situation).
I don't see CyclicBarrier doing anything.
Not sure what you are trying to do, but I'd think about how simpler I can make it. For example, can Reader and Writer be combined into one task? Then, waiting for them to finish would merely be:
executorService.invokeAll(tasks);
System.out.println("Print metrics");
where tasks is a collection of tasks (see also this javadoc)

Categories