ORA-12532: TNS:invalid argument


sqlplus system@orcl

SQL*Plus: Release 11.1.0.6.0 - Production on Sun Aug 19 13:18:56 2007

Copyright (c) 1982, 2007, Oracle. All rights reserved.

Enter password:
ERROR:
ORA-12532: TNS:invalid argument

In this case we can ping to remote host but not able to connect database which we have created on remote host.

Cause : Listener port is closed.May be a firewall policy make the issue.

Action : We need to open Listener port for communication .By default Listener port is 1521.

Insert Array Output into Database


Hello Friends now a days i am working on php.A few days ago i got a task from my trainer and task was to uploading a txt file in new folder and output should be in an array format using loops and after that insert that output into database and the content in the text file was 100 email id's.At that time i was new in php and no idea how to start my task and how to use loops.For that i searched on net for many times but i couldn't find the required data to complete task on single site.
So,i had to serach many sites to collect or get idea how to complete my task.Now here in this post i am going to share that program with you so that if you get similar task like this task you can get help from this,i hope it will be helpful to you.

Here the program is:
1) Using this code you can upload your file from one folder to another folder.


<?php
if (($_FILES["file"]["type"] == 'text/plain') && ($_FILES["file"]["size"] < 20000))

  {
  if ($_FILES["file"]["error"] > 0)
    {
    echo "Return Code: " . $_FILES["file"]["error"] . "<br />";
    }
  else
    {
    echo "Upload: " . $_FILES["file"]["name"] . "<br />";
    echo "Type: " . $_FILES["file"]["type"] . "<br />";
    echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
    echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br />";


    if (file_exists("nit/" . $_FILES["file"]["name"]))
      {
      echo $_FILES["file"]["name"] . " already exists. "."<br/>"."<br/>";
      }
    else
      {
      move_uploaded_file($_FILES["file"]["tmp_name"],
      "nit/" . $_FILES["file"]["name"]);
      echo "Stored in: " . "nit/" . $_FILES["file"]["name"]."<br />";
 
      }
    }
  } 
  ?>


2) Use this code after 1st code as shown above, By using this code you will get your output in array format and after that output will be insert into database, see this code how its works,



<?php
        $file = fopen("file.txt", "r");
if ($file) {
  while (!feof($file))
  {
  $aa=fgets($file);
  $explode= explode(",",$aa);
  print_r(explode(',',$aa));
  foreach ($explode as $id =>$email_id)
 {
   $sql="insert into aa (id,email_id) values ('$id','$email_id')";
   $result=mysql_query($sql);
  }
 }
 
fclose($file);
      }
?>
</body>
</html>



Note:- In this above code we are using while loop as well as explode function after that we are using insert statement to insert output into database.

I hope you will find it informative.

Reclaiming Unused Space in Index.

We can see Reclaimable space in Schema by using below query.

SELECT'Task Name : ' || f.task_name || CHR(10) ||'Start Run Time : ' || TO_CHAR(execution_start, 'dd-mon-yy hh24:mi') || chr (10) ||'Segment Name : ' || o.attr2 || CHR(10) ||'Segment Type : ' || o.type || CHR(10) ||'Partition Name : ' || o.attr3 || CHR(10) ||'Message : ' || f.message || CHR(10) ||'More Info : ' || f.more_info || CHR(10) ||
'------------------------------------------------------' Advice FROM dba_advisor_findings f,dba_advisor_objects o,dba_advisor_executions e WHERE o.task_id = f.task_id AND o.object_id = f.object_id AND f.task_id = e.task_id AND e. execution_start > sysdate - 1 AND e.advisor_name = 'Segment Advisor' ORDER BY f.task_name;

Solution

There are a couple of effective methods for freeing up unused space associated with an index:




•Rebuilding the index
•Shrinking the index


Before you perform either of these operations, first check
USER_SEGMENTS to verify that the amount of space used corresponds with the Segment Advisor’s advice. In this example, the segment name is F_REGS_IDX1

SQL> select bytes from user_segments where segment_name = 'F_REGS_IDX1';
BYTES----------
166723584

This example uses the
ALTER INDEX...REBUILD

statement to re-organize and compact the space usedby an index:

SQL> alter index f_regs_idx1 rebuild;
Alternatively, use the
ALTER INDEX...SHRINK SPACE statement to free up unused space in an index—for example:

SQL> alter index f_regs_idx1 shrink space;

Now query

USER_SEGMENTS

again to verify that the space has been de-allocated. Here is the output forthis example:

BYTES----------
524288

The space consumed by the index has considerably decreased.

I prefer export and import is the another useful method to reclaim free space.

" Bharat Bandh " Is it reality or just a show off.

Is the bandh is the only way to protest, what type of bandh is this where people are forced to stay home and shut down their shops. All anti social elements are having a great time. A bandh should be something where people protest by themselves. Policitcan dont their work in Parliament and does not allow us to work too. What have they gained by calling this bandh we lost one day's pay.




 Its just a show off. If really the cry needs to be heard, there is no point in destroying public properties or blocking roads. Think! cover all petrol pumps, don't allow anyone to fill petrol tanks(allow only people who are in emergency i.e. hospital , ambulance, traveling etc). Cover up govt. offices, don't allow anyone to go inside. When govt. takes a hit, then they think about it. Rt now , general public is getting a hit, how does it affect the govt?

What is thread pool? Why should we use thread pools?

Ans: A thread pool is a collection of threads on which task can be scheduled. Instead of creating a new thread for each task, you can have one of the threads from the thread pool pulled out of the pool and assigned to the task. When the thread is finished with the task, it adds itself back to the pool and waits for another assignment. One common type of thread pool is the fixed thread pool. This type of pool always has a specified number of threads running; if a thread is somehow terminated while it is still in use, it is automatically replaced with a new thread. Below are key reasons to use a Thread Pool
  • Using thread pools minimizes the JVM overhead due to thread creation. Thread objects use a significant amount of memory, and in a large-scale application, allocating and de-allocating many thread objects creates a significant memory management overhead.
  • You have control over the maximum number of tasks that are being processed in parallel (= number of threads in the pool).
Most of the executor implementations in java.util.concurrent use thread pools, which consist of worker threads. This kind of thread exists separately from the Runnable and Callable tasks it executes and is often used to execute multiple tasks.

What is a thread leak? What does it mean in Java?

Ans:Thread leak is when a application does not release references to a thread object properly. Due to this some Threads do not get garbage collected and the number of unused threads grow with time. Thread leak can often cause serious issues on a Java application since over a period of time too many threads will be created but not released and may cause applications to respond slow or hang.

Q:How can I trace whether the application has a thread leak?
Ans:If an application has thread leak then with time it will have too many unused threads. Try to find out what type of threads is leaking out. This can be done using following ways:
  • Give unique and descriptive names to the threads created in application. - Add log entry in all thread at various entry and exit points in threads.
  • Change debugging config levels (debug, info, error etc) and analyze log messages.
  • When you find the class that is leaking out threads check how new threads are instantiated and how they're closed.
  • Make sure the thread is Guaranteed to close properly by doing following - Handling all Exceptions properly.
  • Make sure the thread is Guaranteed to close properly by doing following
-Handling all Exceptions properly.
-releasing all resources (e.g. connections, files etc) before it closes.

How will you take thread dump in Java? How will you analyze Thread dump?

Ans: A Thread Dump is a complete list of active threads. A java thread dump is a way of finding out what each thread in the JVM is doing at a particular point of time. This is especially useful when your java application seems to have some performance issues. Thread dump will help you to find out which thread is causing this. There are several ways to take thread dumps from a JVM. It is highly recommended to take more than 1 thread dump and analyze the results based on it. Follow below steps to take thread dump of a java process

•Step 1

On UNIX, Linux and Mac OSX Environment run below command:

ps -el | grep java

On Windows:

Press Ctrl+Shift+Esc to open the task manager and find the PID of the java process

•Step 2:

Use jstack command to print the Java stack traces for a given Java process PID

jstack [PID]


Why are wait(), notify() and notifyAll() methods defined in the object class?

Ans: The purpose of the wait(), notify() and notifyAll() methods is to temporarily pause and resume the execution of code in an object. Typically the host object is not in a state where it can proceed with a method call it has been given and the thread of execution must literally wait for the object to return to a ready state. A common example would be a limited pool or store of objects where you must wait for a storage slot to be released or an object to be returned to the pool before you can use it.

public synchronized Object getNextObject() {

// Waiting loop
while (! objectAvailable()) {

try {

wait();
}
catch (InterruptedException e) {

// Handle exception
}
}

// No longer waiting, get the return object
Object returnObject;

// Assign the returnObject from store

// Notify state change for other waiters
notify();

return returnObject;
}
The act of waiting is associated with the Object class because any subclass may need to wait for a ready state to occur (Java is fundamentally a multi-threaded language). The waiting process acts on a single thread of execution, but the wait mechanism expects that multiple threads may be waiting for the same object. The wait() and notify() methods are hosted by the Object class so that the Java Virtual Machine can manage the “wait set” of threads through the objects they are waiting for.

What is Starvation? What is a Livelock?

Starvation and livelock are much less common a problem than deadlock, but are still problems that every designer of concurrent software is likely to encounter.

LiveLock

Livelock occurs when all threads are blocked, or are otherwise unable to proceed due to unavailability of required resources, and the non-existence of any unblocked thread to make those resources available. In terms of Java API, thread livelock can occur in following conditions:
  • When all the threads in a program execute Object.wait(0) on an object with zero parameter. The program is live-locked and cannot proceed until one or more threads call Object.notify() or Object.notifyAll() on the relevant objects. Because all the threads are blocked, neither call can be made.
  • When all the threads in a program are stuck in infinite loops.
Starvation

Starvation describes a situation where a thread is unable to gain regular access to shared resources and is unable to make progress. This happens when shared resources are made unavailable for long periods by "greedy" threads. For example, suppose an object provides a synchronized method that often takes a long time to return. If one thread invokes this method frequently, other threads that also need frequent synchronized access to the same object will often be blocked. Starvation occurs when one thread cannot access the CPU because one or more other threads are monopolizing the CPU. In Java, thread starvation can be caused by setting thread priorities inappropriately. A lower-priority thread can be starved by higher-priority threads if the higher-priority threads do not yield control of the CPU from time to time.

What is the difference between sleep(), suspend() and wait()?

Ans:Thread.sleep() sends the current thread into the "Not Runnable" state for some amount of time. The thread keeps the monitors it has aquired -- i.e. if the thread is currently in a synchronized block or method no other thread can enter this block or method. If another thread calls t.interrupt() it will wake up the sleeping thread. Note that sleep is a static method, which means that it always affects the current thread (the one that is executing the sleep method). A common mistake is to call t.sleep() where t is a different thread; even then, it is the current thread that will sleep, not the t thread. t.suspend() is deprecated. Using it is possible to halt a thread other than the current thread. A suspended thread keeps all its monitors and since this state is not interruptable it is deadlock prone. object.wait() sends the current thread into the "Not Runnable" state, like sleep(), but with a twist. Wait is called on a object, not a thread; we call this object the "lock object." Before lock.wait() is called, the current thread must synchronize on the lock object; wait() then releases this lock, and adds the thread to the "wait list" associated with the lock. Later, another thread can synchronize on the same lock object and call lock.notify(). This wakes up the original, waiting thread. Basically, wait()/notify() is like sleep()/interrupt(), only the active thread does not need a direct pointer to the sleeping thread, but only to the shared lock object.

Q:What are native operating system threads?
Ans: Native operating system threads are those provided by the computer operating system that plays host to a Java application, be it Windows, Mac or GNU/Linux. Operating system threads enable computers to run many programs simultaneously on the same central processing unit (CPU) without clashing over the use of system resources or spending lots of time running one program at the expense of another. Operating system thread management is usually optimised to specific microprocessor architecture and features so that it operates much faster than Java green thread processing.

What is ThreadLocal class? How can it be used?

Ans:Below are some key points about ThreadLocal variables
  • A thread-local variable effectively provides a separate copy of its value for each thread that uses it.
  • ThreadLocal instances are typically private static fields in classes that wish to associate state with a thread
  • In case when multiple threads access a ThreadLocal instance, separate copy of Threadlocal variable is maintained for each thread.
  • Common use is seen in DAO pattern where the DAO class can be singleton but the Database connection can be maintained separately for each thread. (Per Thread Singleton) ThreadLocal variable are difficult to understand and I have found below reference links very useful in getting better understanding on them

Q:When InvalidMonitorStateException is thrown? Why?
Ans: This exception is thrown when you try to call wait()/notify()/notifyAll() any of these methods for an Object from a point in your program where u are NOT having a lock on that object.(i.e. u r not executing any synchronized block/method of that object and still trying to call wait()/notify()/notifyAll()) wait(), notify() and notifyAll() all throw IllegalMonitorStateException. since This exception is a subclass of RuntimeException so we r not bound to catch it (although u may if u want to). and being a RuntimeException this exception is not mentioned in the signature of wait(), notify(), notifyAll() methods.

Folder Option Not Visible In Tools Menu


Want to change your windows folder options such as Show hidden files or Hide extensions for know file types.
But my folder options is not visible. How to make folder options visible under tools menu.



Here is the solution:

Step 1 : Goto Start Menu and Select Run otpion.

Step 2 : Type gpedit.msc in run dialog box. Group Policy dialog box will be displayed.

Step 3 : In Group Policy dialog box in the left pane select
user configuration->administrative templates->windows components->windows explorer

Step 4 : In left pane double click on "Removes the folder options menu item from the tools menu".

Step 5 : Change its setting to disabled.

Step 6 : Close the Group Policy Dialog box.

Step 7 : Check tools menu in windows explorer.

enjoy.............

How do Java threads make the environment asynchrnous?


Ans: The thread mechanism in Java begins with the main entry point thread the runtime environment creates to start a Java program. When you use that initial thread create secondary threads, each one runs independently of the other. The Java virtual machine manages the execution of the threads so they behave as if they all run at the same time, in fact each thread briefly takes turns at execution.

In its simplest form there may be no communication or synchronization between multiple threads in a Java program and they each run to completion independently of each other. In this respect Java threads are fundamentally asynchronous, there is no master clock that governs when threads will run and when they synchronize variables to “catch-up” with each other.

It is often necessary and more useful if threads do check ready states before progressing, synchronize read and write access to shared variables and call-back to each other when their work is done. This is where the synchronized keyword and the various sleep(), wait() and notify() methods are used to more closely schedule the interaction between asynchronous threads.

Power On Your Computer With Mouse



Want to power on your computer?


Press Power Button on cabinet.


Is there any other way?


Yah...


Double Click with your mouse.


But for that you need to make some settings.


Here goes the settings.


Step 1 Restart your computer.


Step 2 Press DEL button (F2 in some motherboards) to goto the BIOS settings.


Step 3 Select Integrated Peripherals from main menu.


Step 4 If PS/2 mouse power on disabled, activate it by press page up/ page down key it will became Double-Click.


Step 5 Press Esc key to exit.


Step 6 Press F10 to save and exit Power off your PC.


Step 7 Now double-click the left mouse button,
.. Your PC will turn on


This trick may not work with some motherboards.



What are the advantages or usage of threads?

Ans)
Threads support concurrent operations. For example,
-- Multiple requests by a client on a server can be handled as an individual client thread.
-- Long computations or high-latency disk and network operations can be handled in the background without disturbing foreground computations or screen updates.

Threads often result in simpler programs.
-- In sequential programming, updating multiple displays normally requires a big while-loop that performs small parts of each display update. Unfortunately, this loop basically simulates an operating system scheduler. In Java, each view can be assigned a thread to provide continuous updates.
-- Programs that need to respond to user-initiated events can set up service routines to handle the events without having to insert code in the main routine to look for these events.

Threads provide a high degree of control.
-- Imagine launching a complex computation that occasionally takes longer than is satisfactory. A "watchdog" thread can be activated that will "kill" the computation if it becomes costly, perhaps in favor of an alternate, approximate solution. Note that sequential programs must muddy the computation with termination code, whereas, a Java program can use thread control to non-intrusively supervise any operation.

Threaded applications exploit parallelism.
-- A computer with multiple CPUs can literally execute multiple threads on different functional units without having to simulating multi-tasking ("time sharing").
-- On some computers, one CPU handles the display while another handles computations or database accesses, thus, providing extremely fast user interface response times.

Difference between Multithreading and Multiprocessing

Multi-threading refers to an application with multiple threads running within a process, while multi-processing refers to an application organised across multiple OS-level processes.
A thread is a stream of instructions within a process. Each thread has its own instruction pointer, set of registers and stack memory. The virtual address space is process specific, or common to all threads within a process. So, data on the heap can be readily accessed by all threads, for good or ill.
Multi-threading is a more "light weight" form of concurrency: there is less context per thread than per process. As a result thread lifetime, context switching and synchronisation costs are lower. The shared address space (noted above) means data sharing requires no extra work.
Multi-processing has the opposite benefits. Since processes are insulated from each other by the OS, an error in one process cannot bring down another process. Contrast this with multi-threading, in which an error in one thread can bring down all the threads in the process. Further, individual processes may run as different users and have different permissions.

Difference between multitasking multiprogramming and multithreading?

Multiprogramming is a rudimentary form of parallel processing in which several programs are run at the same time on a uniprocessor.Since there is only one processor, there can be no true simultaneous execution of different programs. Instead, the operating system executes part of one program, then part of another, and so on. To the user it appears that all programs are executing at the same time.

Multitasking, in an operating system, is allowing a user to perform more than one computer task (such as the operation of an application program) at a time. The operating system is able to keep track of where you are in these tasks and go from one to the other without losing information

Multithreading is the ability of a program or an operating system process to manage its use by more than one user at a time and to even manage multiple requests by the same user without having to have multiple copies of the program running in the computer

What is difference between thread and process?


 Ans) Differences between threads and processes are:-
1. Threads share the address space of the process that  created it; processes have their own address.
2. Threads have direct access to the data segment of its process; processes have their own copy of the data segment of the parent process.
3. Threads can directly communicate with other threads of its process; processes must use interprocess communication to communicate with sibling processes.
4. Threads have almost no overhead; processes have considerable overhead.
5. New threads are easily created; new processes require duplication of the parent process.
6. Threads can exercise considerable control over threads of the same process; processes can only exercise control over child processes.
7. Changes to the main thread (cancellation, priority change, etc.) may affect the behavior of the other threads of the process; changes to the parent process do not affect child processes. 

Questions Related to Thread


Q:What’s the difference between Thread and Runnable types?
Ans: Java Thread controls the main path of execution in an application. When you invoke the Java Virtual Machine with the java command, it creates an implicit thread in which to execute the main method. The Thread class provides a mechanism for the first thread to start-up other threads to run in parallel with it.
The Runnable interface defines a type of class that can be run by a thread. The only method it requires is run, which makes the interface very easy to to fulfil by extending existing classes. A runnable class may have custom constructors and any number of other methods for configuration and manipulation.


Q: If all methods are synchronized, is a class thread safe?
Ans: Even if all the methods of a class are synchronized, it may still be vulnerable to thread safety problems if it exposes non-final fields or its methods return mutable object references that could be manipulated by multiple threads. Non-final fields should be declared private and encapsulated with synchronization. Rather than return references to internal object fields, create an independent copy that has no relation to the original, known as a deep copy.
A deep copy of an object duplicates the content and state of the original object and all its constituent fields in such a way that none of its properties refer to instances in the original at any level.
These measures will help prevent uncontrolled access to the internal state of objects, but you must also ensure synchronization techniques are applied in a robust, consistent manner that will not cause deadlock or race conditions. It is generally better to use synchronized blocks than synchronized methods for performance reasons. Limit the extent of synchronized blocks and ensure they all use the same object monitor.

Q: What's the difference between a thread's start() and run() methods?
Ans: The separate start() and run() methods in the Thread class provide two ways to create threaded programs. The start() method starts the execution of the new thread and calls the run() method. The start() method returns immediately and the new thread normally continues until the run()method returns.
The Thread class' run() method calls the run() method of the Runnable type class passed to its constructor. Subclasses of Thread should override the run() method with their own code to execute in the second thread.
Depending on the nature of your threaded program, calling the Thread run() method directly can give the same output as calling via the start() method. Howevever, the code will only be executed in a new thread if the start() method is used.


Q: What is a Runnable object and a Runnable argument?
Ans: A Runnable object is one that implements the Runnable interface, which is the type used to execute new threads. The Runnable interface only has one method, run(), which must be implemented by a Runnable class.
In Java an argument is a primitive value or object reference that is passed to a constructor or method, defined in the method signature. A Runnable argument would be a constructor or method argument that is declared to be a Runnable type. The constructor of the Thread class is the most obvious example.
public Thread(Runnable target);
    
This constructor requires a Runnable type argument to be passed when a Thread is instantiated.


Q: What is a green thread?
Ans: A green thread refers to a mode of operation for the Java Virtual Machine (JVM) in which all code is executed in a single operating system thread. If a Java program has any concurrent threads, the JVM manages multi-threading behaviour internally rather than use additional operating system threads.
There is a significant processing overhead for the JVM to keep track of thread states and swap between them, so green thread mode has been deprecated and removed from more recent Java implementations. Current JVM implementations make more efficient use of native operating system threads. These days there is no case where the green thread approach is useful except on systems where this is the only concurrency scheme that is available for Java, on old operating systems and hardware platforms.


Q:What are the daemon threads? 
Ans: Daemon thread are service provider threads run in the background,these not used to run the application code generally.When all user threads(non-daemon threads) complete their execution the jvm exit the application whatever may be the state of the daemon threads. Jvm does not wait for the daemon threads to complete their execution if all user threads have completed their execution.
To create Daemon thread set the daemon value of Thread using setDaemon(boolean value) method. By default all the threads created by user are user thread. To check whether a thread is a Daemon thread or a user thread use isDaemon() method.
Example of the Daemon thread is the Garbage Collector run by jvm to reclaim the unused memory by the application. The Garbage collector code runs in a Daemon thread which terminates as all the user threads are done with their execution. 


Q:What happens if a start method is not invoked and the run method is directly invoked? 
Ans: If a thread has been instantiated but not started its is said to be in new state. Unless until a start() method is invoked on the instance of the thread, it will not said to be alive. If you do not call a start() method on the newly created thread instance thread is not considered to be alive. If the start() method is not invoked and the run() method is directly called on the Thread instance, the code inside the run() method will not run in a separate new thread but it will start running in the existing thread. 

ThreadGroup Class - Access Restriction Methods

The ThreadGroup class itself does not impose any access restrictions, such as allowing threads from one group to inspect or modify threads in a different group. Rather the Thread and ThreadGroup classes cooperate with security managers (subclasses of the SecurityManager class), which can impose access restrictions based on thread group membership.

The Thread and ThreadGroup class both have a method, checkAccess, which calls the current security manager's checkAccess method. The security manager decides whether to allow the access based on the group membership of the threads involved. If access is not allowed, the checkAccess method throws a SecurityException. Otherwise, checkAccess simply returns.

The following is a list of ThreadGroup methods that call ThreadGroup's checkAccess before performing the action of the method. These are what are known as regulated accesses, that is, accesses that must be approved by the security manager before they can be completed.
  • ThreadGroup(ThreadGroup parent, String name)
  • setDaemon(boolean isDaemon)
  • setMaxPriority(int maxPriority)
  • stop
  • suspend
  • resume
  • destroy
This is a list of the methods in the Thread class that call checkAccess before proceeding:
  • constructors that specify a thread group
  • stop
  • suspend
  • resume
  • setPriority(int priority)
  • setName(String name)
  • setDaemon(boolean isDaemon)
Related Posts:-

Some Unique Guinness World Records


1,253 Smurfs gathered in the high street in the town of Castleblayney in County Monaghan, Ireland on July 18, 2008. (Guinness World Records)

35,310 Lego Star Wars Clone Troopers in the UK.


The longest skis are 534 m long and were worn by 1,043 skiers in an event organized by Danske Bank on Drottninggatan in Örebro, Sweden, on 13 September 2008.

World's biggest pickup truck - 2002




Surrey resident Sarwan Singh achieved a feat, which every Sikh is going to be proud of. He set a new Guinness Book of World Record by having the longest beard.


The largest pocket knife was designed by Telmo Cadavez and hand made by Virgilio, Raul and Manuel Pires of Portugal. The knife is 3.9m long when open and weighs 122kg.





The largest commercially available hamburger is 74.75 kg (164.8 lbs) and is available for US$399 (£271.55) on the menu at Mallie's Sports Grill & Bar in Southgate, Michigan, USA, as of 29 August 2008.


In Germany, Anita Schwarz set a new record for carrying the most steins of lager over 40m. She staggered across the finishing line holding 19 glasses.


Coke & Mentos Guiness world record With 1,911 explosions in Riga, Latvia.






ThreadGroup Class- Methods that Operate on all Threads within a Group

The ThreadGroup class has three methods that allow you to modify the current state of all the threads within that group:

  • resume
  • stop
  • suspend
These methods apply the appropriate state change to every thread in the thread group and its subgroups.

Related Posts:-

ThreadGroup Class - Methods that Operate on the Group

The ThreadGroup class supports several attributes that are set and retrieved from the group as a whole. These attributes include the maximum priority that any thread within the group can have, whether the group is a "daemon" group, the name of the group, and the parent of the group.

The methods that get and set ThreadGroup attributes operate at the group level. They inspect or change the attribute on the ThreadGroup object, but do not affect any of the threads within the group. The following is a list of ThreadGroup methods that operate at the group level:
  • getMaxPriority and setMaxPriority
  • getDaemon and setDaemon
  • getName
  • getParent and parentOf
  • toString
For example, when you use setMaxPriority to change a group's maximum priority, you are only changing the attribute on the group object; you are not changing the priority of any of the threads within the group. Consider the following program that creates a group and a thread within that group:

class MaxPriorityTest {
public static void main(String[] args) {

ThreadGroup groupNORM = new ThreadGroup(
"A group with normal priority");
Thread priorityMAX = new Thread(groupNORM,
"A thread with maximum priority");

// set Thread's priority to max (10)
priorityMAX.setPriority(Thread.MAX_PRIORITY);

// set ThreadGroup's max priority to normal (5)
groupNORM.setMaxPriority(Thread.NORM_PRIORITY);

System.out.println("Group's maximum priority = " +
groupNORM.getMaxPriority());
System.out.println("Thread's priority = " +
priorityMAX.getPriority());
}
}

When the ThreadGroup groupNORM is created, it inherits its maximum priority attribute from its parent thread group. In this case, the parent group priority is the maximum (MAX_PRIORITY) allowed by the Java runtime system. Next the program sets the priority of the priorityMAX thread to the maximum allowed by the Java runtime system. Then the program lowers the group's maximum to the normal priority (NORM_PRIORITY). The setMaxPriority method does not affect the priority of the priorityMAX thread, so that at this point, the priorityMAX thread has a priority of 10, which is greater than the maximum priority of its group, groupNORM. This is the output from the program:
Group's maximum priority = 5
Thread's priority = 10

As you can see a thread can have a higher priority than the maximum allowed by its group as long as the thread's priority is set before the group's maximum priority is lowered. A thread group's maximum priority is used to limit a thread's priority when the thread is first created within a group or when you use setPriority to change the thread's priority. Note that setMaxPriority does change the maximum priority of all of its descendant-threadgroups.

Similarly, a group's daemon status applies only to the group. Changing a group's daemon status does not affect the daemon status of any of the threads in the group. Furthermore, a group's daemon status does not in any way imply the daemon status of its threads--you can put any thread within a daemon thread group. The daemon status of a thread group simply indicates that the group will be destroyed when all of its threads have been terminated.

Related Posts:-

ThreadGroup Class - Collection Management Methods


The ThreadGroup provides a set of methods that manage the threads and subgroups within the group and allow other objects to query the ThreadGroup for information about its contents. For example, you can call ThreadGroup's activeCount method to find out the number of active threads currently in the group. The activeCount method is often used with the enumerate method to get an array filled with references to all the active threads in a ThreadGroup. For example, the listCurrentThreads method in the following example fills an array with all of the active threads in the current thread group and prints their names:

class EnumerateTest {
void listCurrentThreads() {
ThreadGroup currentGroup = Thread.currentThread().getThreadGroup();
int numThreads;
Thread[] listOfThreads;


numThreads = currentGroup.activeCount();
listOfThreads = new Thread[numThreads];
currentGroup.enumerate(listOfThreads);
for (int i = 0; i < numThreads; i++) {
System.out.println("Thread #" + i + " = " + listOfThreads[i].getName());
}
}
}
Other collection management methods provided by the ThreadGroup class include activeGroupCount and list.

Related Posts:-

Java - ThreadGroup Class

The ThreadGroup class manages groups of threads for Java applications. A ThreadGroup can contain any number of threads. The threads in a group are generally related in some way, such as who created them, what function they perform, or when they should be started and stopped.

ThreadGroups can contain not only threads but also other ThreadGroups. The top-most thread group in a Java application is the thread group named main. You can create threads and thread groups in the main group. You can also create threads and thread groups in subgroups of main. The result is a root-like hierarchy of threads and thread groups:


The ThreadGroup class has methods that can be categorized as follows:

Java - Thread Group

Every Java thread is a member of a thread group. Thread groups provide a mechanism for collecting multiple threads into a single object and manipulating those threads all at once, rather than individually. For example, you can start or suspend all the threads within a group with a single method call. Java thread groups are implemented by the ThreadGroup class in the java.lang package.

The runtime system puts a thread into a thread group during thread construction. When you create a thread, you can either allow the runtime system to put the new thread in some reasonable default group or you can explicitly set the new thread's group. The thread is a permanent member of whatever thread group it joins upon its creation--you cannot move a thread to a new group after the thread has been created.

The Default Thread Group

If you create a new Thread without specifying its group in the constructor, the runtime system automatically places the new thread in the same group as the thread that created it (known as the current thread group and the current thread, respectively). So, if you leave the thread group unspecified when you create your thread, what group contains your thread?
When a Java application first starts up, the Java runtime system creates a ThreadGroup named main. Unless specified otherwise, all new threads that you create become members of the main thread group.

Many Java programmers ignore thread groups altogether and allow the runtime system to handle all of the details regarding thread groups. However, if your program creates a lot of threads that should be manipulated as a group, or if you are implementing a custom security manager, you will likely want more control over thread groups.

Creating a Thread Explicitly in a Group

As mentioned previously, a thread is a permanent member of whatever thread group it joins when its created--you cannot move a thread to a new group after the thread has been created. Thus, if you wish to put your new thread in a thread group other than the default, you must specify the thread group explicitly when you create the thread. The Thread class has three constructors that let you set a new thread's group:

public Thread(ThreadGroup group, Runnable target)
public Thread(ThreadGroup group, String name)
public Thread(ThreadGroup group, Runnable target, String name)

Each of these constructors creates a new thread, initializes it based on the Runnable and String parameters, and makes the new thread a member of the specified group. For example, the following code sample creates a thread group (myThreadGroup) and then creates a thread (myThread) in that group.

ThreadGroup myThreadGroup = new ThreadGroup("My Group of Threads");
Thread myThread = new Thread(myThreadGroup, "a thread for my group");

The ThreadGroup passed into a Thread constructor does not necessarily have to be a group that you create--it can be a group created by the Java runtime system, or a group created by the application in which your applet is running.

Getting a Thread's Group
To find out what group a thread is in, you can call its getThreadGroup method:
theGroup = myThread.getThreadGroup();

Thread - Deadlock

There are situations when programs become deadlocked when each thread is waiting on a resource that cannot become available. The simplest form of deadlock is when two threads are each waiting on a resource that is locked by the other thread. Since each thread is waiting for the other thread to relinquish a lock, they both remain waiting forever in the Blocked-for-lock-acquisition state. The threads are said to be deadlocked.

Thread t1 at tries to synchronize first on string o1 and then on string o2. The thread t2 does the opposite. It synchronizes first on string o2 then on string o1. Hence a deadlock can occur as explained above.

Below is a program that illustrates deadlocks in multithreading applications

public class DeadLockExample {

String o1 = "Lock ";
String o2 = "Step ";
Thread t1 = (new Thread("Printer1") {

public void run() {
while (true) {
synchronized (o1) {
synchronized (o2) {
System.out.println(o1 + o2);
}
}
}
}
});
Thread t2 = (new Thread("Printer2") {

public void run() {
while (true) {
synchronized (o2) {
synchronized (o1) {
System.out.println(o2 + o1);
}
}
}
}
});
public static void main(String[] args) {
DeadLockExample dLock = new DeadLockExample();
dLock.t1.start();
dLock.t2.start();
}
}

Java - Thread Joining

A thread invokes the join() method on another thread in order to wait for the other thread to complete its execution.
Consider a thread t1 invokes the method join() on a thread t2. The join() call has no effect if thread t2 has already completed. If thread t2 is still alive, then thread t1 transits to the Blocked-for-join-completion state.

Below is a program showing how threads invoke the overloaded thread join method.

public class ThreadJoinDemo {

public static void main(String[] args) {
Thread t1 = new Thread("T1");
Thread t2 = new Thread("T2");
try {
System.out.println("Wait for the child threads to finish.");
t1.join();
if (!t1.isAlive())
System.out.println("Thread T1 is not alive.");
t2.join();
if (!t2.isAlive())
System.out.println("Thread T2 is not alive.");
} catch (InterruptedException e) {
System.out.println("Main Thread interrupted.");
}
System.out.println("Exit from Main Thread.");
}
}

Output
Wait for the child threads to finish.
Thread T1 is not alive.
Thread T2 is not alive.
Exit from Main Thread.

Share

Twitter Delicious Facebook Digg Stumbleupon Favorites More