Guarded Blocks And Threads

May 30, 2014

I'm reading the following section of the Oracle docs:

Guarded Blocks (The Java Tutorials > Essential Classes > Concurrency)

We have multiple threads. One of them sets the joy flag to true. The other waits until joy flag is set to true in order to print to the output stream. Rather than squander processer resources with a while loop, we choose to use the wait method of Object which suspends execution of thread. When the other thread throws an exception, we check the loop condition again.

Java Code:

public synchronized void guardedJoy() {
// This guard only loops once for each special event, which may not
// be the event we're waiting for.
while(!joy) {
try {
wait();
} catch (InterruptedException e) {}
}
System.out.println("Joy and efficiency have been achieved!");
} mh_sh_highlight_all('java');

The documentation goes on to state the following:

When a thread invokes d.wait, it must own the intrinsic lock for d - otherwise an error is thrown. Invoking wait inside a synchronized method is a simple way to acquire the intrinsic lock. When wait is invoked, the thread releases the lock and suspends execution.

The statement seems somewhat contradictory. When we invoke wait inside a synchronized method, is the intrinsic lock acquired or released? I thought it was the synchronized keyword itself that acquired the intrinsic lock.

View Replies


ADVERTISEMENT

Try Blocks In Main

Mar 10, 2014

import java.io.*;
import java.util.List;
import java.util.ArrayList;
public class ListOfNumbers {
try

[code]....

i tried this code in BlueJ IDE.it told me i had an illegal beginning for "try".am i not supposed to use try for main methods?

View Replies View Related

Building A Pyramid From Blocks?

Apr 15, 2014

I am trying to make a pyramid from blocks . I know that for example to make a bigger block from small blocks you write something like :

for(int i = 10 ;i <=1 ; i--){
for (int j= 10 ;j <= 1 ; j--) {
< statement to create block where you use both i and j to define the location of each block>
}
}

but i cant seem go grasp how to make a pyramid , so far my best effort is :

int i =10 ;
while (i >=1 ) {
for( ; i>=1 ; i-- ){
< statement to create block > }
}

At the moment visually i don't get a pyramid but it might be because of other issues and not because of the while and then a for inside it approach .

My approach is correct and if now what would be the correct one to create a pyramid from smaller blocks ?

View Replies View Related

What Are Static Initialization Blocks

Apr 2, 2015

What static initialization blocks do in java?

View Replies View Related

Proper Way To Organize Code Into Blocks

Feb 16, 2015

When I run this (entering 12 for both questions) I get this error:

java.lang.ArrayIndexOutOfBoundsException: 12
at MathTablesTwo.main(MathTablesTwo.java:22)

Also, what would be the proper way to organize my code into blocks?

import java.util.Scanner;
public class MathTablesTwo {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);

[code]....

View Replies View Related

Static Initializer Blocks In Class?

Mar 10, 2014

when do they get called?

from my code

class MyJava{
static { System.out.println("initializing..."); }
public static void main(String[] args)
{
}
}

i did get the "initializing..." string output, even though i didn't create any MyJava objects.

from this fact, i inferred that initializing blocks get called once when the program compiles.

am i right?

View Replies View Related

JSP :: How To Avoid Large Code Blocks Inside Scriptlets

Jul 22, 2014

I've already seen large code blocks inside JSP's, in a way it is very hard to maintain the web application. Is there a way to avoid that?

View Replies View Related

I/O / Streams :: Divide A Text File Into Blocks Of 128 Bits

Feb 7, 2006

I have to divide a text file into blocks of 128 bits. I think i must use the ByteArrayInputStream and ByteArrayOutputStream classes. is there any website showing how to user these two ByteArrayInputStream and ByteArrayOutputStream classes in detail. or it would be much better if you could show me a portion of the code.

View Replies View Related

Swing/AWT/SWT :: Select Different Blocks Of Code When File Selected In JFileChooser?

Nov 12, 2014

I have a program where I have to open a file and then run a piece of code to do something with it. However since there are different files I want to run different pieces of code depending on the file. I have a JFileChooser setup and it works but I would like to have a something like an if else depending on the file extension.

View Replies View Related

Read Picture And Print Out Number Of Blocks - Counting In Multidimensional Array

Dec 19, 2014

I have to write a program that will read a picture and then print out the number of blocks inside it.

I have to read the picture as a binary matrix of the size r - c (number of rows times number of columns). The blocks are groups of one or more adjacent elements with the value 1.

- Blocks are built exclusively of elements with value 1
- Each element with value 1 is a part of some block
- Adjacent elements with value 1 belong to the same molecule.

We only take into account the horizontal and vertical adjacency but not diagonal.

INPUT:

In the first line of the input we have the integers r and c, separated with one space.
Then we have the r lines, where each contains s 0's and 1's.
The numbers inside the individual lines are NOT separated by spaces.

The OUTPUT only print the number of blocks in the picture.

Example:

INPUT:
7 5
01000
00010
00000
10000
01000
00001
00100

OUTPUT:
6

THIS IS WHAT I CAME UP SO FAR:

import java.util.Scanner;
class Blocks{
public static void main(String[] args){
Scanner sc=new Scanner(System.in);
char ch[][];
int rowNum=sc.nextInt();
int columnNum=sc.nextInt();

[Code] ....

View Replies View Related

SWT And Threads On Mac OS X

Apr 20, 2014

I'm new to Java and trying to write code a Java program on Mac OS X using IntelliJ. My program uses the SWT library and contains two class's; the first called "view" and the second called "main". The "view" class defines the SWT objects, extends the "Thread" class and contains a "run" method;

public void run() {
initComponents();
while (!display.isDisposed()) {
if (!display.readAndDispatch()) {

display.sleep();

[code]....

I searched for a solution and saw that I have to use the "-XstartOnFirstThread" parameter to JVM. I'm trying it with no success.

View Replies View Related

Compute Recursively Total Number Of Blocks In Triangle With Given Number Of Rows

Jul 8, 2014

We have triangle made of blocks. The topmost row has 1 block, the next row down has 2 blocks, the next row has 3 blocks, and so on. Compute recursively (no loops or multiplication) the total number of blocks in such a triangle with the given number of rows.

triangle(0) → 0

triangle(1) → 1

triangle(2) → 3

View Replies View Related

Distinguish Between Different Threads

Apr 28, 2014

I making a program that a client connect to a server, then it's starts changing information throw the socket. The info is String. When connection with one open client everything is working great. The problem starts when I connect 2 or more clients simultaneously.

The server doesn't know how to handle each request so it's send info to both the client info that is wrong. If I run several clients and then execute the last client that opens he will work fine the others will crush. On the server I'm getting connection reset. The problem i believe is with the closing socket and thread holding.

View Replies View Related

Monitoring Java Threads From Another JVM

Feb 5, 2014

I have this web app in Glassfish which, among other things, monitors consultations in some DB. It's a JEE-EAR app, three layers. Pretty boring until now. Now, there's another WAR-app on Tomcat that processes files through threads. These threads represent an Excel file processed one row at a time.

I need to know when one of those threads are created, when they're alive and when they're terminated, from the Glassfish app.

I need to monitor these batch processes.

I think I could insert the thread ID from the tomcat app in some DB and when it dies, delete it. The glassfish app would query that BD and see if there is one of those batch processes running.

I understand that a thread ID can be recycled but I can find a way to make every process unique.

My first question, would this be viable?

My second question is, could I uniquely set the thread name and then ask for it from the glassfish app to the tomcat-app process thread set? I mean, without a DB in the middle?

View Replies View Related

Threads - Print Even And Odd Numbers Between 0 And 30

Mar 11, 2015

Here is what I am trying to do:

Write a program to print the even numbers and the odd numbers between 0 and 30 using a single thread and then again using multiple threads.

I already finished the single-threaded program but am having trouble with the multi-threaded one. I have three classes; one class for odd numbers, one for even numbers, and one to execute the code. Here is my code so far:

Even Numbers:

Java Code:

public class EvenNumbers extends Thread {
public void run() {
for (int i=1; i<=30; i++) {
if (i%2 == 0) {
System.out.println("Even number " + i);

[Code] ....

Unfortunately, my output ends up looking a little weird:

Java Code:

C:UsersREDACTEDDropboxSchoolworkREDACTEDJava ProgrammingUnit 5 - Exception
Handling, AssertionsProgram - Thread>java MultiThread
Even Numbers:
Odd Numbers:
Even number 2

[Code] .....

View Replies View Related

Building DOM Object From Multiple Threads

May 21, 2014

My multi threaded application processes and loads records into an ECM repository. For reconcliation purposes , I am trying to build an XML format report with the results of the processing per record, while processing is underway per thread. The method below is called from every thread wvery time its ready to append an element to the DOM with the status.

public void writeReportLine(Element rptLine) {
// Write output to report file
synchronized (XMLReportHandler.class) {
reportOutput.getDocumentElement().appendChild(rptLine);
}
}

After all processing completes, the below method is called only once by every thread to write to the File on the file system:

public void writeToReportFile() {
synchronized (XMLReportHandler.class) {
try{
//write the content into xml file
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(reportOutput);
 
[Code] ....

The problem is that when under load, the threads just seem to hang while the transformer.transform(source, result) call keeps getting executed until there is an interrupt of some sort. I was able to examine a section of what was appended and it was status for records that had finished processing very early in the process based on my application logs. Once an interrupt is recieved , it looks like the threads recover.

View Replies View Related

How To Minimize CPU Usage For Sockets And Threads

Aug 16, 2012

I created an instant messenger using java. When I have the Server that communicates between the clients and one client running on my Computer the CPU Usage is at 100%. It really slows down everything else I'm doing and I figure this might be an issue if I gave this to people to use. I don't want the client taking up a lot of CPU Usage if they're just running it in the background while doing other things on their computer. The program utilizes multithreading. Each thread is constantly being polled for input.

The Server, as seen below, has two threads. I explain what the threads do before the code. There is also another while loop running constantly in the server that is waiting for sockets to connect. The loop does not run constantly at the line socket.accept(); it stops and just waits.

The User, split into a menu and chat window, has two threads as well. I explain what the threads do before the code. After I originally posted I put a 100 ms sleep in all my threads. CPU Usage is still at 100%*

This thread listens for input from the user. The input tells the server what action to take. There is a thread running for every user currently connected to the server.

public void run()
{
try
{
input = new DataInputStream(user.getSocket().getInputStream());
output = new DataOutputStream(user.getSocket().getOutputStream());

[code]....

View Replies View Related

Threads - Object Visible To More Than One Thread

Mar 24, 2014

I need a small example of an object which is visible to two different threads.

Does saying "an object is visible to two threads" mean that it's fields or methods are being used in both the threads? I am not clear about that.

View Replies View Related

Console Freezes When Working In Different Threads

Jul 22, 2014

I have a console application. One thread allows a user to directly input into a console. Another thread listens on a tcp port, takes input, processes it, and then writes it to the console. The work in different threads, but in tcp thread, one I call a method outside that thread that writes to console, it often gets stuck. here is a mockup of situation:

Java Code:

import java.io.BufferedReader;
import java.io.Console;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

[Code] ......

It often freezes on "Attempt 1". Before I used System.out there, I also tried console.writer() there but both freeze at that point often. Any situation where console or System.out.writeln freeze when working across threads and why it is occurring? It almost feels like one thread has locked the console so the others can't write to it.

View Replies View Related

Array Out Of Bounds Error When Using Threads?

Nov 30, 2014

I have been working on this program for a while and now i seem to be stump it throws an outof Bound array exception error, this program is a matrix multiplication program and spits out the resulting matrix using multithreading. i have a running one and result is

2 -1 0
1 0 3
-1 1 3

but this program's result is:

2 0 0
1 0 0
-1 0 0

it reads a txt document as an commandline arguement the text file reads just like this below:

3 2 2 3
1 0
0 1
-1 1
2 -1 0
1 0 3

the following is my code:

import java.util.*;
import java.io.*;
public class P3 {
public static int matrix1[][];
public static int matrix2[][];

[code].....

View Replies View Related

How To Create Multiple Threads Of Ball

Apr 18, 2014

Actually, i want to create multiple ball using multithreading.I have created a class 'CreateBall' and this class is making ball and second class 'Balls' is a Panel where the ball is display.But only one ball is being displayed.

Here is my code.......

CreateBall.java
import java.awt.*;
public class CreateBall implements Runnable
{
int px,py;
int w=20,h=20;
Graphics g;
public CreateBall(int px,int py)

[Code] .....

View Replies View Related

Move Two Objects Across JFrame With Threads

Jun 25, 2014

Below are three classes. The first and second create car objects and the third is the main method. My goal is to move two cars across the window. When I compile and run the program both cars are generated however they will not animate. I am moving them with threads but I cannot seem to find why the cars will not move.

import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JComponent;
public class CarComponent extends JComponent {
private Car car1;
private Car car2;

[Code] ....

View Replies View Related

Multiple Threads Not Inserting Everything Into MySQL

Jun 19, 2014

I am very new to threading. I have a program that calls my api and gets data back in json format. Each request returns a row of data in json format. All together I need to retrieve about 2,000,000 rows a day which means 2,000,000 requests (I understand that this is bad design, but the system was not designed for this purpose it is just what I need to do for the next couple of weeks). When I tried running it on a single thread I was processing about 200 requests a minute which is much too slow. As a result I created 12 threads and I was processing 5500 rows a minutes which was a great improvement.

The problem was only about on average 90% of the rows were inserted into the database as I ran it a few times to make sure. Before each insert printed to a file each URL which was sent and then I checked to see if each insert statement was successful (returned 1 when executed ) and it all seems fine. Every time I run it it inserts about 90% but it does varies and it has never been a consistent number.

Essentially the code starts in main by creating 12 threads. Each thread's creates a run method which calls a new instance of MySQLPopulateHistData and passes a start and end integer which are used in the insert statement for ranges. I have done many system.out.println type testing and can see all the threads do start and all the 12 instances (one instance for each thread) called are executing?

MAIN:

import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class MainClass {
public static void main(String[] args) {

[code]....

View Replies View Related

Display Serial Number Using Two Threads

Jun 4, 2014

Aim : display a serial number using two thread Say (odd numbers)t1=1,3,5,7....99, and (even no) t2=2,4,6,8......100

How to resolve this problem ?

output will be:
1
2
3
:
100

View Replies View Related

Running Threads Without Using Runnable Implementation?

Dec 16, 2014

I've seen examples that don't use a separate Runnable Implementation, but Instead Just make a subclass of Thread and override the Thread's runO method. That way,you call the Thread's no--arg constructor when you make the new thread;

Thread t = new Thread(); 1/no Runnable"

Any simple code that demonstrates the same. I haven't fully understood what is said in the text above. I have a hunch that the last line is wrong and it should be Thread t = new <Whatever class extends Thread class and over rides its run method>()

Am I correct or wrong....

View Replies View Related

Swing/AWT/SWT :: Using Multiple SwingWorker Threads

Aug 23, 2014

I have a Swing UI in which on click of Search button, I trigger the Search in 6 different modules in 6 Swing Worker threads. The results are returned by each Swing Worker class to the calling class.

I tried to use the below code to get the values returned from each thread. Now, I want to continue further only after all threads finish their execution. How to achieve this?

thread1.addPropertyChangeListener(new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent evt) {
if (StateValue.DONE == thread1.getState()) {
try {

[Code] ....

I got several examples where the UI is updated direstly from multiple threads. I want the values to be returned to calling class because of below reasons:

1) When even one worker thread fails for some reason, I dont want to show the any result in the UI
2) Earlier, I was updating the UI in done() of every worker class. But, UI became inconsistent. E.g When one thread is in progress, other threads were completed and updating the UI which I dont want to do.

View Replies View Related







Copyrights 2005-15 www.BigResource.com, All rights reserved