I'm trying to make room reservation system, I have multi clients access same reservation method.
so I put this method into thread class and I want to make one ReentrantLock to allow one client to access the reservation method.. also this method will be called from another class.
the problem I got is nullPointerException.
this is my code:
public class server {
public static void main(String[] args) throws IOException {
ServerSocket s = new ServerSocket(9800);
ReentrantLock roomLock = new ReentrantLock();
while(true){
System.out.println("Server ready to recive clint... ");
Socket k = s.accept();
System.out.println("Clint "+ s.getInetAddress() +" accept " );
new myThread(k,roomLock).start();
}
}
}
class myThread extends Thread{
Socket s;
public static ReentrantLock roomLock;
public myThread(Socket so, ReentrantLock rl) {
this.s = so;
this.roomLock = rl;
}
#Override
public void run(){
}
public static Boolean resRoom(String usname,JRootPane rootPane,Date date1,Date date2,Boolean chbox,int sp){
Boolean stv = true;
if(roomLock.tryLock()){
// my critical section
roomLock.unlock();
}
return stv;
}
}
the method should be static to access it from another class
Related
This question already has answers here:
Java Wait and Notify: IllegalMonitorStateException
(2 answers)
Closed 4 years ago.
Was trying to practice producer and consumer using a simple counter in java.
Not sure why I am getting a Illegal Monitor State exception on this piece of code.
I have counter rest and counter consume methods which run in their own thread.
The counter itself is a static int volatile field .
The counter class also gives you a lock to
If I change the wait naotify to the following:
Counter.lock.notify();
Counter.lock.wait();
The code works. Dosen't wait() and notify() automatically takes the reference of the lock synchronize is on?
Producer Class
package multithreading;
public class CounterProducer implements Runnable {
public void run() {
try { incrCounter(); } catch (InterruptedException e) { e.printStackTrace(); }
}
public void incrCounter() throws InterruptedException {
while (true) {
synchronized (Counter.lock) {
if (Counter.counter < 1) {
System.out.println("Counter Reset");
Counter.counter = 10;
notify();
wait();
}
}
}
}
}
Consumer Class
package multithreading;
public class CounterConsumer implements Runnable {
public void run() {
try { consumeCounter(); } catch (InterruptedException e) { e.printStackTrace(); }
}
public void consumeCounter() throws InterruptedException {
while (true) {
synchronized (Counter.lock) {
if (Counter.counter > 0) {
System.out.println("Consumed");
Counter.counter--;
notify();
wait();
}
}
}
}
}
The Counter
public class Counter {
public static volatile int counter;
public static final Object lock = new Object();
}
The Counter
public class CounterRunner {
public static void main(String[] args) {
Thread con = new Thread(new CounterConsumer());
Thread prod = new Thread(new CounterProducer());
con.start();
prod.start();
}
}
The Runner
public class CounterRunner {
public static void main(String[] args) {
Thread con = new Thread(new CounterConsumer());
Thread prod = new Thread(new CounterProducer());
con.start();
prod.start();
}
}
If I change the wait naotify to the following, the code works:
Counter.lock.notify();
Counter.lock.wait();
Every Java method is either a static method of some class or an instance method of some object. If you see a method call that does not contain an explicit class name or object reference, then it is an implicit call to a method belonging to the this object.
That is to say, notify() means the same thing as this.notify(), and wait() means this.wait().
this, refers to the CounterProducer instance when it appears in your CounterProducer.incrCounter() method, and it refers to the CounterConsumer instance when it appears in your CounterConsumer.consumeCounter() method.
import java.util.Scanner;
import static java.lang.Thread.sleep;
class RunnableDemo implements Runnable {
private Thread t;
private String threadName;
RunnableDemo( String name){
threadName = name;
}
public void run() {
System.out.println("asd");
}
public void start ()
{
if (t == null)
{
t = new Thread (this, threadName);
t.start ();
}
}
}
class RunnableDemo1 implements Runnable {
private Thread t;
private String threadName;
RunnableDemo1( String name){
threadName = name;
}
public void run() {
Scanner in = new Scanner(System.in);
System.out.print("Enter here:");
String x = in.nextLine();
System.out.println(x);
}
public void start ()
{
if (t == null)
{
t = new Thread (this, threadName);
t.start ();
}
}
}
public class Main {
public static void main(String[] args) throws InterruptedException {
RunnableDemo1 R1 = new RunnableDemo1( "Thread-1");
R1.start();
sleep(1000);
RunnableDemo R2 = new RunnableDemo( "Thread-2");
R2.start();
}
}
Println will print a line to the command prompt but in.nexLine() (also tried in.next() does not recognize it. Is there any way I am able to print a string to the command prompt and have the scanner recognize it? Or something similar?
System.out.println shouldn't send anything to the server since it sends the String to the standard out only, usually the console, unless you've re-routed the standard out, something that I don't recommend that you do. Instead you need to actually send something to the server, perhaps in your notifyObservers method, but hard to say without your mcve.
In all this remains a very incomplete question until you improve it.
Edit: yes the Observable API shows that public void notifyObservers(Object arg) has an overload that accepts an Object parameter. Why not pass your String in there?
Edit 2: OK, you're confused, because that's not how you have one class communicate with another. Printing something out to the console will not trigger the System.in to update in another thread. Again, do what I stated above.
I am in an introductory networking class this semester and we are working with Server/Client chat rooms. This is my Server program so far, and I can't figure out why I'm getting the error in the title. It show the error on lines 17, 33, and 53, which are all lines where I've named new classes.
Any help with me appreciated!
import java.io.*;
import java.net.*;
public class Server
{
public static void main(String[] args) throws Exception
{
new MyServer().start(); //Creates new Server for Clients to connect
}
}
public class MyServer() extends Thread
{
ServerSocket SS = new ServerSocket(11200);
Socket S;
ClientManager CM = new ClientManager();
public void run()
{
while(true)
{
S = SS.Accept; //Endless loop allowing clients to repeatedly connect
CM.Add(); //Calls the Add method in ClientManager, which adds the Client to the Array
}
}
}
public class MyClient() extends Thread
{
MyClient Client = new MyClient(Socket, CM);
Scanner S;
public void run()
{
while(true)
{
S = new Scanner(System.in);
CM.SendToAllClients(S); //Calls the method that will send each client the received message
}
}
public void Send(String S)
{
PrintWriter.println(S);
}
}
public class ClientManager()
{
MyClient[] X = new MyClient[15];
int num = 0;
public synchronized void Add(MyClient C)
{
X[num] = C;
num++;
C.start();
}
public synchronized void SendToAllClient(String S)
{
for(i = 0;i < num;i++);
{
X[i].Send(S);
}
}
}
Don't use () after your class names:
public class MyServer extends Thread {...}
public class MyClient extends Thread {...}
public class ClientManager {...}
Hi i have made a something that extends thread that adds adds an object that has a IP in it. then i made two instances of this thread and started them. they use the same list.
I now want to use Synchronized to stop the concurrent update problem. But its not working and i cant work out why.
My main class:
import java.util.*;
import java.io.*;
import java.net.*;
class ListTest2 {
public static LinkedList<Peer> myList = new LinkedList<Peer>();
public static void main(String [] args) {
try {
AddIp test1 = new AddIp(myList);
AddIp test2 = new AddIp(myList);
test1.start();
test2.start();
} catch(Exception e) {
System.out.println("not working");
}
}
}
My thread class:
class AddIp extends Thread {
public static int startIp = 0;
List<Peer> myList;
public AddIp(List<Peer> l) {
myList = l;
}
public synchronized void run() {
try {
startIp = startIp+50;
int ip = startIp;
InetAddress address = InetAddress.getByName("127.0.0.0");
Peer peer = new Peer(address);
while(ip <startIp+50) {
ip++;
address = InetAddress.getByName("127.0.0."+ip);
peer = new Peer(address);
myList.add(peer);
if(myList.indexOf(peer)== (myList.size() -1)) {
} else {
System.out.println("Lost"+peer.peerIp);
}
}
} catch(Exception e) {
}
}
}
Can anyone help me out here im lost for ideas thanks.
public synchronized void run()
Synchronizes on calling instance: this.
So,
1st thread synchronizes on test1 and 2nd thread synchronizes on test2, which doesn't help at all.
You want to synchronize on the shared resource, in this case: myList
public void run() {
synchronize(myList){
//your Logic
}
}
As a side note: Implement runnable instead of extending a Thread. Read more here.
You'd be better off implementing Runnable oppose to extending thread
also
public void run() {
synchronize(list){
//stuffs
}
}
they use the same list.
You can try to use Vector instead List. Vector is synchronized
or set your List to be synchronized:
List myList = Collections.synchronizedList(myList);
instead to use:
synchronize(myList){
}
The easiest way is to use a List implementation that can handle multiple threads. Try CopyOnWriteArrayList.
I am new to threads and learning. Why does this data race? I know how to do it using the Synchronized(){} method but not with the modifier.
public class SyncMethodDataRace extends Thread {
private static int common = 0;
public synchronized void run(){
int local = common;
local++;
common = local;
}
public static void main(String[] args) throws InterruptedException {
SyncMethodDataRace[] allThreads = new SyncMethodDataRace[20000];
for(int i = 0; i < allThreads.length; i++){
allThreads[i] = new SyncMethodDataRace();
}
for(SyncMethodDataRace d: allThreads){
d.start();
}
for(SyncMethodDataRace d: allThreads){
d.join();
}
System.out.println(common);
}
}
By making run method synchronized you did not achieve the desired synchronization. A synchronized method locks on the current instance of the class. In your example, no other thread is calling the run method of another thread, so there is no blocking.
In your case you probably need a static object that is shared among all instances to synchronize on, ie:
private static Object syncObject = new Object();
public void run() {
synchronized (syncObject) {
//....
}
}